> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lean.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# Streaming

> Follow orders, positions, balances and market books over one WebSocket.

The stream pushes the same objects the REST API returns, as they change. One WebSocket carries
every channel you subscribe to, for one key, its trading account and its mode.

## Get a ticket

Your API key never travels over the socket. Exchange it for a ticket first:

```bash theme={"dark"}
curl -sS -X POST "$LEAN_API_URL/v1/ws/token" \
  -H "Authorization: Bearer $LEAN_API_KEY"
```

```json theme={"dark"}
{
  "success": true,
  "data": { "token": "<ticket>", "expires_at": "2026-11-01T20:25:00.000Z", "livemode": false },
  "meta": { "requestId": "<request id>" }
}
```

A ticket opens one connection and is good for 60 seconds, or until the key expires if that is
sooner. Request a new one for each connection,
including every reconnect. A `503` with `FEATURE_DISABLED` means streaming is not available right
now.

## Connect and authenticate

Open the WebSocket at `wss://api.lean.xyz/v1/ws`, the `/v1/ws` path on the same host as the REST
API. Test and live keys use the same URL; the ticket sets the mode. Within 10 seconds, send the
ticket as the first frame:

```json theme={"dark"}
{ "op": "auth", "ticket": "<ticket>" }
```

```json theme={"dark"}
{ "type": "authenticated", "livemode": false, "key_id": "<key id>" }
```

Every frame in both directions is one JSON text object. Frames you send must not carry fields
other than the ones shown here.

## Subscribe

```json theme={"dark"}
{
  "op": "subscribe",
  "channels": [
    { "channel": "orders" },
    { "channel": "positions" },
    { "channel": "balances" },
    { "channel": "book", "market_id": "mkt_..." }
  ]
}
```

The reply lists the channels you named:

```json theme={"dark"}
{
  "type": "subscribed",
  "channels": [
    { "channel": "orders" },
    { "channel": "positions" },
    { "channel": "balances" },
    { "channel": "book", "market_id": "mkt_..." }
  ]
}
```

Send `{"op":"unsubscribe","channels":[...]}` to stop a channel; the reply is an `unsubscribed`
frame. A connection holds at most 1000 channels; a frame must stay under 16 KB, so following
hundreds of books takes several `subscribe` frames. Send `{"op":"ping"}` at any time; the reply is
`{"type":"pong"}`.

Channels always follow the ticket's account and mode; no frame can name another. The `trades` and
`market_lifecycle` channels carry venue data, the same for live and test keys.

## Channels

| Channel | Frame | Holds |
| - | - | - |
| `orders` | `{"type":"order","order":{...}}` | Each new state of an order, as `GET /v1/orders/{id}` returns it. |
| `positions` | `{"type":"positions","positions":{...}}` | The whole `GET /v1/positions` result. |
| `balances` | `{"type":"balances","balances":{...}}` | The whole `GET /v1/balances` result. |
| `book` | `{"type":"book","market_id":"...","snapshot":true,"sequence":1,"book":{...}}`, then `{"type":"book_delta","market_id":"...","sequence":2,"prev_sequence":1,"delta":{...}}` | The combined order book of one market, then what changes in it. |
| `trades` | `{"type":"trades","ticker":"...","trades":[...],"timestamp":...}` | Trades on one venue listing as they happen. |
| `market_lifecycle` | `{"type":"market_lifecycle","event":"status_change",...}` | Status and tick size changes of one venue listing. |

### Orders

Each order's states only move forward. The channel sends states that happen after you subscribe,
so call `GET /v1/orders` once after `subscribed` to cover anything earlier.

The channel never drops a frame while the connection stays open. If Lean cannot be sure every
frame reached you, it closes the connection with `1013` and `UPSTREAM_ERROR`, so reconnect and call
`GET /v1/orders` again. A frame carries the order as it is when Lean sends it, so an order that
fills as it is placed, such as an `ioc` order, can arrive first as `filled` with no `pending` frame
before it.

Only orders placed with `POST /v1/orders` send `order` frames. The sales that stop losses, limit
chases and conditional sells make are not API orders: follow them by reading that object, and
through the `positions` and `balances` frames. Their fills are listed in `GET /v1/fills` with
`order_id` set to `null`.

