> For the complete documentation index, see [llms.txt](https://docs.hypertracker.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.hypertracker.io/order-book-data/l2-order-book.md). Agents can also search and read this documentation through its [MCP server](https://docs.hypertracker.io/~gitbook/mcp).

# L2 Order Book

Aggregated depth of a market: total size and order count per price level. Choose a full snapshot in every message (`l2book`) or one snapshot followed by diffs (`l2bookdiff`). Both accept selectors for price buckets and depth.

<table><thead><tr><th width="119">Channel</th><th>Message type</th><th>First publication</th><th>Later publications</th><th>Your local state</th><th width="113.25">If you miss a message</th></tr></thead><tbody><tr><td><code>l2book:&#x3C;coin></code></td><td><code>l2Book</code></td><td>Next applied block</td><td>Complete snapshots</td><td>Replace it with every message</td><td>The next message restores the full view</td></tr><tr><td><code>l2bookdiff:&#x3C;coin></code></td><td><code>l2BookDiff</code></td><td>Next applied block (<code>snapshot: true</code>)</td><td>Changed levels only</td><td>Apply every diff in order</td><td>Your local book can be wrong</td></tr></tbody></table>

{% hint style="info" %}
`l2book` is simpler, because every message replaces the previous view. `l2bookdiff` sends only changed levels, but you must apply every diff in order. For individual orders see [L4 Order Book](https://docs.hypertracker.io/order-book-data/l4-order-book.md).
{% endhint %}

Connection, subscribing, errors, and message envelopes are described in [Getting Started](https://docs.hypertracker.io/order-book-data/getting-started.md). The examples below use the inner message: `ctx.data` in JavaScript, `ctx.pub.data` in Python.

Depth is the same on every plan: up to 100 price levels per side, set with `nLevels` (default 20).

### Selectors

Both L2 channels take selectors in the subscription `data`. There are no tag filters.

<table><thead><tr><th width="129.453125">Field</th><th width="186.3958740234375">Type</th><th>Meaning</th></tr></thead><tbody><tr><td><code>coin</code></td><td>string, optional</td><td>Must match the coin in the channel name when supplied. Prefer leaving it out.</td></tr><tr><td><code>nSigFigs</code></td><td>integer, optional</td><td>Price aggregation precision, from <code>2</code> to <code>5</code>. Leave it out for unaggregated prices.</td></tr><tr><td><code>mantissa</code></td><td>integer, optional</td><td><code>2</code> or <code>5</code>. Allowed only when <code>nSigFigs</code> is <code>5</code>. Leave it out for the default multiplier of <code>1</code>.</td></tr><tr><td><code>nLevels</code></td><td>integer, optional</td><td>Number of aggregated price buckets per side, from <code>1</code> to <code>100</code>. Leave it out for the default of <code>20</code>.</td></tr></tbody></table>

`nLevels` is applied after `nSigFigs` and `mantissa`. Omitted fields and `null` select the defaults. Zeros, negative values, decimals, unknown fields, and trailing JSON are rejected.

<table data-search="false"><thead><tr><th width="316.583251953125">data</th><th>Result</th></tr></thead><tbody><tr><td><code>{}</code></td><td>Valid. Default view.</td></tr><tr><td><code>{ "nLevels": 10 }</code></td><td>Valid.</td></tr><tr><td><code>{ "nSigFigs": 3, "nLevels": 50 }</code></td><td>Valid.</td></tr><tr><td><code>{ "nSigFigs": 5, "mantissa": 5, "nLevels": 100 }</code></td><td>Valid.</td></tr><tr><td><code>{ "nLevels": 20 }</code></td><td>Rejected. <code>20</code> is the default, so leave the field out.</td></tr><tr><td><code>{ "nSigFigs": 4, "mantissa": 2 }</code></td><td>Rejected. <code>mantissa</code> is allowed only with <code>nSigFigs</code> of <code>5</code>.</td></tr><tr><td><code>{ "coin": "ETH", "nSigFigs": 5 }</code></td><td>Rejected on <code>l2book:BTC</code>, because the two coins differ.</td></tr></tbody></table>

An invalid selector returns error `1071`. See [Errors](https://docs.hypertracker.io/order-book-data/getting-started.md#errors).

One connection holds one selector set per channel. For a second set, open a second connection. It counts toward your connection limit.

#### Price buckets

* Bucket size = 10^(digits before the decimal point − `nSigFigs`) × `mantissa`.
* `mantissa` is 1 if you leave it out. `2` or `5` are allowed only with `nSigFigs` of `5`.
* Bid prices are rounded down to their bucket, and ask prices are rounded up. Levels in the same bucket are combined: their sizes and order counts are added.

Example for BTC, with a best bid of 63,100.5 and a best ask of 63,101.3:

* No selectors (full precision): bid 63100.5, ask 63101.3
* `nSigFigs: 5`: bucket size 1, bid 63100, ask 63102
* `nSigFigs: 5`, `mantissa: 2`: bucket size 2, bid 63100, ask 63102
* `nSigFigs: 5`, `mantissa: 5`: bucket size 5, bid 63100, ask 63105
* `nSigFigs: 4`: bucket size 10, bid 63100, ask 63110
* `nSigFigs: 3`: bucket size 100, bid 63100, ask 63200
* `nSigFigs: 2`: bucket size 1000, bid 63000, ask 64000

The bucket size changes when the best bid crosses a power of ten. For example, at `nSigFigs: 5` it is 1 below 100,000 and 10 from 100,000 upward.

### Full L2 book: `l2book:<coin>`

A complete snapshot of the book in every message.

#### **Event format**

<table data-search="false"><thead><tr><th width="153.552001953125">Field</th><th width="196.6666259765625">Type</th><th>Notes</th></tr></thead><tbody><tr><td><code>coin</code></td><td>string</td><td>Canonical market name.</td></tr><tr><td><code>time</code></td><td>number</td><td>Source event or block time in Unix epoch milliseconds.</td></tr><tr><td><code>levels[0]</code></td><td>array</td><td>Bids in descending price order.</td></tr><tr><td><code>levels[1]</code></td><td>array</td><td>Asks in ascending price order.</td></tr><tr><td><code>px</code></td><td>string</td><td>Price of the level. Decimal string.</td></tr><tr><td><code>sz</code></td><td>string</td><td>Total resting size at that price. Decimal string.</td></tr><tr><td><code>n</code></td><td>number</td><td>Number of resting orders at that price.</td></tr></tbody></table>

Each message replaces the previous one, so never merge messages. A message is published on every block (about 15 per second), even when the book did not change. A slow client skips to the latest book. For updates only when the book changes, use `l2bookdiff`.

{% tabs %}
{% tab title="JavaScript" %}
{% code expandable="true" %}

```
{
  "channel": "l2Book",
  "data": {
    "coin": "BTC",
    "time": 1786905889616,
    "levels": [
      [
        { "px": "63100", "sz": "12.5", "n": 4 },
        { "px": "63099", "sz": "5.1", "n": 2 }
      ],
      [
        { "px": "63101", "sz": "3.2", "n": 2 },
        { "px": "63102", "sz": "8.0", "n": 1 }
      ]
    ]
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code expandable="true" %}

```
{
    "channel": "l2Book",
    "data": {
        "coin": "BTC",
        "time": 1786905889616,
        "levels": [
            [
                {"px": "63100", "sz": "12.5", "n": 4},
                {"px": "63099", "sz": "5.1", "n": 2},
            ],
            [
                {"px": "63101", "sz": "3.2", "n": 2},
                {"px": "63102", "sz": "8.0", "n": 1},
            ],
        ],
    },
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

#### Subscribe

{% tabs %}
{% tab title="JavaScript" %}
{% code expandable="true" %}

```
const sub = client.newSubscription('l2book:BTC', {
  data: { nSigFigs: 5, mantissa: 2, nLevels: 10 },
});

sub.on('publication', (ctx) => {
  const [bids, asks] = ctx.data.data.levels;
  console.log(bids[0]?.px, asks[0]?.px); // best bid and best ask of the view
});

sub.subscribe();
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code expandable="true" %}

```
class L2BookHandler(SubscriptionEventHandler):
    async def on_publication(self, ctx):
        bids, asks = ctx.pub.data["data"]["levels"]
        print(bids[0]["px"] if bids else None, asks[0]["px"] if asks else None)


sub = client.new_subscription(
    "l2book:BTC",
    events=L2BookHandler(),
    data={"nSigFigs": 5, "mantissa": 2, "nLevels": 10},
)
await sub.subscribe()
```

{% endcode %}
{% endtab %}
{% endtabs %}

### L2 snapshot and diffs: `l2bookdiff:<coin>`

One complete snapshot, then only the price levels that changed.

#### **Event format**

<table data-search="false"><thead><tr><th width="139.578125">Field</th><th width="147.395751953125">Type</th><th>Notes</th></tr></thead><tbody><tr><td><code>snapshot</code></td><td>boolean</td><td><code>true</code> for a complete visible ladder, <code>false</code> for a diff.</td></tr><tr><td><code>coin</code></td><td>string</td><td>Canonical market name.</td></tr><tr><td><code>time</code></td><td>number</td><td>Source event or block time in Unix epoch milliseconds.</td></tr><tr><td><code>height</code></td><td>number</td><td>Source block height. Use it to order updates.</td></tr><tr><td><code>levels[0]</code></td><td>array</td><td>Bid levels. In a diff, only the levels that changed.</td></tr><tr><td><code>levels[1]</code></td><td>array</td><td>Ask levels. In a diff, only the levels that changed.</td></tr><tr><td><code>px</code></td><td>string</td><td>Price of the level. Decimal string.</td></tr><tr><td><code>sz</code></td><td>string</td><td>Total resting size at that price. Decimal string. <code>"0"</code> means the level is gone.</td></tr><tr><td><code>n</code></td><td>number</td><td>Number of resting orders at that price. <code>0</code> means the level is gone.</td></tr></tbody></table>

The first publication is a complete visible ladder:

{% tabs %}
{% tab title="JavaScript" %}
{% code expandable="true" %}

```
{
  "channel": "l2BookDiff",
  "data": {
    "snapshot": true,
    "coin": "BTC",
    "time": 1786905889616,
    "height": 123,
    "levels": [
      [{ "px": "63100", "sz": "12.5", "n": 4 }],
      [{ "px": "63101", "sz": "3.2", "n": 2 }]
    ]
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code expandable="true" %}

```
{
    "channel": "l2BookDiff",
    "data": {
        "snapshot": True,
        "coin": "BTC",
        "time": 1786905889616,
        "height": 123,
        "levels": [
            [{"px": "63100", "sz": "12.5", "n": 4}],
            [{"px": "63101", "sz": "3.2", "n": 2}],
        ],
    },
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

Later publications contain only changed levels:

{% tabs %}
{% tab title="JavaScript" %}
{% code expandable="true" %}

```
{
  "channel": "l2BookDiff",
  "data": {
    "snapshot": false,
    "coin": "BTC",
    "time": 1786905889716,
    "height": 124,
    "levels": [
      [
        { "px": "63100", "sz": "14.0", "n": 5 },
        { "px": "63099", "sz": "0", "n": 0 }
      ],
      []
    ]
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code expandable="true" %}

```
{
    "channel": "l2BookDiff",
    "data": {
        "snapshot": False,
        "coin": "BTC",
        "time": 1786905889716,
        "height": 124,
        "levels": [
            [
                {"px": "63100", "sz": "14.0", "n": 5},
                {"px": "63099", "sz": "0", "n": 0},
            ],
            [],
        ],
    },
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

#### **Rebuild the book**

Apply every publication in the order it arrives:

1. For `snapshot: true`, clear both sides and install all levels.
2. For `snapshot: false`, replace every level by price. Delete a level when `sz` is `"0"` and `n` is `0`.
3. Ignore a diff whose `height` is not higher than the last one you applied. Heights can skip, because unchanged blocks produce no publication.
4. A later `snapshot: true` is a resynchronization boundary. It replaces all state you rebuilt locally.

{% tabs %}
{% tab title="JavaScript" %}
{% code expandable="true" %}

```
const book = { bids: new Map(), asks: new Map(), height: 0 };

function applyL2BookDiff(envelope) {
  if (envelope.channel !== 'l2BookDiff') return;
  const update = envelope.data;

  if (update.snapshot) {
    book.bids.clear();
    book.asks.clear();
  } else if (update.height <= book.height) {
    return; // stale or duplicate publication
  }

  for (const [side, levels] of [
    [book.bids, update.levels[0]],
    [book.asks, update.levels[1]],
  ]) {
    for (const level of levels) {
      if (level.sz === '0' && level.n === 0) side.delete(level.px);
      else side.set(level.px, level);
    }
  }
  book.height = update.height;
}

// Read the book. Prices are strings, so compare them numerically.
function topOfBook(depth = 5) {
  const bids = [...book.bids.values()].sort((a, b) => Number(b.px) - Number(a.px));
  const asks = [...book.asks.values()].sort((a, b) => Number(a.px) - Number(b.px));
  return { bids: bids.slice(0, depth), asks: asks.slice(0, depth) };
}
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code expandable="true" %}

```
from decimal import Decimal

book = {"bids": {}, "asks": {}, "height": 0}


def apply_l2_book_diff(envelope):
    if envelope["channel"] != "l2BookDiff":
        return
    update = envelope["data"]

    if update["snapshot"]:
        book["bids"].clear()
        book["asks"].clear()
    elif update["height"] <= book["height"]:
        return  # stale or duplicate publication

    for side, levels in (
        (book["bids"], update["levels"][0]),
        (book["asks"], update["levels"][1]),
    ):
        for level in levels:
            if level["sz"] == "0" and level["n"] == 0:
                side.pop(level["px"], None)
            else:
                side[level["px"]] = level
    book["height"] = update["height"]


# Read the book. Prices are strings, so compare them as decimals.
def top_of_book(depth=5):
    bids = sorted(book["bids"].values(), key=lambda lv: Decimal(lv["px"]), reverse=True)
    asks = sorted(book["asks"].values(), key=lambda lv: Decimal(lv["px"]))
    return {"bids": bids[:depth], "asks": asks[:depth]}
```

{% endcode %}
{% endtab %}
{% endtabs %}

With `nLevels`, a level entering the window arrives as a normal level. A level leaving it arrives with `"sz": "0"` and `"n": 0`, so remove it locally. Your book then always holds `nLevels` levels per side, or fewer if the book is smaller.

{% hint style="warning" %}
Losing one diff corrupts your local book. If a subscription ends, discard your book, resubscribe, and start from the new snapshot.
{% endhint %}

A new `snapshot: true` arrives when you subscribe (including reconnects and changed selectors) or after a server-side recovery. Accept it at any time and replace your local book.

`l2bookdiff` never skips a message while you are subscribed. If your client falls too far behind, the subscription ends.

#### Subscribe

{% tabs %}
{% tab title="JavaScript" %}
{% code expandable="true" %}

```
const sub = client.newSubscription('l2bookdiff:BTC', {
  data: { nSigFigs: 5, mantissa: 2, nLevels: 10 },
});

sub.on('publication', (ctx) => applyL2BookDiff(ctx.data));

sub.subscribe();
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code expandable="true" %}

```
class L2DiffHandler(SubscriptionEventHandler):
    async def on_publication(self, ctx):
        apply_l2_book_diff(ctx.pub.data)


sub = client.new_subscription(
    "l2bookdiff:BTC",
    events=L2DiffHandler(),
    data={"nSigFigs": 5, "mantissa": 2, "nLevels": 10},
)
await sub.subscribe()
```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# 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.hypertracker.io/order-book-data/l2-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.
