# QuantConnect LEAN tutorial: CLI, Docker and local runs

URL: https://fincodelabs.com/en/blog/quantconnect-lean-tutorial · Publisher: Fincode (Fincode Yazılım ve Teknoloji A.Ş.), Istanbul, Turkey · Category: Trading bots · Published: 2026-11-26 · Updated: 2026-11-26

QuantConnect LEAN tutorial, tested 26 Nov 2026: the Apache-2.0 engine, why the CLI needs a login and Docker, a pre-flight script, and where setups fail.

**Short answer:** **QuantConnect LEAN** is an open-source, event-driven trading engine in C# with Python support, published under the Apache 2.0 license. The usual way to run it locally is the LEAN CLI (`pip install lean`), which runs the engine in Docker; on 26 November 2026 its `lean init` step asked for a QuantConnect user ID and API token, and the documentation says the CLI needs a paid-tier organization. Building the engine from source with the .NET 10 SDK uses a local configuration with no API token by default.

This guide comes from the LEAN repository, the LEAN CLI documentation and QuantConnect's tier pages, read on 26 November 2026, and from installing LEAN CLI 1.0.234 in a clean Python 3.11 virtual environment on Windows 11 the same day.

The engine itself was not run here, and the reasons are part of the answer. Nothing below is a strategy or a performance figure, this guide recommends neither the software nor any broker, and automated trading can lose money.

## What QuantConnect LEAN is: engine, CLI and cloud

LEAN is the engine; the LEAN CLI and the QuantConnect cloud are separate products built around it, with different terms.

**The three pieces, as described on official pages read 26 November 2026**

| Piece | What it is | License or access |
| --- | --- | --- |
| LEAN engine (GitHub QuantConnect/Lean) | Event-driven backtesting and live-trading engine; algorithms in C# or Python | Apache License 2.0; default branch `master`, last push 25 November 2026 |
| LEAN CLI (PyPI package `lean`) | Python command-line tool that runs the engine in Docker for backtests, optimization, research and live trading | Code under Apache 2.0; the documentation says you must be a member of an organization on a paid tier to use it |
| QuantConnect cloud | Hosted IDE, backtest nodes, live nodes and data | Free tier plus paid tiers (Quant Researcher, Team, Trading Firm, Institution) |

The license covers the code. It does not give you market data, and it does not remove the CLI's account requirement.

