> ## 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.

# Order-book reconstruction

> Maintain local order books from 0xArchive snapshots, diffs, replay streams, SDK helpers, and reconciliation checkpoints.

Keep a local order book over time from a starting snapshot and ordered changes, with the SDK reconstruction helpers or your own code, and rebuild it whenever a gap appears. If you only need independent snapshots, read them from REST instead.

## Pattern

<Steps>
  <Step title="Start from a snapshot">
    Load the starting book from a REST snapshot, a checkpoint route, or the first WebSocket snapshot. A snapshot-only read stops here and applies no changes.
  </Step>

  <Step title="Apply ordered changes">
    For [L4 WebSocket state](/websocket/l4-orderbook), apply the server's ordered events after the `l4_snapshot` and keep its `last_block_number`. For [Lighter L3 tick history](/rest-api/order-books-l3), apply the checkpoint first, then each delta in `sequence` order. Never sort or discard updates by timestamp alone.
  </Step>

  <Step title="Detect gaps">
    When a replay or live stream reports a gap, or an ordered sequence skips, mark the local book unsafe until it is rebuilt.
  </Step>

  <Step title="Resync">
    Pull a fresh snapshot and resume from the latest known safe point.
  </Step>
</Steps>

```mermaid theme={"theme":"github-dark"}
flowchart LR
  A["Snapshot"] --> B["Diff batch"]
  B --> C["Local book"]
  C --> D{"Gap?"}
  D -->|no| B
  D -->|yes| E["Resync snapshot"]
  E --> C
```

Record where the snapshot and the changes came from (route, channel, or replay) with every run.

## TypeScript helpers

The TypeScript SDK reads Lighter tick history and rebuilds the book with `OrderBookReconstructor`. `historyTick` returns one page: the checkpoint at `start` and the first 100 deltas after it. The window below ends now, inside every plan's history, including Free's most recent 30 days.

```typescript theme={"theme":"github-dark"}
import { OxArchive } from "@0xarchive/sdk";

const client = new OxArchive({ apiKey: process.env.OXARCHIVE_API_KEY! });

const tickData = await client.lighter.orderbook.historyTick("BTC", {
  start: Date.now() - 5 * 60_000,
  end: Date.now()
});

const reconstructor = client.lighter.orderbook.createReconstructor();
const book = reconstructor.reconstructFinal(tickData.checkpoint, tickData.deltas);
console.log(tickData.deltas.length, "deltas applied; best bid", book.bids[0]?.px, "best ask", book.asks[0]?.px);
```

`iterateTickHistory` yields the rebuilt book after each delta of that page instead of only the final state:

```typescript theme={"theme":"github-dark"}
for await (const snapshot of client.lighter.orderbook.iterateTickHistory("BTC", {
  start: Date.now() - 60_000,
  end: Date.now()
})) {
  console.log(snapshot.timestamp, snapshot.midPrice);
}
```

Lighter delta `sequence` values set the order to apply deltas in; they are not consecutive within one market, so a jump between two sequence numbers is not a gap. To continue past the first page, call the Lighter order-book history route ([L2 order books](/rest-api/order-books-l2)) with `granularity=tick` and follow `meta.next_cursor`.

Each venue family exposes its own depth. Lighter L3 is separate from Hyperliquid L4. [L4 REST routes](/rest-api/order-books-l4) and checkpoint-anchored WebSocket replay cover Hyperliquid core, Spot, HIP-3, and HIP-4, and [full-depth L2](/rest-api/order-books-l2) covers Hyperliquid core and HIP-3. Every plan reaches the same depth; plans differ in credits, request rate, concurrency, standard replay speed, history window, and exports.

## Python and Rust helpers

| Runtime | Helpers |
| - | - |
| Python | `oxarchive` with `OrderBookReconstructor` and `L4OrderBookReconstructor`, plus the `websocket` extra for stream callbacks |
| Rust | `oxarchive` with the `orderbook_reconstructor` and `l4_reconstructor` modules, plus the `websocket` feature for async services and backtest runners |
| TypeScript | `@0xarchive/sdk` with `OrderBookReconstructor`, `L4OrderBookReconstructor`, and the WebSocket helpers |

`L4OrderBookReconstructor` rebuilds Hyperliquid core and HIP-3 L4 books from a checkpoint and its diffs. Exact import paths and method names are in each package's README. When a runtime has no helper for your venue family, use the REST or WebSocket route directly and follow the same pattern and gap rule.

## Gap rule

A local book is only as trustworthy as its gap handling. When a replay, diff stream, or checkpoint route reports a missing segment, mark the state unsafe and rebuild. Applying newer updates on top of an unknown hole produces depth that looks plausible and is wrong.

Before relying on a reconstruction path, force a gap or close the connection and confirm the book rebuilds. Record what triggered the rebuild in the manifest.

## Reconstruction manifest

Store a manifest beside reconstructed output.

| Field | Store |
| - | - |
| Venue family and symbol | Lighter `BTC`, Spot `HYPE-USDC`, HIP-3 `km:US500`, or another explicit family |
| Baseline source | REST snapshot, WebSocket snapshot, checkpoint route, or replay snapshot |
| Update source | Diffs, replay stream, tick history, or live channel |
| Window | Start and end timestamps, and any cursor or iterator state |
| Gap state | Gap list, rebuild trigger, and whether the output is complete |
| Output depth | Full book or a capped depth |
| Code | SDK package and version, generated client, or direct REST or WebSocket path |

Keep reconstruction code aware of the venue family instead of normalizing every stream into one path: Hyperliquid core, Spot, HIP-3, HIP-4, and Lighter expose different depth. Check [Venue coverage](/venue-coverage) before sharing code across families.

## Next step

Follow a live order-level book from snapshot to diffs with [WebSocket L4 order book](/websocket/l4-orderbook).


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