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

# L4 Order Book

Every resting order of a market, with the wallet behind it: one snapshot, then order-level updates as orders are placed, changed, and removed. Use L4 to see who rests where and in which queue order. For aggregated depth see [L2 Order Book](https://docs.coinmarketman.com/order-book-data/l2-order-book.md).

* **Channel:** `l4book:<coin>`
* **Message type:** `l4Book`
* **Subscribe `data`:** Omit, `{}`, or a matching `{"coin":"..."}`
* **First publication:** Immediate snapshot
* **Replay:** No

L4 is included only on Stream, and per contract on Enterprise. On Surge and Flow, subscribing is rejected with `1084`. Each `l4book` subscription counts as an order book stream. See [Plan limits and availability](https://docs.coinmarketman.com/order-book-data.md#plan-limits-and-availability).

L4 contains only orders that rest on the book. Untriggered stop and take profit orders are not included. A trigger order that has fired and rests on the book appears as a normal order with `isTrigger: false` and `triggerCondition: "Triggered"`. At the same block, L4 contains the same resting orders as the Order Data snapshot, minus the untriggered trigger orders.

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

### Message types

The `data` of every `l4Book` message contains exactly one of three keys:

<table><thead><tr><th width="184.7552490234375">Key</th><th>When it is sent</th></tr></thead><tbody><tr><td><code>Snapshot</code></td><td>Right after you subscribe. A complete book.</td></tr><tr><td><code>SnapshotPart</code></td><td>Instead of <code>Snapshot</code> when the snapshot is larger than 3,000,000 encoded bytes.</td></tr><tr><td><code>Updates</code></td><td>After the snapshot. The changes of one block.</td></tr></tbody></table>

### Snapshot

A complete snapshot of every resting order.

<table><thead><tr><th width="156.9010009765625">Field</th><th width="153.171875">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>height</code></td><td>number</td><td>Source block height.</td></tr><tr><td><code>levels[0]</code></td><td>array</td><td>Bid orders.</td></tr><tr><td><code>levels[1]</code></td><td>array</td><td>Ask orders.</td></tr></tbody></table>

Each side is sorted from the best price. Within a price, orders are listed in queue order, first in line first, subject to priority-order placement.

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

```
{
  "channel": "l4Book",
  "data": {
    "Snapshot": {
      "coin": "BTC",
      "time": 1786905889616,
      "height": 123,
      "levels": [
        [
          {
            "user": "0xbuyer...",
            "coin": "BTC",
            "side": "B",
            "limitPx": "63100",
            "sz": "0.025",
            "oid": 105338503859,
            "timestamp": 1786905800000,
            "triggerCondition": "N/A",
            "isTrigger": false,
            "triggerPx": "0.0",
            "isPositionTpsl": false,
            "reduceOnly": false,
            "orderType": "Limit",
            "tif": "Gtc",
            "cloid": null
          }
        ],
        []
      ]
    }
  }
}
```

{% endcode %}
{% endtab %}

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

```
{
    "channel": "l4Book",
    "data": {
        "Snapshot": {
            "coin": "BTC",
            "time": 1786905889616,
            "height": 123,
            "levels": [
                [
                    {
                        "user": "0xbuyer...",
                        "coin": "BTC",
                        "side": "B",
                        "limitPx": "63100",
                        "sz": "0.025",
                        "oid": 105338503859,
                        "timestamp": 1786905800000,
                        "triggerCondition": "N/A",
                        "isTrigger": False,
                        "triggerPx": "0.0",
                        "isPositionTpsl": False,
                        "reduceOnly": False,
                        "orderType": "Limit",
                        "tif": "Gtc",
                        "cloid": None,
                    }
                ],
                [],
            ],
        }
    },
}
```

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

### **Order fields**

<table data-search="false"><thead><tr><th>Field</th><th>Type</th><th>Notes</th></tr></thead><tbody><tr><td><code>user</code></td><td>string or null</td><td>Account address in a snapshot. <code>null</code> in the nested <code>order</code> of an update, because the sibling status has the address.</td></tr><tr><td><code>coin</code></td><td>string</td><td>Canonical market name.</td></tr><tr><td><code>side</code></td><td>string</td><td><code>B</code> for bid or buy, <code>A</code> for ask or sell.</td></tr><tr><td><code>limitPx</code></td><td>string</td><td>Limit price. Decimal string.</td></tr><tr><td><code>sz</code></td><td>string</td><td>Current resting size. Decimal string.</td></tr><tr><td><code>oid</code></td><td>number</td><td>Exchange order ID.</td></tr><tr><td><code>timestamp</code></td><td>number</td><td>Order timestamp in Unix epoch milliseconds.</td></tr><tr><td><code>triggerCondition</code>, <code>isTrigger</code>, <code>triggerPx</code></td><td>string, boolean, string</td><td>Trigger description, trigger flag, and trigger price.</td></tr><tr><td><code>isPositionTpsl</code>, <code>reduceOnly</code></td><td>boolean</td><td>Position take profit or stop loss flag, and reduce-only flag.</td></tr><tr><td><code>orderType</code>, <code>tif</code></td><td>string</td><td>Order type and time in force. <code>tif</code> can be <code>null</code>.</td></tr><tr><td><code>cloid</code></td><td>string or null</td><td>Client order ID, or <code>null</code> when none was supplied.</td></tr></tbody></table>

{% hint style="info" %}
Treat `status`, `orderType`, `tif`, and `triggerCondition` as open string values. New values can appear, so do not map them to a closed list.
{% endhint %}

### Updates

The changes of one block. After the snapshot, every `l4Book` message contains an `Updates` object.

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

```
{
  "channel": "l4Book",
  "data": {
    "Updates": {
      "time": 1786905889716,
      "height": 124,
      "order_statuses": [
        {
          "time": "2026-09-15T18:04:49.716000000",
          "user": "0xbuyer...",
          "status": "open",
          "order": {
            "user": null,
            "coin": "BTC",
            "side": "B",
            "limitPx": "63100.0",
            "sz": "0.025",
            "oid": 105338503859,
            "timestamp": 1786905889716,
            "triggerCondition": "N/A",
            "isTrigger": false,
            "triggerPx": "0.0",
            "isPositionTpsl": false,
            "reduceOnly": false,
            "orderType": "Limit",
            "tif": "Alo",
            "cloid": null
          }
        }
      ],
      "book_diffs": [
        {
          "user": "0xbuyer...",
          "oid": 105338503859,
          "px": "63100.0",
          "coin": "BTC",
          "raw_book_diff": {
            "new": { "sz": "0.025", "insertBefore": 105338503858 }
          }
        }
      ]
    }
  }
}
```

{% endcode %}
{% endtab %}

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

```
{
    "channel": "l4Book",
    "data": {
        "Updates": {
            "time": 1786905889716,
            "height": 124,
            "order_statuses": [
                {
                    "time": "2026-09-15T18:04:49.716000000",
                    "user": "0xbuyer...",
                    "status": "open",
                    "order": {
                        "user": None,
                        "coin": "BTC",
                        "side": "B",
                        "limitPx": "63100.0",
                        "sz": "0.025",
                        "oid": 105338503859,
                        "timestamp": 1786905889716,
                        "triggerCondition": "N/A",
                        "isTrigger": False,
                        "triggerPx": "0.0",
                        "isPositionTpsl": False,
                        "reduceOnly": False,
                        "orderType": "Limit",
                        "tif": "Alo",
                        "cloid": None,
                    },
                }
            ],
            "book_diffs": [
                {
                    "user": "0xbuyer...",
                    "oid": 105338503859,
                    "px": "63100.0",
                    "coin": "BTC",
                    "raw_book_diff": {
                        "new": {"sz": "0.025", "insertBefore": 105338503858}
                    },
                }
            ],
        }
    },
}
```

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

The keys inside `Updates` are snake\_case.

<table data-search="false"><thead><tr><th width="258.3385009765625">Field</th><th width="148.510498046875">Type</th><th>Notes</th></tr></thead><tbody><tr><td><code>time</code></td><td>number</td><td>Source block time in Unix epoch milliseconds, for the whole update.</td></tr><tr><td><code>height</code></td><td>number</td><td>Source block height, for the whole update.</td></tr><tr><td><code>order_statuses[]</code></td><td>array</td><td>The complete order and status records observed in the block.</td></tr><tr><td><code>order_statuses[].time</code></td><td>string</td><td>Node timestamp without a time zone suffix. Keep it as text if the exact format matters.</td></tr><tr><td><code>order_statuses[].user</code></td><td>string</td><td>Account address of the status.</td></tr><tr><td><code>order_statuses[].status</code></td><td>string</td><td>Node status such as <code>open</code>, <code>filled</code>, or <code>canceled</code>. New values can appear.</td></tr><tr><td><code>order_statuses[].order</code></td><td>object</td><td>The full order. Use it to build a new book entry. Its <code>user</code> is <code>null</code>.</td></tr><tr><td><code>book_diffs[]</code></td><td>array</td><td>Ordered changes to the resting book. Apply them in array order.</td></tr><tr><td><code>book_diffs[].user</code></td><td>string</td><td>Account address of the order.</td></tr><tr><td><code>book_diffs[].oid</code></td><td>number</td><td>Exchange order ID.</td></tr><tr><td><code>book_diffs[].px</code></td><td>string</td><td>Price of the order. Decimal string.</td></tr><tr><td><code>book_diffs[].coin</code></td><td>string</td><td>Canonical market name.</td></tr><tr><td><code>book_diffs[].raw_book_diff</code></td><td>string or object</td><td>One of the four shapes below.</td></tr></tbody></table>

#### **Book diff shapes**

`raw_book_diff` has four shapes. Apply `book_diffs` in array order.

| Shape                                                        | Meaning                                                                                       |
| ------------------------------------------------------------ | --------------------------------------------------------------------------------------------- |
| `{ "new": { "sz": "0.025" } }`                               | A new resting order. Append it at the back of its price level.                                |
| `{ "new": { "sz": "0.025", "insertBefore": 105338503858 } }` | A new resting order. Insert it ahead of the resting order with that `oid`, at the same price. |
| `{ "update": { "origSz": "0.025", "newSz": "0.010" } }`      | The size of a resting order changed from `origSz` to `newSz`.                                 |
| `"remove"`                                                   | The order left the book.                                                                      |

For `new`, take the other order fields from the `order_statuses` entry with the same `oid`. The `sz` in the diff is authoritative.

* Several entries with the same `oid` in one block: use the last one that places the order, which is `open`, or `triggered` for a fired trigger order. `filled` and `canceled` are never used. Price and size always come from the diff.
* An `update` keeps the order’s place in the queue. Only the size changes. `origSz` is informational.
* The same price can appear as `"63100"` in a snapshot and as `"63100.0"` in an update. Parse prices and sizes as numbers, never compare them as strings.

### Large snapshots

A snapshot larger than 3,000,000 encoded bytes is split into several `SnapshotPart` messages instead of one `Snapshot`.

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

```
{
  "channel": "l4Book",
  "data": {
    "SnapshotPart": {
      "coin": "BTC",
      "time": 1786905889616,
      "height": 123,
      "seq": 0,
      "total": 5,
      "bids": [],
      "asks": []
    }
  }
}
```

{% endcode %}
{% endtab %}

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

```
{
    "channel": "l4Book",
    "data": {
        "SnapshotPart": {
            "coin": "BTC",
            "time": 1786905889616,
            "height": 123,
            "seq": 0,
            "total": 5,
            "bids": [],
            "asks": [],
        }
    },
}
```

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

<table data-search="false"><thead><tr><th width="159.078125">Field</th><th width="148.432373046875">Type</th><th>Notes</th></tr></thead><tbody><tr><td><code>coin</code></td><td>string</td><td>Identical in all parts.</td></tr><tr><td><code>time</code></td><td>number</td><td>Identical in all parts.</td></tr><tr><td><code>height</code></td><td>number</td><td>Identical in all parts.</td></tr><tr><td><code>seq</code></td><td>number</td><td>Zero-based index of this part.</td></tr><tr><td><code>total</code></td><td>number</td><td>Number of parts. Identical in all parts.</td></tr><tr><td><code>bids</code></td><td>array</td><td>Bid orders of this part.</td></tr><tr><td><code>asks</code></td><td>array</td><td>Ask orders of this part.</td></tr></tbody></table>

Parts arrive back to back in increasing `seq` order. Append `bids` and `asks` in that order to get the same `levels` as a normal `Snapshot`. Apply `Updates` only after all parts have arrived.

The handler below assembles the parts and checks their order. `applySnapshot` and `applyUpdates` (Python: `apply_snapshot`, `apply_updates`) are your own functions.

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

```
let pending;

function handleL4Publication(envelope) {
  if (envelope.channel !== 'l4Book') return;
  const payload = envelope.data;

  if (payload.Snapshot) {
    pending = undefined;
    applySnapshot(payload.Snapshot);
    return;
  }

  if (payload.Updates) {
    if (pending) throw new Error('update arrived before snapshot completed');
    applyUpdates(payload.Updates);
    return;
  }

  const part = payload.SnapshotPart;
  if (!part) return;

  if (!Number.isInteger(part.seq) || !Number.isInteger(part.total) ||
      part.seq < 0 || part.total <= 0 || part.seq >= part.total) {
    throw new Error('invalid SnapshotPart sequence');
  }

  if (part.seq === 0) {
    pending = {
      coin: part.coin,
      time: part.time,
      height: part.height,
      total: part.total,
      next: 0,
      bids: [],
      asks: [],
    };
  }

  if (!pending || part.coin !== pending.coin ||
      part.time !== pending.time || part.height !== pending.height ||
      part.total !== pending.total || part.seq !== pending.next) {
    pending = undefined;
    throw new Error('incomplete or inconsistent SnapshotPart sequence');
  }

  pending.bids.push(...part.bids);
  pending.asks.push(...part.asks);
  pending.next += 1;

  if (pending.next === pending.total) {
    const snapshot = {
      coin: pending.coin,
      time: pending.time,
      height: pending.height,
      levels: [pending.bids, pending.asks],
    };
    pending = undefined;
    applySnapshot(snapshot);
  }
}
```

{% endcode %}
{% endtab %}

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

```
pending = None


def handle_l4_publication(envelope):
    global pending
    if envelope.get("channel") != "l4Book":
        return
    payload = envelope["data"]

    if "Snapshot" in payload:
        pending = None
        apply_snapshot(payload["Snapshot"])
        return
    if "Updates" in payload:
        if pending is not None:
            raise RuntimeError("update arrived before snapshot completed")
        apply_updates(payload["Updates"])
        return

    part = payload.get("SnapshotPart")
    if part is None:
        return
    if not (isinstance(part["seq"], int)
            and isinstance(part["total"], int)
            and 0 <= part["seq"] < part["total"]
            and part["total"] > 0):
        raise RuntimeError("invalid SnapshotPart sequence")

    if part["seq"] == 0:
        pending = {
            "coin": part["coin"],
            "time": part["time"],
            "height": part["height"],
            "total": part["total"],
            "next": 0,
            "bids": [],
            "asks": [],
        }

    if (pending is None
            or part["coin"] != pending["coin"]
            or part["time"] != pending["time"]
            or part["height"] != pending["height"]
            or part["total"] != pending["total"]
            or part["seq"] != pending["next"]):
        pending = None
        raise RuntimeError("incomplete or inconsistent SnapshotPart sequence")

    pending["bids"].extend(part["bids"])
    pending["asks"].extend(part["asks"])
    pending["next"] += 1

    if pending["next"] == pending["total"]:
        snapshot = {
            "coin": pending["coin"],
            "time": pending["time"],
            "height": pending["height"],
            "levels": [pending["bids"], pending["asks"]],
        }
        pending = None
        apply_snapshot(snapshot)
```

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

If a part is missing, its metadata changes, the stream ends, or any L4 update is lost, discard the partial or current book and resubscribe to get a new snapshot.

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

`l4book` never skips a message while you are subscribed. If your client falls too far behind, the subscription ends. After a reconnect, the new subscription starts with a snapshot. Heights can skip, because only blocks with order activity produce an update.

### Subscribe

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

```
const sub = client.newSubscription('l4book:BTC');

sub.on('publication', (ctx) => {
  try {
    handleL4Publication(ctx.data);
  } catch (err) {
    console.error(err.message);
    // Discard your local book here, then ask for a new snapshot.
    sub.unsubscribe();
    sub.subscribe();
  }
});

sub.subscribe();
```

{% endcode %}
{% endtab %}

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

```
async def resubscribe():
    await sub.unsubscribe()
    await sub.subscribe()


class L4Handler(SubscriptionEventHandler):
    async def on_publication(self, ctx):
        try:
            handle_l4_publication(ctx.pub.data)
        except RuntimeError as err:
            print(err)
            # Discard your local book here, then ask for a new snapshot.
            # Run the resubscribe as its own task. Awaiting it inside the handler blocks the client.
            asyncio.create_task(resubscribe())


sub = client.new_subscription("l4book:BTC", events=L4Handler())
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.coinmarketman.com/order-book-data/l4-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.
