> 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/getting-started.md). Agents can also search and read this documentation through its [MCP server](https://docs.hypertracker.io/~gitbook/mcp).

# Getting Started

This page covers what all Order Book Data channels share. Payloads for each stream are on [Market Streams](https://docs.hypertracker.io/order-book-data/market-streams.md), [L2 Order Book](https://docs.hypertracker.io/order-book-data/l2-order-book.md), and [L4 Order Book](https://docs.hypertracker.io/order-book-data/l4-order-book.md).

In short:

1. Open one WebSocket connection and authenticate once.
2. Subscribe to one channel per stream and market, for example `bbo:BTC`.
3. Read each message from its two nested envelopes.
4. For L2 diffs and L4, keep a local book and rebuild it from a new snapshot after any interruption.

### Connect

```
wss://jp-ws.hypertracker.io/connection/websocket
```

Authenticate once when the connection opens, with the API key from your dashboard (the same one as for the REST API). See [Authentication](https://docs.coinmarketman.com/real-time-websocket-streams/authentication). Your plan must include Order Book Data, see [Plan limits and availability](https://docs.coinmarketman.com/order-book-data#plan-limits-and-availability). If your key leaks, generate a new one in your dashboard. This invalidates all previous keys.\
Use an SDK for most applications. See [Connecting with the SDK](https://docs.coinmarketman.com/real-time-websocket-streams/connecting-with-the-sdk). Without an SDK, follow the protocol rules in [Connecting with a Plain WebSocket](https://docs.coinmarketman.com/real-time-websocket-streams/connecting-with-a-plain-websocket): send `connect` first, reply `{}` to every `{}` ping, and split every frame on `\n` before parsing.

### Channels

<table data-search="false"><thead><tr><th width="112.1458740234375">Stream</th><th width="181">Channel</th><th width="115.3646240234375">Message type</th><th width="110.286376953125">Subscribe (data)</th><th>First publication</th><th width="108.338623046875">Later publications</th></tr></thead><tbody><tr><td>Best bid/offer</td><td><code>bbo:&#x3C;coin></code></td><td><code>bbo</code></td><td>Omit</td><td>Next BBO change</td><td>Changed BBO only</td></tr><tr><td>Mid price</td><td><code>mids:&#x3C;coin></code></td><td><code>mids</code></td><td>Omit</td><td>Next mid price change</td><td>Changed mid only</td></tr><tr><td>Trades</td><td><code>trades:&#x3C;coin></code></td><td><code>trades</code></td><td>Omit</td><td>Next trade batch</td><td>Every trade batch</td></tr><tr><td>All mid prices</td><td><code>allmids:stream</code></td><td><code>allMids</code></td><td>Omit or <code>{}</code></td><td>Immediate snapshot</td><td>Complete map when a mid changes</td></tr><tr><td>Full L2 book</td><td><code>l2book:&#x3C;coin></code></td><td><code>l2Book</code></td><td>Optional L2 selectors</td><td>Next applied block</td><td>Complete snapshots</td></tr><tr><td>L2 snapshot + diffs</td><td><code>l2bookdiff:&#x3C;coin></code></td><td><code>l2BookDiff</code></td><td>Optional L2 selectors</td><td>Next applied block (<code>snapshot: true</code>)</td><td>Changed levels only</td></tr><tr><td>L4 order book</td><td><code>l4book:&#x3C;coin></code></td><td><code>l4Book</code></td><td>Omit, <code>{}</code>, or matching <code>coin</code></td><td>Immediate snapshot</td><td>Order-level updates</td></tr></tbody></table>

* `bbo`, `mids`, and `trades` publish only new events. Subscribing does not return an earlier value.

### Message format

Every publication reaches a plain WebSocket client in two nested envelopes. The outer one belongs to the connection protocol. The inner one is the Order Book Data message.

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

```
{
  "push": {
    "channel": "bbo:BTC",
    "pub": {
      "data": {
        "channel": "bbo",
        "data": {
          "coin": "BTC",
          "time": 1786905889616,
          "bbo": [
            { "px": "63100.0", "sz": "1.5", "n": 3 },
            { "px": "63101.0", "sz": "0.8", "n": 2 }
          ]
        }
      }
    }
  }
}
```

{% endcode %}
{% endtab %}

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

```
{
    "push": {
        "channel": "bbo:BTC",
        "pub": {
            "data": {
                "channel": "bbo",
                "data": {
                    "coin": "BTC",
                    "time": 1786905889616,
                    "bbo": [
                        {"px": "63100.0", "sz": "1.5", "n": 3},
                        {"px": "63101.0", "sz": "0.8", "n": 2},
                    ],
                },
            },
        },
    },
}
```

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

| Path                    | Meaning                                                                                |
| ----------------------- | -------------------------------------------------------------------------------------- |
| `push.channel`          | Subscription channel, including the market.                                            |
| `push.pub.data.channel` | Message type: `bbo`, `mids`, `allMids`, `trades`, `l2Book`, `l2BookDiff`, or `l4Book`. |
| `push.pub.data.data`    | The stream payload. Each stream page documents it.                                     |

An SDK removes the outer wrapper. The message type and payload are then available on the publication context:

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

```
sub.on('publication', (ctx) => {
  const envelope = ctx.data;
  console.log(envelope.channel, envelope.data);
});
```

{% endcode %}
{% endtab %}

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

```
class SubHandler(SubscriptionEventHandler):
    async def on_publication(self, ctx):
        envelope = ctx.pub.data
        print(envelope["channel"], envelope["data"])
```

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

### Market names

Use the market name exactly as the [Info endpoint](https://docs.hypertracker.io/endpoints/hyperliquid-info-endpoints.md) returns it in `name`, for example `BTC`, `xyz:GOLD`, or `@107`. Names are case-sensitive. Spot markets are available on every channel. For spot, use the `name` from the `universe` list of `spotMeta`, not a token name.

To list markets, call the Perpetuals info endpoint with `{"type":"meta"}` for the main perpetuals. Call `{"type":"perpDexs"}` for the builder dexes, then `{"type":"meta","dex":"<dex>"}` for each. Call `{"type":"spotMeta"}` on the [Spot info endpoint](https://docs.coinmarketman.com/endpoints/hyperliquid-info-endpoints/spot) for spot markets. Skip entries with `"isDelisted": true`. Subscribing to a delisted market is rejected with `1084`. Open subscriptions to a market are closed when it is delisted. A market without an order book is rejected with `1071`.

Names that contain only the characters `A-Z a-z 0-9 @ . _ - / :` are sent as they are. Any other name must be sent as `~` followed by its URL-safe base64 without padding. A name in the wrong form is rejected with `1071` or receives no data. All currently supported markets need no encoding. The example below only shows the format: `#10570` becomes `~IzEwNTcw`.

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

```
const encodeCoin = (coin) =>
  '~' + btoa(String.fromCharCode(...new TextEncoder().encode(coin)))
    .replaceAll('+', '-')
    .replaceAll('/', '_')
    .replaceAll('=', '');

console.log(`l2book:${encodeCoin('#10570')}`); // l2book:~IzEwNTcw
```

{% endcode %}
{% endtab %}

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

```
import base64


def encode_coin(coin: str) -> str:
    return "~" + base64.urlsafe_b64encode(coin.encode()).decode().rstrip("=")


print(f"l2book:{encode_coin('#10570')}")  # l2book:~IzEwNTcw
```

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

### Subscribe

Send one `subscribe` command per channel after `connect` succeeds. Only `l2book` and `l2bookdiff` take selectors in the subscription data. There are no tag filters. See [L2 Order Book](https://docs.hypertracker.io/order-book-data/l2-order-book.md).

With an SDK, pass the selectors as subscription `data`:

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

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

{% endcode %}
{% endtab %}

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

```
sub = client.new_subscription("l2book:BTC", data={"nLevels": 10})
await sub.subscribe()
```

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

With a plain WebSocket, send the command yourself:

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

```
{ "id": 2, "subscribe": { "channel": "bbo:BTC" } }
```

{% endcode %}
{% endtab %}

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

```
{"id": 2, "subscribe": {"channel": "bbo:BTC"}}
```

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

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

```
{
  "id": 4,
  "subscribe": {
    "channel": "l2book:BTC",
    "data": { "nSigFigs": 5, "mantissa": 2, "nLevels": 10 }
  }
}
```

{% endcode %}
{% endtab %}

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

```
{
    "id": 4,
    "subscribe": {
        "channel": "l2book:BTC",
        "data": {"nSigFigs": 5, "mantissa": 2, "nLevels": 10},
    },
}
```

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

A successful reply carries the request `id` and an empty `subscribe` object:

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

```
{ "id": 4, "subscribe": {} }
```

{% endcode %}
{% endtab %}

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

```
{"id": 4, "subscribe": {}}
```

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

Initial data arrives as a normal publication. Match replies to commands by `id`, because a publication can arrive next to a reply and one frame can hold several JSON messages.

### Common fields

<table data-search="false"><thead><tr><th width="235.0989990234375">Field</th><th>Meaning</th></tr></thead><tbody><tr><td><code>coin</code></td><td>Canonical, case-sensitive market name.</td></tr><tr><td><code>time</code></td><td>Source event or block time in Unix epoch milliseconds. <br>Exception: <code>order_statuses[].time</code> is a node timestamp string.</td></tr><tr><td><code>height</code></td><td>Source block height. Use it to order L2 diff and L4 state transitions.</td></tr><tr><td><code>side</code></td><td><code>B</code> for bid or buy, <code>A</code> for ask or sell. On trades, it is the aggressor side.</td></tr><tr><td><code>px</code>, <code>limitPx</code>, <code>triggerPx</code></td><td>Decimal price strings.</td></tr><tr><td><code>sz</code>, <code>origSz</code>, <code>newSz</code></td><td>Decimal size strings.</td></tr><tr><td><code>levels[0]</code>, <code>levels[1]</code></td><td>Bids, then asks. Both sides are best price first.</td></tr></tbody></table>

{% hint style="warning" %}
Prices and sizes are decimal strings. Parse them with a decimal library, because floating point can lose precision.
{% endhint %}

### Errors

A failed command returns the request `id` with an `error` instead of `subscribe`:

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

```
{
  "id": 4,
  "error": {
    "code": 1071,
    "message": "centrifugo proxy: validate l2Book: sig figs aren't set correctly"
  }
}
```

{% endcode %}
{% endtab %}

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

```
{
    "id": 4,
    "error": {
        "code": 1071,
        "message": "centrifugo proxy: validate l2Book: sig figs aren't set correctly",
    },
}
```

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

<table><thead><tr><th width="72.885498046875">Code</th><th>Meaning</th><th>Solution</th></tr></thead><tbody><tr><td><code>105</code></td><td>Already subscribed to this exact channel on this connection.</td><td>Reuse the subscription or unsubscribe first. Use a second connection for another L2 selector set on the same channel.</td></tr><tr><td><code>1071</code></td><td>Malformed channel or data, unknown market, or invalid selectors.</td><td>Correct the request. Retrying it unchanged will not help.</td></tr><tr><td><code>1072</code></td><td>A valid subscription could not get its initial state in time.</td><td>Retry with backoff.</td></tr><tr><td><code>1073</code></td><td>Subscription denied for a reason without a specific code. The message gives the reason.</td><td>Read the message. Request access, or use an authorized key.</td></tr><tr><td><code>1074</code></td><td>The authorization service was unavailable.</td><td>Retry with backoff.</td></tr></tbody></table>

Retryable errors include `"temporary": true`. The field can be absent on an error that is not temporary. In an SDK, the same details are available on the subscription’s `error` and `unsubscribed` events.

#### Plan and limit errors

* `1080` WS\_NOT\_ENTITLED: your plan does not include WebSocket access
* `1081` WS\_CONNECTION\_LIMIT, temporary: too many open connections
* `1082` WS\_SUBSCRIPTION\_LIMIT, temporary: too many active subscriptions
* `1083` WS\_ORDERBOOK\_LIMIT, temporary: too many order book streams
* `1084` WS\_STREAM\_NOT\_ALLOWED: this channel is not included in your plan, or the market is delisted.
* `1086` WS\_ACCESS\_UNAVAILABLE, temporary: access could not be checked right now, retry shortly
* `1087` WS\_MESSAGE\_RATE\_LIMIT, temporary: too many client messages per minute. Not temporary if your plan allows no client messages.
* `1088` WS\_CONNECT\_RATE\_LIMIT, temporary: too many connection attempts per minute.
* `401`: missing or invalid key

On `l2book`, `l2bookdiff`, `l4book`, `allmids`, and `orders`, retry the subscription yourself after `1081` to `1083`, `1086`, or `1087`. The client library does not retry these channels automatically.

If your plan no longer includes WebSocket access, the connection closes with code `4585`. If a channel is no longer allowed, the subscription ends with code `2000`. Plan changes reach open connections within about 2 minutes.

### Delivery and recovery

* Order Book Data channels have no replay. Do not send `recover`, `epoch`, `offset`, or the SDK `since` option. Replay is available only for Fills, Account Events, and TWAPs, see [Replaying Missed Data](https://docs.hypertracker.io/websocket-streams/replaying-missed-data.md).
* After a reconnect, `allmids` and `l4book` start with an immediate snapshot, `l2book` and `l2bookdiff` with the next applied block, and `bbo`, `mids`, and `trades` with the next new publication.
* `l2bookdiff` and `l4book` never skip a message while the subscription is open. If your client falls too far behind, the subscription ends. Subscribe again for a fresh snapshot.
* `l2book`, `allmids`, `bbo`, and `mids` carry the full state. A slow client can skip older messages and gets the latest one.
* Trades are best effort. Skipped trades are reported by a message with a `gap` field on the same channel. Use `coin` and `tid` to drop duplicates.
* Messages have no sequence number or event ID. A jump in `height` is normal, because messages are sent only for blocks where something changed.

{% hint style="warning" %}
Losing one L2 diff or L4 update can corrupt your local book. If a subscription ends, discard the local state, resubscribe, and start again from the new snapshot.
{% endhint %}

#### Slow clients

Each connection has a 64 MB outgoing buffer. If more than 64 MB of messages queue up, the connection is closed with `3008 slow`. A full BTC L4 snapshot (about 17 MB) fits in the buffer, so the snapshot alone does not trigger it. Read messages promptly and do heavy processing off the receiving thread.

### Complete client examples

These examples subscribe to BBO, trades, and a 10-level L2 diff book for BTC over one connection.

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

```
// npm install centrifuge
import { Centrifuge } from 'centrifuge';

const client = new Centrifuge('wss://jp-ws.hypertracker.io/connection/websocket', {
  websocket: globalThis.WebSocket,
  data: { token: API_KEY },
});
client.on('error', (ctx) => console.error(ctx.error?.message ?? ctx.error));
client.on('disconnected', (ctx) => console.error(ctx.code, ctx.reason));

const definitions = [
  ['bbo:BTC', {}],
  ['trades:BTC', {}],
  ['l2bookdiff:BTC', { data: { nSigFigs: 5, mantissa: 2, nLevels: 10 } }],
];

for (const [channel, options] of definitions) {
  const sub = client.newSubscription(channel, options);
  sub.on('subscribed', () => console.log('subscribed', channel));
  sub.on('publication', (ctx) => {
    // ctx.data is { channel: <message type>, data: <payload> }
    console.log(channel, ctx.data.channel, ctx.data.data);
  });
  sub.on('error', (ctx) => console.error(channel, ctx.error?.message ?? ctx.error));
  sub.on('unsubscribed', (ctx) => {
    if (ctx.code) console.warn('unsubscribed', channel, ctx.code, ctx.reason);
  });
  sub.subscribe();
}

client.connect();
```

{% endcode %}
{% endtab %}

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

```
# pip install centrifuge-python
import asyncio
import os

from centrifuge import Client, ClientEventHandler, SubscriptionEventHandler

API_KEY = os.environ["API_KEY"]

DEFINITIONS = [
    ("bbo:BTC", None),
    ("trades:BTC", None),
    ("l2bookdiff:BTC", {"nSigFigs": 5, "mantissa": 2, "nLevels": 10}),
]


class ClientHandler(ClientEventHandler):
    async def on_connected(self, ctx):
        print("connected:", ctx.client)

    async def on_error(self, ctx):
        print("client error:", ctx.error)


class SubHandler(SubscriptionEventHandler):
    def __init__(self, channel):
        self.channel = channel

    async def on_subscribed(self, ctx):
        print("subscribed", self.channel)

    async def on_publication(self, ctx):
        envelope = ctx.pub.data
        print(self.channel, envelope["channel"], envelope["data"])

    async def on_error(self, ctx):
        print(self.channel, "error:", ctx.error)

    async def on_unsubscribed(self, ctx):
        print("unsubscribed", self.channel, ctx.code, ctx.reason)


async def main():
    client = Client(
        "wss://jp-ws.hypertracker.io/connection/websocket",
        events=ClientHandler(),
        data={"token": API_KEY},
    )
    await client.connect()
    for channel, data in DEFINITIONS:
        sub = client.new_subscription(channel, events=SubHandler(channel), data=data)
        await sub.subscribe()
    await asyncio.Event().wait()


asyncio.run(main())
```

{% 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/getting-started.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.
