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

| | |
| - | - |
| Path | `/v1/ws` at the WebSocket URL for your environment |
| 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 32 on one connection |

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. A second `auth` frame on the same connection is
answered with a `VALIDATION_ERROR` error frame.

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

```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:

```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` is not shaped like a market id or venue symbol. |
| `Too many channels on one connection` | The subscription would take the connection past 32 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` | One market's book, as [Get a market orderbook](https://docs.lean.xyz/api-reference/markets/retrieve-market-book.md) returns it. |

### 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_...",
    "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",
        "mark_price": null,
        "unrealized_pnl_usd": null,
        "market_id": "mkt_...",
        "title": "<market title>",
        "outcome": "<outcome>"
      }
    ],
    "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 book updates about once a second, and each frame replaces the one before it. A
`market_id` that names no market sends nothing.

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.

```json theme={"dark"}
{
  "type": "book",
  "market_id": "mkt_...",
  "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 session that reads positions, balances or books too slowly skips ahead to the newest 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

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

## Close codes

Before authentication, or when the connection must end, Lean sends an 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 frame came before `auth`; or the key was revoked or expired. |
| `1008` | `VALIDATION_ERROR` | The first frame was not an `auth` frame. |
| `1003` | `VALIDATION_ERROR` | A binary frame was sent. |
| `1013` | `RATE_LIMITED` | The session read order states too slowly to keep up. |
| `1013` | `UPSTREAM_ERROR` | 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. |

After a `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.