> For the complete documentation index, see [llms.txt](https://docs.outpoll.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.outpoll.com/api/futures-api/websockets/futures-market-data/order-book.md).

# Order Book

Real-time futures order book: snapshot plus incremental updates, or grouped snapshots.

Use this stream to keep a local copy of a pair's order book. On the native price grid you get one snapshot followed by deltas; with a grouping step you get a full snapshot on every update.

### Endpoint

```
wss://futures-marketdata-service.outpoll.com/ws/book/depth
```

The connection supports `permessage-deflate` compression; most WebSocket clients enable it automatically.

### Authentication

No authentication required.

### Message Envelope

Every data frame has the same fields. A delta is recognised by the presence of `pu`.

| Field | Type    | Description                                              |
| ----- | ------- | -------------------------------------------------------- |
| `pi`  | string  | Pair ID, as a string (for example `"1"`)                 |
| `a`   | array   | Ask levels, `[price, size]`, best (lowest) price first   |
| `b`   | array   | Bid levels, `[price, size]`, best (highest) price first  |
| `t`   | integer | Book time, epoch ms                                      |
| `u`   | integer | Update ID of this book state                             |
| `pu`  | integer | Delta only: update ID of the state this delta applies to |

### Message Types

| Type                        | Direction       | Description                                                                                    |
| --------------------------- | --------------- | ---------------------------------------------------------------------------------------------- |
| `subscribe` / `unsubscribe` | Client → Server | Start or stop a pair, set depth and grouping                                                   |
| Snapshot                    | Server → Client | Full book, trimmed to `dp` levels per side. No `pu`                                            |
| Delta                       | Server → Client | Changed levels only. Has `pu`. Native grid only                                                |
| Error                       | Server → Client | `{"er", "msg"}` — see [Errors](broken://pages/7b60c6363e2dcb27a5c7d2ef03222a2bd85342c5#errors) |
| `ping` / `pong`             | Both            | Plain-text keep-alive                                                                          |

### Subscribe

```json
{"act": "subscribe", "pi": 1, "dp": 20}
```

With price grouping:

```json
{"act": "subscribe", "pi": 1, "dp": 20, "g": 10}
```

| Field       | Type            | Required | Description                                                                                                               |
| ----------- | --------------- | -------- | ------------------------------------------------------------------------------------------------------------------------- |
| `act`       | string          | Yes      | `subscribe`                                                                                                               |
| `pi` / `ps` | integer / array | Yes      | Pair ID, or list of pair IDs; `dp` and `g` apply to every pair in the frame                                               |
| `dp`        | integer         | No       | Levels per side, default `20`. The native book holds a fixed number of levels per pair; a larger `dp` returns all of them |
| `g`         | number          | No       | Price grouping step. Omit, or send `0`, for the native tick grid                                                          |

Server confirmation: there is no confirmation frame — the first frame after subscribing is the pair's snapshot.

`all: true` is not supported on this stream; subscribe by pair ID.

To change `dp` or `g`, send `subscribe` again for the same pair. The next frame is a fresh snapshot with the new settings.

### Native Grid: Snapshot and Deltas

Without `g`, the book is on the pair's tick size.

{% stepper %}
{% step %}

#### Receive the snapshot

Right after subscribing you receive a **snapshot** (no `pu`). Replace your local book with it and remember its `u`.
{% endstep %}

{% step %}

#### Apply deltas

After that you receive **deltas** (with `pu`) carrying only the price levels that changed:

* `[price, size]` with `size > 0` — set the level at this price to `size` (add or replace).
* `[price, 0]` — remove the level at this price.
  {% endstep %}

{% step %}

#### Verify the update sequence

Apply a delta only if its `pu` equals the `u` of the last frame you applied, then remember the delta's `u`.
{% endstep %}

{% step %}

#### Recover from a gap

If `pu` does not match, a frame was missed: discard the local book and send `subscribe` for the pair again. The next frame is a new snapshot.
{% endstep %}
{% endstepper %}

#### Notes

* Update IDs increase but are **not consecutive** — check `pu` against your last `u`, never `u` against last `u + 1`.
* Deltas are **not trimmed** to `dp`: they carry every changed level of the native book. Keep the full book locally and cut it to `dp` when you display it.
* Levels inside a delta are addressed by price; their order in the array carries no meaning.
* When nothing changed, no frame is sent.
* If the server cannot deliver a delta to your connection, the next frame you receive is a new snapshot. Treat any frame without `pu` as a reset.

### Grouped: Full Snapshots

With a positive `g`, levels are merged into price buckets of size `g`, and **every** frame is a full snapshot (no `pu`, no deltas). Replace your local book with each frame.

* Ask prices are rounded up to the bucket, bid prices rounded down; sizes in one bucket are summed.
* Each side has `dp` rows.
* Frames follow the same cadence as the native book.

#### How `g` is applied

| `g` sent                                                   | Result                                                       |
| ---------------------------------------------------------- | ------------------------------------------------------------ |
| Absent, `0` or negative                                    | Native grid with deltas                                      |
| More than 8 decimal places, or more than 18 integer digits | Error `invalid_group`; the pair is served on the native grid |
| Smaller than or equal to the tick size                     | Tick size, as full snapshots                                 |
| Not a multiple of the tick size                            | Rounded down to a multiple of the tick size                  |
| Larger than tick size × 1,000,000                          | Capped at tick size × 1,000,000                              |

Example for a pair with tick size `0.1`: `g = 0.25` becomes `0.2`, `g = 0.01` becomes `0.1`.

### Snapshot Payload

```json
{
  "pi": "1",
  "a": [[64250.5, 0.412], [64250.6, 1.035], [64250.7, 0.088]],
  "b": [[64250.4, 0.731], [64250.3, 0.264], [64250.2, 2.519]],
  "t": 1790662754945,
  "u": 48211907
}
```

| Field | Type    | Description                               |
| ----- | ------- | ----------------------------------------- |
| `pi`  | string  | Pair ID                                   |
| `a`   | array   | Asks `[price, size]`, ascending by price  |
| `b`   | array   | Bids `[price, size]`, descending by price |
| `t`   | integer | Book time, epoch ms                       |
| `u`   | integer | Update ID                                 |

### Delta Payload

```json
{
  "pi": "1",
  "a": [[64250.6, 0.977], [64250.8, 0.150]],
  "b": [[64250.2, 0]],
  "t": 1790662755278,
  "u": 48211961,
  "pu": 48211907
}
```

| Field | Type    | Description                                                 |
| ----- | ------- | ----------------------------------------------------------- |
| `pi`  | string  | Pair ID                                                     |
| `a`   | array   | Changed asks `[price, size]`; `size` `0` = remove the level |
| `b`   | array   | Changed bids `[price, size]`; `size` `0` = remove the level |
| `t`   | integer | Book time, epoch ms                                         |
| `u`   | integer | Update ID after applying this delta                         |
| `pu`  | integer | Update ID this delta builds on                              |

### Python Example

{% code title="order\_book.py" %}

```python
import asyncio
import json
from decimal import Decimal

import websockets

URL = "wss://futures-marketdata-service.outpoll.com/ws/book/depth"
PAIR_ID = 1
DEPTH = 10


class Book:
    def __init__(self):
        self.asks, self.bids, self.u = {}, {}, None

    def load(self, msg):
        self.asks = {p: q for p, q in msg["a"]}
        self.bids = {p: q for p, q in msg["b"]}
        self.u = msg["u"]

    def apply(self, msg):
        for side, levels in ((self.asks, msg["a"]), (self.bids, msg["b"])):
            for price, size in levels:
                if size == 0:
                    side.pop(price, None)
                else:
                    side[price] = size
        self.u = msg["u"]

    def top(self, n):
        asks = sorted(self.asks.items())[:n]
        bids = sorted(self.bids.items(), reverse=True)[:n]
        return asks, bids


async def subscribe(ws):
    await ws.send(json.dumps({"act": "subscribe", "pi": PAIR_ID, "dp": DEPTH}))


async def main():
    book = Book()
    async with websockets.connect(URL) as ws:
        await subscribe(ws)
        async for raw in ws:
            if raw == "pong":
                continue
            msg = json.loads(raw, parse_float=Decimal)
            if "er" in msg:
                print("error:", msg)
                continue
            if "pu" not in msg:
                book.load(msg)
            elif book.u is None:
                continue  # waiting for a snapshot
            elif msg["pu"] == book.u:
                book.apply(msg)
            else:
                book.u = None  # gap: request a fresh snapshot
                await subscribe(ws)
                continue
            asks, bids = book.top(DEPTH)
            if asks and bids:
                print("best bid", bids[0], "best ask", asks[0])


asyncio.run(main())
```

{% endcode %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.outpoll.com/api/futures-api/websockets/futures-market-data/order-book.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