If you are still choosing a framework, the comparison of [Python backtesting libraries](https://fincodelabs.com/en/blog/backtesting-python-libraries) and the [NautilusTrader guide](https://fincodelabs.com/en/blog/nautilus-trader-python) cover engines with different trade-offs.

## How to install the LEAN CLI: what ran on 26 November 2026

The install works without an account, but everything that touches the engine stopped at the login prompt or the missing `lean.json`.

**LEAN CLI 1.0.234, Python 3.11, Windows 11, Docker 29.4.0 running, 26 November 2026**

| Command | Result |
| --- | --- |
| `pip install lean` | Installed 1.0.234 (PyPI upload 18 November 2026) with `quantconnect-stubs` 18294 for autocomplete |
| `lean --help` | Listed 25 commands (two are aliases), including `backtest`, `data`, `live`, `optimize` and `research` |
| `lean init` | Printed a news box, then asked for a QuantConnect user ID and API token; with no input it aborted |
| `lean project-create --language python Demo` | Worked offline: `main.py`, `config.json`, `research.ipynb` and editor folders |
| `lean data generate --start 20240101 --symbol-count 1` | Refused: needs a Lean configuration file from `lean init` |
| `lean backtest Demo` | Refused for the same reason |
| `lean whoami` | "You are not logged in" |

The CLI source confirms it: `lean init` validates credentials, and `data generate` is declared as needing a Lean config and Docker.

## Three ways to run LEAN locally

You can run LEAN through the CLI with Docker, build it from source, or use the hosted cloud, and each route has a different obstacle.

**Routes and what each needs, from official pages read 26 November 2026**

| Route | Needs | Main obstacle |
| --- | --- | --- |
| LEAN CLI + Docker | Python, `pip install lean`, Docker running, `lean login`, `lean init` | Paid-tier organization per the docs; the `quantconnect/lean` amd64 image was a 14.05 GB compressed download on Docker Hub (tag 18294, 25 November 2026) |
| Build from source | .NET 10 SDK, the repository, `dotnet build QuantConnect.Lean.sln`, then `dotnet QuantConnect.Lean.Launcher.dll` | For Python algorithms: Python 3.11 with `PYTHONNET_PYDLL` pointing at the Python library, pandas 2.2.3 and wrapt 1.16.0, per the Algorithm.Python readme |
| QuantConnect cloud | An account | Your code and backtests run on QuantConnect's servers under its terms |

The repository README recommends the CLI for most users. The README and the Launcher project file (`net10.0`) call for .NET 10; QuantConnect's LEAN engine getting-started page still named dotnet 9 (Mac) and dotnet 6 (Linux) on 26 November 2026, so follow the repository. The source route asks for no QuantConnect login in its default configuration: the stock `Launcher/config.json` sets `job-user-id` to 0, leaves `api-access-token` empty and points `data-folder` at the repository's `Data` folder, which holds sample SPY minute data for 4 to 11 October 2013 and one day in August 2023. The test machine had .NET runtimes but no SDK, so the source build was not tried; installing an SDK is a system change to make deliberately.

No prices are quoted here: the pricing page loaded them with JavaScript and the tier-features documentation lists none, so check the pricing page on the day you decide.

## A LEAN pre-flight check to run before lean backtest

Most first-run failures come from Docker, disk space or the workspace files, and a short script can check all of them before a 14 GB pull.

```python
import pathlib, re, shutil, subprocess, sys

IMAGE = "quantconnect/lean:latest"
NEED_GB = 30  # your own margin; the amd64 image alone was a 14.05 GB compressed download (Docker Hub, 26 Nov 2026)

def run(*args):
    """Return (ok, text); never raises for a missing binary or a hung daemon."""
    try:
        p = subprocess.run(args, capture_output=True, text=True, timeout=30)
    except FileNotFoundError:
        return False, "not found on PATH"
    except subprocess.TimeoutExpired:
        return False, "no answer within 30 s"
    return p.returncode == 0, (p.stdout or p.stderr).strip()

def check(workspace="."):
    ws = pathlib.Path(workspace).resolve()
    if not ws.is_dir():
        return [("Workspace", False, f"{ws} is not a folder")]
    results = []
    ok, out = run("docker", "version", "--format", "{{.Server.Version}}")
    results.append(("Docker daemon", ok, out if ok else "Docker not running or not installed: " + out[:80]))
    if ok:
        has, out = run("docker", "image", "inspect", IMAGE, "--format", "{{.Size}}")
        size = f"present, Size {int(out) / 1e9:.1f} GB" if has and out.isdigit() else "not pulled yet"
        results.append(("Engine image", has, f"{IMAGE}: {size}"))
    free = shutil.disk_usage(ws).free / 1e9
    results.append(("Free disk", free >= NEED_GB, f"{free:.0f} GB free, margin set to {NEED_GB} GB"))
    try:
        text = (ws / "lean.json").read_text(encoding="utf-8")
    except FileNotFoundError:
        results.append(("lean.json", False, "missing: run lean login, then lean init in an empty folder"))
    except (OSError, ValueError) as e:
        results.append(("lean.json", False, f"unreadable: {e.__class__.__name__}"))
    else:
        # a real lean.json has // comments, so json.loads fails on it; drop comment lines, match the keys
        text = "\n".join(l for l in text.splitlines() if not l.lstrip().startswith("//"))
        ids = {v.strip() for v in re.findall(r'"(?:job-)?organization-id"\s*:\s*"([^"]*)"', text)} - {""}
        note = {0: "present but no organization id", 1: "organization id set"}.get(len(ids), "conflicting ids")
        results.append(("lean.json", len(ids) == 1, note))
    cred = pathlib.Path.home() / ".lean" / "credentials"
    results.append(("Credentials", cred.is_file(), str(cred) if cred.is_file() else "not logged in"))
    return results

if __name__ == "__main__":
    rows = check(sys.argv[1] if len(sys.argv) > 1 else ".")
    for name, ok, note in rows:
        print(f"{'OK  ' if ok else 'FAIL'} {name:<13} {note}")
    sys.exit(0 if all(ok for _, ok, _ in rows) else 1)
```

Saved as `lean_preflight.py` and run against the folder where `project-create` had worked, it printed this on 26 November 2026 and exited with status 1:

```
OK   Docker daemon 29.4.0
FAIL Engine image  quantconnect/lean:latest: not pulled yet
OK   Free disk     311 GB free, margin set to 30 GB
FAIL lean.json     missing: run lean login, then lean init in an empty folder
FAIL Credentials   not logged in
```

> **Paths tested on 26 November 2026 (synthetic files, no real account):** Docker not on PATH; a command that hangs past the 30-second timeout; a command that exits non-zero; an image that exists locally; `lean.json` missing, not UTF-8, a JSON list, with a blank ID, with two different IDs, with a commented-out old ID above the real one, and the repository's real `config.json` with `//` comments plus an ID line; and a workspace path that does not exist. Each produced the expected line instead of a traceback.

The `Size` that `docker image inspect` reports can be the compressed content size rather than space used, so leave a margin of your own.

## How a QuantConnect Python algorithm is structured

A LEAN Python algorithm is a class derived from `QCAlgorithm` that sets dates, cash and subscriptions in `initialize` and receives each time slice of data in `on_data`.

This is the skeleton `lean project-create` generated, with the import region and comments removed and the trading line replaced:

```python
class Demo(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2013, 10, 7)
        self.set_end_date(2013, 10, 11)
        self.set_cash(100000)
        self.add_equity("SPY", Resolution.MINUTE)

    def on_data(self, data: Slice):
        ...  # the generated file buys SPY here; replace it with your own rules
```

The engine owns the loop: it reads data, builds a `Slice` for each time step, calls your method, and passes orders to modelled fills, fees and brokerage behaviour, which are pluggable components. The dates in the template match the SPY sample data in the repository, which is why a fresh project covers only those days until you add data.

For synthetic data, `lean data generate` builds random prices with a Brownian motion model, for Equity, Forex, CFD, Future and Crypto from tick to daily resolution and Options at minute resolution, at three densities. The documentation presents it as a way to design and test algorithms without buying real data; it is random by construction, so it tells you nothing about real markets. Use it to test plumbing, as described in [how to test trading bots](https://fincodelabs.com/en/blog/how-to-test-trading-bots), and read [backtesting pitfalls](https://fincodelabs.com/en/blog/backtesting-trading-strategy-pitfalls) before trusting any result on real data.

## Brokerages and data providers LEAN lists

The LEAN CLI documentation lists 21 named live-trading brokerages plus a category for CFD and forex brokerages, as of 26 November 2026.

**Live-trading brokerages named on the LEAN CLI brokerages page, read 26 November 2026**

| Group | Names as listed |
| --- | --- |
| Paper | QuantConnect Paper Trading |
| Stock, options and futures brokers | Interactive Brokers, TradeStation, Tastytrade, Public, Alpaca, Charles Schwab, Clear Street, Webull, Tradier, Samco, Zerodha |
| Crypto venues | Binance, Bybit, Kraken, Coinbase, Bitfinex, dYdX |
| Institutional routing | Bloomberg EMSX, SSC Eze, Trading Technologies |

The grouping is ours; the names are the project's. A listing says a connector exists, not that your account type, your country or the broker's API terms allow its use. Account types and API access vary, and rules depend on where you live. For readers in Turkey: Article 99/A of Capital Markets Law No. 6362 treats activity by foreign crypto-asset platforms directed at Turkish residents as unauthorized. Naming these firms here does not mean Fincode integrates them or has built on them, and it is not a recommendation.

Start with paper trading, as in the [paper trading API guide](https://fincodelabs.com/en/blog/paper-trading-api), and check broker specifics such as the [Interactive Brokers API](https://fincodelabs.com/en/blog/interactive-brokers-api-python) against the broker's own documentation.

## Where LEAN setups fail

Most LEAN setups fail on environment, account and data problems before any trading logic runs.

**Failure points from the LEAN CLI troubleshooting page and this test, 26 November 2026**

| Symptom | Cause | Fix |
| --- | --- | --- |
| "Please make sure Docker is installed and running" | Docker stopped, or the virtual environment cannot reach it | Start Docker; rerun with `--verbose`; reinstall Docker if its path is non-standard |
| "This command requires a Lean configuration file" | Command run outside the workspace | Run from the folder holding `lean.json` or pass `--lean-config` |
| "Docker wants access to <path>" | Windows legacy Hyper-V backend without file sharing | Share your temp folder and workspace in Docker's Resources settings |
| "Invalid credentials" or organization not found | Not logged in, or a wrong organization ID in `lean.json` | `lean login`; rerun `lean init` in an empty folder |
| Backtest has no data | Only the small sample data set is local | Generate, buy or import data and confirm its license allows your use |

One smaller warning sign: the news box `lean init` printed on 26 November 2026 still carried a 2021 item announcing FTX support, and its newest item was dated August 2022. Treat the reference documentation and CLI help as the current source.

Plan where the engine will run before going live; [trading bot hosting](https://fincodelabs.com/en/blog/trading-bot-hosting) covers servers, restarts and monitoring. Fincode's [algorithmic trading service page](https://fincodelabs.com/en/services/algorithmic-trading) describes how Fincode builds systems from rules the client writes; it is a general pointer only, and Fincode supplies no strategies.

## Frequently asked questions

### Is QuantConnect LEAN free?

The LEAN engine code is free under the Apache 2.0 license. On 26 November 2026 the LEAN CLI documentation said you must be a member of a paid-tier organization to use the CLI, and data is a separate cost.

### Can I run LEAN locally without a QuantConnect account?

The documented CLI route asks for a user ID and API token at lean init. Building the engine from source with the .NET 10 SDK uses a local config with no API token by default, but that route was not built in this test.

### Does the LEAN CLI need Docker?

Yes for local backtests, optimization, research, live trading and data generation. The quantconnect/lean amd64 image was a 14.05 GB compressed download on Docker Hub on 26 November 2026.

### Can LEAN backtest results predict live results?

No. A backtest models fills, fees and data, and live markets differ; LEAN's generated data is random by design. Automated trading can lose money.

## Sources

- [QuantConnect/Lean on GitHub: README (description, CLI, local installation, .NET 10 SDK)](https://github.com/QuantConnect/Lean)
- [QuantConnect/Lean LICENSE (Apache License 2.0)](https://github.com/QuantConnect/Lean/blob/master/LICENSE)
- [LEAN Algorithm.Python readme (Python 3.11, PYTHONNET_PYDLL, pandas, wrapt, stubs)](https://github.com/QuantConnect/Lean/tree/master/Algorithm.Python)
- [LEAN Launcher config.json (default local configuration)](https://github.com/QuantConnect/Lean/blob/master/Launcher/config.json)
- [LEAN CLI docs: Getting started (paid tier, Docker, login, init)](https://www.lean.io/docs/v2/lean-cli/key-concepts/getting-started)
- [LEAN CLI docs: Troubleshooting (common errors)](https://www.lean.io/docs/v2/lean-cli/key-concepts/troubleshooting)
- [LEAN CLI docs: Generating data (random Brownian motion data)](https://www.lean.io/docs/v2/lean-cli/datasets/generating-data)
- [LEAN CLI docs: Live trading brokerages](https://www.lean.io/docs/v2/lean-cli/live-trading/brokerages)
- [lean on PyPI (LEAN CLI releases)](https://pypi.org/project/lean/)
- [quantconnect/lean on Docker Hub (engine image tags and sizes)](https://hub.docker.com/r/quantconnect/lean)
- [QuantConnect docs: Organization tier features](https://www.quantconnect.com/docs/v2/cloud-platform/organizations/tier-features)
- [QuantConnect docs: LEAN engine getting started (local source build)](https://www.quantconnect.com/docs/v2/lean-engine/getting-started)
- [QuantConnect pricing](https://www.quantconnect.com/pricing/)

> This guide is general information about software and markets, not investment, legal or tax advice. Automated trading can lose money, past or backtested performance does not guarantee future results, and the rules that apply depend on your jurisdiction and your exchange's terms. Sources, checks and corrections: see the [editorial policy](https://fincodelabs.com/en/editorial-policy).

---

Published by Fincode (Fincode Yazılım ve Teknoloji A.Ş.), a software company in Istanbul, Turkey: https://fincodelabs.com/en/blog/quantconnect-lean-tutorial

Cite as: Fincode, "QuantConnect LEAN tutorial: CLI, Docker and local runs", updated November 26, 2026, https://fincodelabs.com/en/blog/quantconnect-lean-tutorial
