> ## 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.

# WebSocket

> Connect, authenticate and subscribe to the orders, positions, balances and book channels.

One WebSocket carries every channel you subscribe to, for one key, its trading account and its
mode. For reconnecting and rebuilding state, see the [Streaming guide](https://docs.lean.xyz/streaming.md).

## Connect

| | |
| - | - |
| URL | `wss://api.lean.xyz/v1/ws`, on the same host as the REST API |
| Frames | One JSON text object per frame, in both directions |
| Frame size | Keep each frame you send under 16 KB; a larger frame ends the connection |
| Channels | At most 1000 on one connection; split a long list across several `subscribe` frames |

Frames you send must not carry fields other than the ones shown on this page. Channels always
follow the ticket's account and mode; no frame can name another.

## Get a ticket

Your API key never travels over the socket. Exchange it for a ticket with
[Create a stream ticket](https://docs.lean.xyz/api-reference/streaming/create-stream-ticket.md):

```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": { "timestampMs": 1793564640000, "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.

## Authenticate

Within 10 seconds of opening the socket, 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>" }
```

Any other frame before `auth` closes the socket; see [Before authentication](#before-authentication).
A second `auth` frame on the same connection is answered with a `VALIDATION_ERROR` error frame and
the connection stays open.

## Subscribe and unsubscribe

Name one or more channels:

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

The reply lists the channels you named, each once:

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

To stop channels, send the same shape with `unsubscribe`. The reply is an `unsubscribed` frame
listing the channels you named, each once:

```json theme={"dark"}
{ "op": "unsubscribe", "channels": [{ "channel": "book", "market_id": "mkt_..." }] }
```

```json theme={"dark"}
{ "type": "unsubscribed", "channels": [{ "channel": "book", "market_id": "mkt_..." }] }
```

Subscribing to a channel you already hold does not add it twice. These are answered with a
`VALIDATION_ERROR` error frame and the connection stays open:

| Message | When |
| - | - |
| `Name at least one channel` | `subscribe` named no channels. |
| `Unrecognized market id` | A `book` channel's `market_id`, or a `trades` or `market_lifecycle` channel's `ticker`, is not printable ASCII without spaces of at most 512 characters. |
| `Too many channels on one connection` | The subscription would take the connection past 1000 channels. |

## Channels

| Channel | Frame type | Holds |
| - | - | - |
| `orders` | `order` | Each new state of an order, as [Retrieve an order](https://docs.lean.xyz/api-reference/orders/retrieve-order.md) returns it. |
| `positions` | `positions` | The whole [List positions](https://docs.lean.xyz/api-reference/account/list-positions.md) result. |
| `balances` | `balances` | The whole [List balances](https://docs.lean.xyz/api-reference/account/list-balances.md) result. |
| `book` | `book`, then `book_delta`, then `book_ended` if it ends | One market's book, as [Get a market orderbook](https://docs.lean.xyz/api-reference/markets/retrieve-market-book.md) returns it, then what changes in it. |
| `trades` | `trades` | Trades on one venue listing, named by `ticker`, as they happen. |
| `market_lifecycle` | `market_lifecycle` | Status and tick size changes of one venue listing, named by `ticker`. |

### orders

Sends each state of the account's orders that happens after `subscribed`. Each order's states only
move forward. Call `GET /v1/orders` once after `subscribed` to cover anything earlier.

```json theme={"dark"}
{
  "type": "order",
  "order": {
    "id": "<order id>",
    "client_order_id": "my_order_0001",
    "market_id": "mkt_...",
    "title": "Denver Broncos at Los Angeles Chargers: Moneyline, Denver Broncos",
    "outcome": "DEN",
    "source": "api",
    "venue": "hyperliquid",
    "ticker": "<venue ticker>",
    "side": "yes",
    "action": "buy",
    "type": "limit",
    "time_in_force": "ioc",
    "expires_at": null,
    "quantity": "5",
    "filled_quantity": "5",
    "remaining_quantity": "0",
    "limit_price": "0.50",
    "avg_fill_price": "0.47",
    "notional_usd": "2.5",
    "filled_notional_usd": "2.35",
    "status": "filled",
    "venue_status": "filled",
    "venue_order_id": "<venue order id>",
    "status_reason": null,
    "legs": [
      {
        "venue": "hyperliquid",
        "ticker": "<venue ticker>",
        "side": "yes",
        "quantity": "5",
        "filled_quantity": "5",
        "limit_price": "0.50",
        "avg_fill_price": "0.47",
        "status": "filled",
        "venue_status": "filled",
        "venue_order_id": "<venue order id>",
        "cancel_requested_at": null,
        "status_reason": null
      }
    ],
    "post_only": false,
    "replaces_order_id": null,
    "replaced_by_order_id": null,
    "created_at": "2026-11-01T20:24:02.114Z",
    "updated_at": "2026-11-01T20:24:02.587Z",
    "livemode": false
  }
}
```

### positions

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

```json theme={"dark"}
{
  "type": "positions",
  "positions": {
    "positions": [
      {
        "venue": "hyperliquid",
        "ticker": "<venue ticker>",
        "side": "yes",
        "quantity": "5",
        "average_price": "0.5",
        "cost_basis_usd": "2.5",
        "mark_price": null,
        "unrealized_pnl_usd": null,
        "redeemable": false,
        "payout_usd": null,
        "market_id": "mkt_...",
        "title": "<market title>",
        "outcome": "<outcome>",
        "settled": false
      }
    ],
    "unavailable": [],
    "livemode": false
  }
}
```

### balances

Sent and refreshed the same way as positions.

```json theme={"dark"}
{
  "type": "balances",
  "balances": {
    "balances": [
      { "venue": "polymarket", "currency": "pUSD", "total_usd": "10000", "available_usd": "10000" },
      { "venue": "hyperliquid", "currency": "USDC", "total_usd": "10000", "available_usd": "10000" }
    ],
    "unavailable": [],
    "livemode": false
  }
}
```

### book

Takes a `market_id`: a market ID or a [venue symbol](https://docs.lean.xyz/markets.md#venue-symbols). With a market ID,
each frame holds the market's book across every venue that lists it; with a venue symbol, only
that symbol's listing. `combined` merges the venues' levels by price, at a depth of 20 levels per
side.

The channel opens with a `book` frame holding the whole book, then sends `book_delta` frames
holding only what changed since the book Lean last published. 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.

Every `book` and `book_delta` frame has a `sequence`. A delta also has `prev_sequence`: apply it
only when that equals the `sequence` of the book you hold, then hold its `sequence`. When a delta
cannot follow the frame before it, because your session read too slowly or the market's venues
changed, Lean sends a whole `book` frame instead, which replaces the book you hold. If you still
see a delta whose `prev_sequence` is not yours, drop the book, send `unsubscribe` for the channel,
then `subscribe` again: the new subscription opens with a whole `book` frame.
The official SDKs do all of this and hand you the whole book after each frame.

The frame's top-level `market_id` is the one you subscribed with, so a session following one market
under two names can tell their frames apart. `book.market_id` is always the market ID.

`book.as_of` is when Lean built the book. 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. Every later `book` frame has `snapshot` set to `false`, and
`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.

```json theme={"dark"}
{
  "type": "book",
  "market_id": "mkt_...",
  "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
  }
}
```

A `book_delta` frame lists only the levels that changed:

* Each level replaces the level at its price on its side. A `quantity` of `"0"` removes the level.
* A level that falls out of the 20 shown is removed, and one that comes into them is added, so the
  book you build always matches the next whole `book`.
* A `combined` level carries its whole `venues` split, not only the venue that changed.
* A venue book is matched by `venue`, `ticker` and `side`. It lists only its changed levels, with
  its new quantity and notional totals.
* The four book totals and `as_of` are always the new book's.
* Keep bids highest price first and asks lowest price first.

Quantities keep the venue's precision, as `GET /v1/markets/:id/book` returns them, so a level
holding a fraction of a share is listed and can be the best price. Every listed level holds more
than `0`, so `"0"` only ever means a removal.

```json theme={"dark"}
{
  "type": "book_delta",
  "market_id": "mkt_...",
  "sequence": 1842,
  "prev_sequence": 1841,
  "delta": {
    "venues": [
      {
        "venue": "polymarket",
        "ticker": "<venue ticker>",
        "side": "yes",
        "bids": [{ "price": "0.52", "quantity": "0" }, { "price": "0.51", "quantity": "75" }],
        "asks": [],
        "bid_quantity": "75",
        "ask_quantity": "40",
        "bid_notional_usd": "38.25",
        "ask_notional_usd": "22"
      }
    ],
    "combined": {
      "bids": [
        { "price": "0.52", "quantity": "0", "venues": [] },
        { "price": "0.51", "quantity": "75", "venues": [{ "venue": "polymarket", "quantity": "75" }] }
      ],
      "asks": []
    },
    "total_bid_quantity": "75",
    "total_ask_quantity": "40",
    "total_bid_notional_usd": "38.25",
    "total_ask_notional_usd": "22",
    "as_of": "2026-11-01T20:25:00.050Z"
  }
}
```

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` when the `market_id` names no market, or is a
[venue symbol that names more than one market](https://docs.lean.xyz/markets.md#venue-symbols), such as the ticker of a
listing that pays both outcomes. The REST endpoints refuse that symbol with `400`; the channel
ends instead. `reason` is `market_closed` once every venue listing of the market is closed or
resolved. `unknown_market`
arrives within a few seconds. `market_closed` arrives after Lean records the close, which can be a
few minutes after the venue closes the market. A market whose listings are unopened or resolving
still streams its book.

```json theme={"dark"}
{ "type": "book_ended", "market_id": "mkt_...", "reason": "unknown_market" }
```

A market listed after you subscribed, such as an upcoming crypto window, can end with
`unknown_market`. Subscribe again once [List markets](https://docs.lean.xyz/api-reference/markets/list-markets.md) returns it.

### trades

Name a venue listing by its leg `ticker`, as a market's `legs[].ticker` shows it:

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

Each frame holds the trades the venue reported since the last frame, oldest first. Only trades
that happen after `subscribed` are sent; read
[List recent market trades](https://docs.lean.xyz/api-reference/markets/list-market-trades.md) for earlier ones. Live and
test keys get the same trades.

```json theme={"dark"}
{
  "type": "trades",
  "ticker": "<venue ticker>",
  "timestamp": 1764620700120,
  "trades": [
    {
      "venue": "polymarket",
      "ticker": "<venue ticker>",
      "trade_id": "<venue trade id>",
      "side": "yes",
      "price": "0.42",
      "quantity": "120",
      "taker_side": "yes",
      "maker_side": "no",
      "timestamp": 1764620700050,
      "received_at_ms": 1764620700080,
      "maker": "0x...",
      "taker": "0x...",
      "maker_username": null,
      "taker_username": null,
      "maker_builder": null,
      "taker_builder": null,
      "additional_makers": [],
      "notional_cents": 5040
    }
  ]
}
```

| Field | Meaning |
| - | - |
| `side`, `price` | The side and price of the trade as the venue reports them, the price in dollars. |
| `quantity` | Shares traded, as a decimal string. |
| `taker_side`, `maker_side` | The side each party took. `maker_side` is `null` when the venue does not say. |
| `timestamp` | When the venue executed the trade, in Unix milliseconds. The frame's own `timestamp` is when Lean published it. |
| `received_at_ms` | When Lean received the trade, in Unix milliseconds, or `null`. |
| `maker`, `taker` | The parties' venue addresses where the venue publishes them, else `null`. `*_username` and `*_builder` name them when known. |
| `additional_makers[]` | Further makers filled by the same trade, each with `address`, `quantity`, `maker_side`, `username` and `builder`. |
| `notional_cents` | What the trade was worth, in cents. |

### market\_lifecycle

Name a venue listing the same way:

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

A `status_change` frame arrives when the listing's status changes. `status` is `unopened`, `open`,
`closed`, `resolving` or `resolved`, and `result` names the outcome once the venue reports one,
else `null`:

```json theme={"dark"}
{
  "type": "market_lifecycle",
  "event": "status_change",
  "venue": "kalshi",
  "ticker": "<venue ticker>",
  "status": "resolved",
  "result": "yes",
  "timestamp": 1764620700000
}
```

A `tick_size_change` frame arrives when the listing's price step changes. `tick_rule` is `cent`,
`half_cent`, `tenth`, `hundredth` or `tapered`, and `tick_size` is the exact step in dollars when
the venue gives one, else `null`:

```json theme={"dark"}
{
  "type": "market_lifecycle",
  "event": "tick_size_change",
  "venue": "polymarket",
  "ticker": "<venue ticker>",
  "tick_rule": "tenth",
  "tick_size": "0.001",
  "timestamp": 1764620700000
}
```

The first frame after `subscribed` can repeat the listing's current state. New `event` values can
appear without a new version; skip one you do not recognize.

Only a `ticker`'s shape is checked: one no venue lists is accepted and sends nothing. Unlike a
`book` channel's `market_id`, a Polymarket condition ID, token ID or Hyperliquid coin is not
resolved to a ticker.

A session that reads positions, balances or books too slowly skips ahead to the newest state. A
session that reads trades or lifecycle events too slowly is closed with `1013` and `RATE_LIMITED`,
with the message `Stream fell behind; reconnect and refetch state`.

## Keep the connection alive

Send `{"op":"ping"}` every 10 seconds; the reply is `{"type":"pong"}`. If no frame of any kind,
`pong` included, arrives for 25 seconds, close the socket and reconnect with a new ticket.

## Errors

Every error is an `error` frame with a `code` and a `message`. Whether the connection stays open
depends on whether it has authenticated.

### Before authentication

Until `authenticated` arrives, Lean accepts only an `auth` frame. Anything else gets one error
frame, then the socket closes:

| You send | Close code | `code` | `message` |
| - | - | - | - |
| `ping`, `subscribe` or `unsubscribe` | `1008` | `UNAUTHORIZED` | `Authenticate before any other frame` |
| Text that is not JSON, or JSON that is not a frame shown on this page | `1008` | `VALIDATION_ERROR` | `Expected an auth frame` |
| A binary frame | `1003` | `VALIDATION_ERROR` | `Frames must be JSON text` |
| No `auth` frame within 10 seconds | `1008` | `UNAUTHORIZED` | `Authentication timed out` |

An `auth` frame whose ticket or key is refused also closes with `1008` and `UNAUTHORIZED`: the
ticket is invalid, expired or already used, or the key is expired or revoked. The closes that can
follow an `auth` frame for other reasons are in [Close codes](#close-codes).

### 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" }
```

`Unrecognized frame` answers text that is not JSON or not a frame shown on this page. A second
`auth` frame gets `This connection is already authenticated`, and a bad `subscribe` gets one of the
[subscribe errors](#subscribe-and-unsubscribe). A binary frame still closes the socket with `1003`.

## Close codes

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

| Close code | `code` | When |
| - | - | - |
| `1008` | `UNAUTHORIZED` | Before authentication, as [listed above](#before-authentication). After it, the key was revoked or expired. |
| `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 also keeps the connection open.

After a `1001`, `1012` or `1013` close, reconnect with a new ticket, subscribe again and call
`GET /v1/orders`. After a `1008` close, the ticket or key was refused: try once more with a new
ticket and stop after three `1008` closes in a row. The
[Streaming guide](https://docs.lean.xyz/streaming.md#reconnecting) covers the full reconnect plan.


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