### Positions and balances

Each frame is a whole state that replaces the one before it. The newest state arrives first, then
each change. They are sent after every order change on the account and refreshed about every ten
seconds otherwise.

### Book

A book frame holds one market's book across every venue that lists it, at a depth of 20 levels
per side. `market_id` takes a market ID or a [venue symbol](https://docs.lean.xyz/markets.md#venue-symbols); a symbol's
channel holds only the listing it names, under the market's ID. Each frame's top level
`market_id` is the ID or symbol you subscribed with, so you can follow one market under several
names and still tell their frames apart:

```json theme={"dark"}
{
  "type": "book",
  "market_id": "<market ID or venue symbol you subscribed with>",
  "snapshot": true,
  "sequence": 1841,
  "book": {
    "market_id": "mkt_...",
    "venues": [
      {
        "venue": "polymarket",
        "ticker": "<venue ticker>",
        "side": "yes",
        "bids": [{ "price": "0.52", "quantity": "100" }],
        "asks": [{ "price": "0.55", "quantity": "40" }],
        "bid_quantity": "100",
        "ask_quantity": "40",
        "bid_notional_usd": "52",
        "ask_notional_usd": "22"
      }
    ],
    "combined": {
      "bids": [
        { "price": "0.52", "quantity": "100", "venues": [{ "venue": "polymarket", "quantity": "100" }] }
      ],
      "asks": [
        { "price": "0.55", "quantity": "40", "venues": [{ "venue": "polymarket", "quantity": "40" }] }
      ]
    },
    "total_bid_quantity": "100",
    "total_ask_quantity": "40",
    "total_bid_notional_usd": "52",
    "total_ask_notional_usd": "22",
    "unavailable": [],
    "as_of": "2026-11-01T20:25:00.000Z",
    "livemode": false
  }
}
```

* Bids are what a sell fills against and asks are what a buy fills against, for the market's
  outcome. Prices and quantities are decimal strings.
* `combined` merges every venue's levels by price and shows each venue's share.
* Quantity and notional totals cover every level read, not only the 20 listed.
* A venue whose book was read but holds no orders appears in `venues` with no levels. A venue
  whose book could not be read appears in `unavailable` instead, once per venue.
* After the whole book, the channel sends `book_delta` frames with only the levels that changed.
  Each delta holds the changes since the book Lean last published, so a busy book can get several
  deltas within a few milliseconds or one delta covering many changes. A book with no change gets
  a delta with no levels about once a second. Where Lean has no live venue data it polls the
  venue about once a second.
* In a delta, each level replaces the level at its price on its side, and a `quantity` of `"0"`
  removes it. A level that falls out of the 20 shown is removed and one that comes into them is
  added. Venue books are matched by `venue`, `ticker` and `side`, and the totals and `as_of` are
  always the new book's. Keep bids highest price first and asks lowest price first.
* Apply a delta only when its `prev_sequence` equals the `sequence` of the book you hold, then hold
  its `sequence`. When a delta cannot follow, because your session read too slowly or the market's
  venues changed, Lean sends a whole `book` frame instead. If a delta still does not follow, drop
  the book, send `unsubscribe` for the channel, then `subscribe` again: the new subscription opens
  with a whole `book` frame. The official SDKs apply deltas for you and always hand you the
  whole book. See [WebSocket](https://docs.lean.xyz/api-reference/streaming/websocket.md#book).
* `as_of` is when Lean built the book, not when you received it.
* The first frame after you subscribe has `snapshot` set to `true`. It is the newest book Lean
  already holds, so on a quiet book its `as_of` can be up to about a second before you subscribed.
  The book is still current: Lean replaces it as soon as a venue book changes. Every later `book`
  frame has `snapshot` set to `false`; `book_delta` frames carry no `snapshot` field. Both are
  built as they are sent. To measure delay, skip the snapshot
  frame. Subscribing again to a channel you already have changes nothing, so it sends no new
  snapshot; unsubscribe first to get one.
* Each `book` frame replaces the book you hold.
* When a book channel will send no more books, it sends one `book_ended` frame and the session
  stops following it. `reason` is `unknown_market` for a market that does not exist or a symbol
  that names more than one market, and `market_closed` once every venue listing of the market is
  closed or resolved. See [WebSocket](https://docs.lean.xyz/api-reference/streaming/websocket.md#book).

The book channel and
[`GET /v1/markets/{id}/book`](https://docs.lean.xyz/api-reference/markets/retrieve-market-book) agree on which venues
make up a market, how levels are merged and what counts as empty or unavailable. They read venue
books differently, so these differences are expected:

* The channel builds every venue's book from the venue data Lean ingests. The REST endpoint reads
  that data for `polymarket_us` and `lighter`, but reads `polymarket`, `kalshi` and `hyperliquid`
  books from the venue when called. For those three, the two can differ for the moment a venue
  book change takes to reach Lean.
* The first frame waits up to 3 seconds for every venue's book. A venue whose book has not arrived
  by then appears in `unavailable` and fills in on a later frame. A Polymarket market Lean has
  just started following takes a few seconds longer.
* A Polymarket market that is not open and tradable in Lean's catalog is not ingested, so the
  channel lists Polymarket in `unavailable` even where the REST endpoint can still read its book.

A session that reads positions, balances or books too slowly skips ahead to the newest state.

### Trades and market lifecycle

These channels follow one venue listing, named by its leg `ticker` as a market's `legs[].ticker`
shows it, such as a Kalshi market ticker or a `pm:…` ticker:

```json theme={"dark"}
{
  "op": "subscribe",
  "channels": [
    { "channel": "trades", "ticker": "<venue ticker>" },
    { "channel": "market_lifecycle", "ticker": "<venue ticker>" }
  ]
}
```

* `trades` sends the trades that happen after you subscribe, a batch per frame, with the venue's
  price, side, maker and taker details. It sends no history; read
  [recent trades](https://docs.lean.xyz/markets.md#recent-trades) for that.
* `market_lifecycle` sends a `status_change` frame when the listing's status changes, with
  `result` once it resolves, and a `tick_size_change` frame when its price step changes. The first
  frame can repeat the current state.
* Only the ticker's shape is checked. A ticker no venue lists is accepted and sends nothing, and a
  Polymarket condition ID, token ID or Hyperliquid coin is not resolved to a ticker as a `book`
  channel resolves it.
* These channels never skip a frame. A session that reads them too slowly is closed with `1013`
  and `RATE_LIMITED`; reconnect, subscribe again and read the current state over REST.

See [WebSocket](https://docs.lean.xyz/api-reference/streaming/websocket.md#trades) for every field.

## Errors and closing

After authentication, a bad frame is answered with an error frame and the connection stays open:

```json theme={"dark"}
{ "type": "error", "code": "VALIDATION_ERROR", "message": "Unrecognized frame" }
```

Before authentication, Lean accepts only an `auth` frame. Any other frame gets one error frame and
then the socket closes. A `ping`, `subscribe` or `unsubscribe` sent first gets `UNAUTHORIZED` with
`Authenticate before any other frame`. Text that is not JSON, or not a frame shown here, gets
`VALIDATION_ERROR` with `Expected an auth frame`. Both close with `1008`. See
[WebSocket errors](https://docs.lean.xyz/api-reference/streaming/websocket.md#errors) for every message.

When the connection must end, Lean sends the error frame and then closes the socket:

| Close code | `code` | When |
| - | - | - |
| `1008` | `UNAUTHORIZED` | The ticket is invalid, expired or already used; no `auth` frame arrived within 10 seconds; a `ping`, `subscribe` or `unsubscribe` came before `auth`; or the key was revoked or expired. |
| `1008` | `VALIDATION_ERROR` | Before authentication, a frame was not JSON or not a frame shown here. |
| `1003` | `VALIDATION_ERROR` | A binary frame was sent, before or after authentication. |
| `1013` | `RATE_LIMITED` | In reply to `auth`: the key already has 500 open streams. |
| `1013` | `RATE_LIMITED` | The session read order states, trades or lifecycle events too slowly to keep up. |
| `1013` | `UPSTREAM_ERROR` | In reply to `auth`: Lean could not check whether the ticket was already used. |
| `1013` | `UPSTREAM_ERROR` | Order updates were interrupted inside Lean, so some may not have reached the session. Only sessions subscribed to `orders`, or sending a `subscribe` that names it, close this way; that `subscribe` gets no `subscribed` reply. |
| `1012` | none | Lean is restarting. |
| `1001` | none | Nothing arrived from the client for 45 seconds, not even a pong to Lean's pings. The close reason is `no frames from client`. |

Lean sends a WebSocket ping every 15 seconds, and any frame from the client counts, a pong
included. Most WebSocket libraries answer pings on their own; sending `{"op":"ping"}` every 10
seconds, as [Notice a lost connection](#notice-a-lost-connection) suggests, also keeps the
connection open.

Revoking a key closes its open streams with `1008` and `UNAUTHORIZED`. Pausing trading on an
account does not close streams, since they only read.

## Reconnecting

Connections end: Lean restarts and moves streams between servers, networks drop, and tickets
expire. Plan for it. Frames that would have been sent while you were disconnected are not sent
later, so a reconnect always rebuilds state from fresh data.

### Notice a lost connection

A connection can stop delivering frames without closing. Send `{"op":"ping"}` every 10 seconds.
If no frame of any kind, `pong` included, arrives for 25 seconds, close the socket and reconnect.
Treat a socket that has not answered `auth` with `authenticated` within 15 seconds the same way.

### Wait before retrying

Wait a random delay between zero and `min(30 seconds, 0.5 seconds × 2^attempt)` before each
attempt, where `attempt` counts from zero. The random spread keeps many clients that lost their
connections together from retrying together. Reset `attempt` to zero once a connection has stayed
authenticated for 15 seconds.

### Reconnect

1. Get a new ticket from `POST /v1/ws/token`. A ticket works once, so never reuse one.
2. Open `/v1/ws` and send the `auth` frame.
3. After `authenticated`, send `subscribe` frames naming every channel you want, splitting the
   list so each frame stays under 16 KB. Lean keeps nothing from the old connection.
4. Rebuild state from what arrives:
   * **Books:** mark each book stale when the connection drops. The first `book` frame for that
     market replaces it, and its deltas follow from there.
   * **Positions and balances:** the newest state arrives first after `subscribed` and replaces
     yours.
   * **Orders:** after `subscribed`, call `GET /v1/orders` and merge it with the order frames you
     receive. For each order keep the copy with the latest `updated_at`.

### Which closes to retry

| What happened | What to do |
| - | - |
| Close `1012` | Lean is restarting. Reconnect with a new ticket after the delay. |
| Close `1001` | Nothing came from your client for 45 seconds. Reconnect with a new ticket after the delay, and answer pings or send `{"op":"ping"}`. |
| Close `1013` with `RATE_LIMITED` | Reconnect with a new ticket after the delay, and read frames faster. If it came in reply to `auth`, close another stream on the key first. |
| Close `1013` with `UPSTREAM_ERROR` | Lean could not check the ticket, or order updates were interrupted. Reconnect with a new ticket after the delay, subscribe again and call `GET /v1/orders`. |
| Any other close, or no close at all | Reconnect with a new ticket after the delay. |
| The upgrade answered HTTP `502`, `503` or `504`, or no connection could be made | Retry with a new ticket after the delay. |
| `POST /v1/ws/token` answered `5xx` or did not answer | Retry it after the delay. No new connection can start until it succeeds. |
| Close `1008` | The ticket or the key was refused. Try once more with a new ticket. Stop after three `1008` closes in a row. |
| `POST /v1/ws/token` answered `401` or `403` | The key is revoked, expired or lacks access. Stop and fix the key. |

### What to expect

* While you reconnect, no frames arrive. Most reconnects take a few seconds, longer during an
  outage. Show data as stale until its first frame after the reconnect.
* Lean never replays missed frames. Books, positions and balances recover with their next frame;
  orders recover through `GET /v1/orders`.
* Your client cannot tell which server it reached, and does not need to: tickets, channels and
  frames behave the same on every connection.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.