> For the complete documentation index, see [llms.txt](https://docs.hydromancer.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.hydromancer.xyz/readme/websocket/orderbook-streaming/l4bookupdates.md).

# l4BookUpdates

Stream real-time L4 orderbook updates per block.

{% hint style="info" %}
💧 New endpoint - this endpoint is not a part of original Hyperliquid API and is added by us for builder convenience.
{% endhint %}

Streams every order change (new, update, remove) for the markets you subscribe to, one message per block. Every message has both `"type"` and `"channel"` set to `"l4BookUpdates"`; route on either.

### Subscribe

```json
{
    "method": "subscribe",
    "subscription": {
        "type": "l4BookUpdates",
        "coins": ["ETH", "BTC"]
    }
}
```

| Parameter     | Type      | Required | Description                                                                                                                                     |
| ------------- | --------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `coins`       | string\[] | No       | Coins to subscribe to, at most 200 per request. Omit for all markets (needs the **l4BookUpdatesAll** add-on).                                   |
| `marketTypes` | string\[] | No       | All markets only. Picks which market types you get, see [All-markets filter](#all-markets-filter). Can't be combined with `coins`.              |
| `merge`       | bool      | No       | Default `false`. `true` adds these coins to your existing coin-list subscription instead of opening a new one. Subscribe only, coin lists only. |

### Adding coins (`merge`)

By default each subscribe opens its own stream: subscribing to `["ETH"]` and then `["BTC"]` gives you two messages per block.

With `"merge": true` the new coins join your existing coin-list subscription:

* From the next block, one message covers all your coins. No gap and no missed block.
* The ack lists the full merged coin list. Coins you already have are ignored.
* The merged list can't go over your tier's coin cap. If it would, the subscribe is rejected and nothing changes.
* With a `cursor`, replay covers only the coins named in that request, even though the ack lists all of them.

**The ack is the switch-over point.** Messages that arrive before the ack may still use the old coin list; messages after it use the new one. Each message lists its coins in `coins`, so you can always check. Rarely, when the server is under load, a few messages right after the ack can still miss a just-added coin. This clears within a few blocks.

{% hint style="warning" %}
**Planned change: `merge: true` will become the default.** Set `merge` explicitly on every coin-list subscribe: `true` opts in now, `false` keeps today's behaviour after the switch. The flag stays supported. This only affects connections that subscribe to coin lists more than once.
{% endhint %}

### All-markets filter

Omit `coins` to get every market. `marketTypes` picks which types: `"perp"`, `"spot"`, `"outcome"`, or `["*"]` for all types, including ones added later.

```json
{
    "method": "subscribe",
    "subscription": {
        "type": "l4BookUpdates",
        "marketTypes": ["perp", "outcome"]
    }
}
```

* The default is `["perp"]`. Spot and outcome markets only appear if you ask for them, and new types are never added to the default.
* Subscribing again with a different `marketTypes` replaces the filter.
* An all-markets subscription can run next to a coin-list subscription on the same connection. Coins in both are delivered twice.

### Unsubscribe

```json
{
    "method": "unsubscribe",
    "subscription": {
        "type": "l4BookUpdates",
        "coins": ["ETH"]
    }
}
```

* **One coin-list subscription:** the named coins are removed and the rest keep streaming without a gap. Coins you don't hold are ignored. Removing the last coin ends the subscription.
* **Several coin-list subscriptions:** `coins` must exactly match one of them, and only that one is removed.
* **No `coins`:** removes the all-markets subscription only, not your coin lists. You can't remove single coins from an all-markets subscription.

As with subscribe, the ack is the switch-over point: no message after the ack contains the removed coins.

### Update data format

You get a message for **every** block, with `diffs: []` when none of your coins changed, so `height` never skips. Coin-list messages include `coins`, the subscription's sorted coin list, which tells you which subscription a message belongs to. All-markets messages don't include `coins`.

```json
{
    "type": "l4BookUpdates",
    "channel": "l4BookUpdates",
    "seq": 1,
    "cursor": "500:1704067200000",
    "coins": ["ETH"],
    "data": {
        "height": 782007304,
        "timestamp": 1704067200000,
        "diffs": [
            {
                "type": "new",
                "coin": "ETH",
                "oid": 217148811876,
                "user": "0x742d35cc6634c0532925a3b844bc9e7595f7f2e2",
                "side": "B",
                "px": "3245.50",
                "sz": "1.5"
            },
            {
                "type": "new",
                "coin": "ETH",
                "oid": 217148811877,
                "user": "0x8f3c55aa1122c0532925a3b844bc9e7595f7f9a1",
                "side": "B",
                "px": "3245.50",
                "sz": "0.8",
                "insertBefore": 217148811876
            },
            {
                "type": "update",
                "coin": "ETH",
                "oid": 217148811800,
                "sz": "2.0"
            },
            {
                "type": "remove",
                "coin": "ETH",
                "oid": 217148811750
            }
        ]
    }
}
```

### Diff types

| Type     | Description                       | Fields                                                               |
| -------- | --------------------------------- | -------------------------------------------------------------------- |
| `new`    | New order placed                  | `coin`, `oid`, `user`, `side`, `px`, `sz`, `insertBefore` (optional) |
| `update` | Order size changed (partial fill) | `coin`, `oid`, `sz`                                                  |
| `remove` | Order removed (filled/cancelled)  | `coin`, `oid`                                                        |

### Field definitions

| Field          | Type                | Description                                                                                                                                                                            |
| -------------- | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `coins`        | string\[]           | Coin-list messages only. The subscription's sorted coin list, not just the coins that changed.                                                                                         |
| `height`       | int                 | Block height                                                                                                                                                                           |
| `timestamp`    | int                 | Block timestamp (ms since epoch)                                                                                                                                                       |
| `coin`         | string              | Market symbol (e.g., "ETH", "BTC")                                                                                                                                                     |
| `oid`          | int                 | Unique order ID                                                                                                                                                                        |
| `user`         | string              | User address (0x...)                                                                                                                                                                   |
| `side`         | string              | "B" = bid, "A" = ask                                                                                                                                                                   |
| `px`           | string              | Price as decimal string                                                                                                                                                                |
| `sz`           | string              | Size as decimal string                                                                                                                                                                 |
| `insertBefore` | int (oid), optional | `new` only. Place this order in its price level's queue directly in front of the order with this oid (Hyperliquid ALO priority). If absent, or that order is gone, add it to the back. |

### Replay and gaps

When you resubscribe with a `cursor`, the server first replays the blocks you missed (see [Session Management and Reconnection](https://docs.hydromancer.xyz/readme/websocket/session-management-and-reconnection.md)).

* Replay can skip heights where none of your coins changed, and can include blocks with empty `diffs`. For those, just advance your height and cursor. Live messages never skip heights.
* **`hasGap: true` means the replay is incomplete** and can't rebuild your book. Throw away the affected book and its cursor. Keep buffering live updates, fetch a fresh [`l4Book`](https://docs.hydromancer.xyz/readme/rest-api/market-data/l4book.md) snapshot, then apply the buffered updates above the snapshot's height.

#### Automatic snapshot recovery (rolling out)

{% hint style="info" %}
This is being rolled out and is not on everywhere yet. Until you receive `l4BookSnapshot` messages, use the REST rebuild above.
{% endhint %}

With recovery on, the server follows `hasGap` with the current book as `l4BookSnapshot` messages, so you don't need the REST call. A subscribe without a `cursor` also gets this. The messages arrive automatically; don't subscribe to them. Each one has a `seq`, a `cursor` (informational only) and a `data` like this:

```json
{
  "scope": {"coins": ["BTC"], "marketTypes": null},
  "height": 100,
  "timestamp": 1700000000000,
  "coins": ["BTC"],
  "chunk": 0,
  "totalChunks": 1,
  "isFinal": true,
  "markets": [{"coin": "BTC", "bids": [], "asks": []}]
}
```

To apply it:

1. Collect the chunks separately from your live books. A large coin can span several chunks; join its `bids` and `asks` in chunk order.
2. Check that every chunk has the same `scope`, `height`, `timestamp` and `coins`, that `chunk` counts up from 0 to `totalChunks - 1`, and that the last one has `isFinal: true`.
3. Only then replace your books. Apply live updates above `height` before you save a cursor.

If recovery fails you get an `l4BookRecoveryUnavailable` message with `scope`, `coins` and a `reason` (`snapshotSource`, `incompleteSpan`, `deadline`, `budget` or `cancelled`). Your other subscriptions keep running. Rebuild the affected books through REST, as you would if no snapshot arrives within 15 seconds.

The Python SDK does all of this for you. It caps snapshot memory at 1 GiB by default; change it with `L4OrderbookClient(snapshot_max_bytes=...)`.

Snapshot recovery is L4 only. `l2BookDiff` still resyncs through REST.

### Examples

{% tabs %}
{% tab title="JavaScript" %}

```javascript
const WebSocket = require('ws');

const ws = new WebSocket(`wss://api.hydromancer.xyz/ws?token=${process.env.HYDROMANCER_API_KEY}`);

ws.on('open', () => {
    ws.send(JSON.stringify({
        method: 'subscribe',
        subscription: {
            type: 'l4BookUpdates',
            coins: ['ETH', 'BTC']
        }
    }));
});

ws.on('message', (data) => {
    const msg = JSON.parse(data);

    if (msg.type === 'ping') {
        ws.send(JSON.stringify({ method: 'pong' }));
    } else if (msg.type === 'l4BookUpdates') {
        const { height, diffs } = msg.data;
        console.log(`Height ${height}: ${diffs.length} order changes`);
    }
});
```

{% endtab %}

{% tab title="Python" %}

```python
import websocket
import json
import os

def on_message(ws, message):
    msg = json.loads(message)

    if msg.get('type') == 'ping':
        ws.send(json.dumps({'method': 'pong'}))
    elif msg.get('type') == 'l4BookUpdates':
        data = msg['data']
        print(f"Height {data['height']}: {len(data['diffs'])} order changes")

def on_open(ws):
    ws.send(json.dumps({
        "method": "subscribe",
        "subscription": {
            "type": "l4BookUpdates",
            "coins": ["ETH", "BTC"]
        }
    }))

if __name__ == "__main__":
    api_key = os.environ.get('HYDROMANCER_API_KEY')
    ws = websocket.WebSocketApp(f'wss://api.hydromancer.xyz/ws?token={api_key}',
                                on_open=on_open,
                                on_message=on_message)
    ws.run_forever()
```

{% endtab %}
{% endtabs %}

### Common errors

Error and warning formats are described in the [WebSocket overview](https://docs.hydromancer.xyz/readme/websocket.md#correlating-subscription-feedback).

1. `invalid coin name(s): [...]` - Lists every invalid name in the request. Nothing is subscribed.
2. `too_many_coins` - More than 200 coins in one request, or a `merge: true` subscribe would go over your tier's coin cap. Your existing subscription is unchanged.
3. `Subscribing to all markets requires permission` - Needs the **l4BookUpdatesAll** add-on.
4. `Rate limit exceeded` - Subscribe less often.
5. `Authentication failed` - Check your API key.

A valid but inactive coin is accepted with an `inactive_coins` warning, so you know why it sends no data.
