> ## Documentation Index
> Fetch the complete documentation index at: https://docs.0xarchive.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Keep a live order book

> Keep a full-depth Hyperliquid or HIP-3 order book current over the 0xArchive WebSocket: one snapshot, then level changes you apply in order.

The `orderbook_full` channel (`hip3_orderbook_full` for HIP-3) sends every price level once, then the level changes from each block. The script below keeps the total size at every BTC price level from that one subscription and prints the best bid, best ask and level counts.

## The script

```python live_book.py theme={"theme":"github-dark"}
# Keep a live full-depth order book from 0xArchive
# python3 -m pip install "websockets>=14"
# OXARCHIVE_API_KEY=your_key python3 live_book.py
import asyncio, json, os, websockets

URL = "wss://api.0xarchive.io/ws"
CHANNEL = "orderbook_full"  # HIP-3: "hip3_orderbook_full"
SYMBOL = "BTC"              # HIP-3: "xyz:XYZ100"


async def heartbeat(ws):
    while True:
        await asyncio.sleep(25)
        await ws.send(json.dumps({"op": "ping"}))


def show(book):
    bids, asks = book["B"], book["A"]
    print("bid", max(bids, default=None), "ask", min(asks, default=None),
          "levels", len(bids), len(asks))


async def stream(book):
    key = os.environ["OXARCHIVE_API_KEY"]
    headers = {"Authorization": "Bearer " + key}
    sub = {"op": "subscribe", "channel": CHANNEL, "symbol": SYMBOL}
    # max_size=None: the snapshot is the whole book (~830 KB for BTC)
    async with websockets.connect(
        URL, additional_headers=headers, max_size=None
    ) as ws:
        await ws.send(json.dumps(sub))
        pinger = asyncio.create_task(heartbeat(ws))
        try:
            batches = 0
            async for raw in ws:
                m = json.loads(raw)
                if m["type"] == "l4_snapshot":
                    d = m["data"]
                    book["B"] = {x["px"]: x["sz"] for x in d["bids"]}
                    book["A"] = {x["px"]: x["sz"] for x in d["asks"]}
                    show(book)
                elif m["type"] == "l4_batch":
                    for u in m["data"]:
                        side = book[u["side"]]
                        if u["sz"] == 0:
                            side.pop(u["px"], None)
                        else:
                            side[u["px"]] = u["sz"]
                    batches += 1
                    if batches % 40 == 0:
                        show(book)
                elif m["type"] == "error":
                    if m.get("error_code") == "slow_consumer":
                        return  # changes were dropped: resubscribe
                    raise SystemExit(m.get("message"))
        finally:
            book.clear()  # stale until the next snapshot
            pinger.cancel()
            await asyncio.gather(pinger, return_exceptions=True)


async def main():
    book = {}
    while True:
        try:
            await stream(book)
        except websockets.InvalidStatus as e:
            if e.response.status_code < 500:
                raise  # 401: check the key
            print("reconnecting:", e)
        except (websockets.ConnectionClosed, OSError,
                asyncio.TimeoutError) as e:
            print("reconnecting:", e)
        await asyncio.sleep(1)


asyncio.run(main())
```

Save it as `live_book.py` and run it with your API key in `OXARCHIVE_API_KEY`, as the top comments show. It needs Python 3.9 or later and `websockets` 14 or later. For a HIP-3 market, change `CHANNEL` and `SYMBOL` as the comments show.

## How it works

**1. Connect with your key**

Send your API key in the opening handshake as `Authorization: Bearer <key>`. An invalid key is refused with HTTP 401 before the socket opens. [Connection](https://docs.0xarchive.io/websocket/connection.md) covers the full handshake.

**2. Subscribe**

Send one subscribe message per book. The server confirms with a `subscribed` message.

```json theme={"theme":"github-dark"}
{
  "op": "subscribe",
  "channel": "orderbook_full",
  "symbol": "BTC"
}
```

HIP-3 symbols keep the builder prefix and its case, such as `xyz:XYZ100`.

**3. Load the snapshot**

The first data message is an `l4_snapshot` holding every level: `data.bids` and `data.asks`, each level `{px, sz, n}` with price, total size and order count. Replace the book you hold with it. The top-level `last_block_number` is the block the snapshot reflects.

**4. Apply each batch in order**

Every `l4_batch` carries a list of level changes `{side, px, sz, n, bn}`. `side` is `B` for bids and `A` for asks, and `bn` is the block number. Set the level at `px` to size `sz` and order count `n`, and delete it when `sz` is `0`. The script keeps sizes only. Apply the changes in the order they arrive.

## Stay connected

The server sends a ping frame every 30 seconds, and `websockets` answers it automatically. The script also sends `{"op":"ping"}` every 25 seconds, and the server replies `{"type":"pong"}`. A connection with active subscriptions closes after 60 seconds without activity; [Keep-alive](https://docs.0xarchive.io/websocket/keep-alive.md) has the details.

A BTC snapshot is about 830 KB, and a busy batch can pass 200 KB. `websockets` caps messages at 1 MiB unless you set `max_size`, so the script turns the cap off.

When the connection drops, the script clears the book and reconnects. The new subscription opens with a fresh snapshot. A handshake refused with a 4xx status, such as 401 for an invalid key, stops the script instead of retrying.

## Keep up with the stream

A BTC book receives about 8 batches and 3,000 level changes a second. Keep the receive loop to the dictionary updates above, and run display, storage and signal work outside it. Read the book only while it holds both `B` and `A`. The script prints once every 40 batches for the same reason. To read the best bid and ask on every update, keep each side in a sorted structure such as `SortedDict` from `sortedcontainers` instead of calling `max` and `min`.

If the client falls behind, changes are dropped: the server sends an `error` with `error_code` `slow_consumer` and stops that subscription. The script then reconnects and starts again from a fresh snapshot.

## Credits

WebSocket data is billed per delivered message, at no more than 1 credit a message. The snapshot is one message, and each `l4_batch` is one message however many level changes it carries. A BTC book at about 8 batches a second costs at most about 8 credits a second. [Credits](https://docs.0xarchive.io/credits.md) covers estimating a job, and [Rate limits](https://docs.0xarchive.io/rate-limits.md) lists each plan's monthly credits.

## Next step

**Track individual orders instead of levels**

Subscribe to L4 diffs to hold every resting order with its queue position, or replay a past window from a checkpoint.

[Open the L4 order book](https://docs.0xarchive.io/websocket/l4-orderbook.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.