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

Reconstruction is for applications that need a local book over time instead of independent snapshots.

## Pattern

<Steps>
  <Step title="Start from a snapshot">
    Load the initial book state from REST or the first WebSocket snapshot.
  </Step>

  <Step title="Apply diffs in timestamp order">
    Ignore messages older than the snapshot timestamp and apply updates in order.
  </Step>

  <Step title="Detect gaps">
    If replay or live streams emit a gap signal, mark the local book as unsafe until it is rebuilt.
  </Step>

  <Step title="Resync when needed">
    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
```

## Inputs

Reconstruction needs a trustworthy starting point and ordered changes. The starting point can come from a REST snapshot, a WebSocket snapshot, or a checkpoint route where the venue family supports it. Changes can come from diffs, replay messages, or a bounded historical stream. Store the source route or channel with every run.

## TypeScript Reconstruction Helpers

The TypeScript SDK exposes Lighter tick-history helpers and an `OrderBookReconstructor` for workflows that need checkpoint plus delta reconstruction.

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

const tickData = await client.lighter.orderbook.historyTick("BTC", {
  start: Date.now() - 3_600_000,
  end: Date.now()
});

const reconstructor = client.lighter.orderbook.createReconstructor();
const finalBook = reconstructor.reconstructFinal(
  tickData.checkpoint,
  tickData.deltas
);

const gaps = OrderBookReconstructor.detectGaps(tickData.deltas);
if (gaps.length > 0) {
  throw new Error(`Unsafe reconstruction: ${gaps.length} gap(s)`);
}
```

For larger windows, prefer the SDK's async iterator helper where available so pagination and reconstruction state stay together:

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

Use these helpers only where the venue, plan, and route support the required depth. For other families, keep the same reconstruction discipline but use the documented REST and WebSocket route family for that market.

## Python And Rust Helpers

The Python and Rust SDKs also expose reconstruction-oriented types and helpers. Use the package README for exact import paths and method names, then keep the same manifest and gap policy from this page.

| Runtime    | Package surface                                               | Use it for                                                                          |
| ---------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| Python     | `oxarchive`, `OrderBookReconstructor`, WebSocket extra        | Notebook or pipeline reconstruction with typed models and optional stream callbacks |
| Rust       | `oxarchive`, `orderbook_reconstructor`, `websocket` feature   | Async services and backtest runners that need typed reconstruction behavior         |
| TypeScript | `@0xarchive/sdk`, `OrderBookReconstructor`, WebSocket helpers | App and worker code that needs checkpoint-plus-delta reconstruction                 |

If a runtime helper is missing for the venue family, use the REST/WebSocket route directly and keep the same reconstruction checklist instead of pretending every SDK has the same method.

## Gap Policy

A local book is only as trustworthy as its gap handling. If a replay, diff stream, or checkpoint route reports a missing segment, mark the local state unsafe and rebuild. Do not keep applying newer updates to a state that has an unknown hole. That can produce plausible but wrong depth.

## 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/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 capped depth level                                               |
| Code surface            | SDK package/version, generated client, or direct REST/WebSocket path          |

## Venue Family Notes

Hyperliquid core, Hyperliquid Spot, HIP-3, HIP-4, and Lighter can expose different depth primitives. Keep the reconstruction code aware of venue family rather than trying to normalize every stream into one generic path. Use [Venue coverage](/venue-coverage) and Endpoint Reference pages before sharing reconstruction code across families.

## Review Rule

Any reconstruction example should include a resync path. If the local book has no way to recover from a missing diff, unavailable checkpoint, or replay gap, it is a demo, not reconstruction logic a production client should trust.
The resync path should be testable with a forced gap or closed connection, and the rebuild trigger should be documented beside the manifest.
