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

# SDK WebSocket usage

> Use 0xArchive SDK helpers for WebSocket live subscriptions, historical replay, reconnect behavior, and order-book reconstruction.

Use SDK WebSocket helpers when you want reconnection handling, message typing, and subscription state in application code.

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

const ws = new OxArchiveWs({
  apiKey: process.env.OXARCHIVE_API_KEY!
});

ws.connect();
ws.subscribeOrderbook("BTC");

ws.onOrderbook((symbol, data) => {
  console.log(symbol, data.midPrice);
});
```

```python Python theme={"theme":"github-dark"}
import asyncio
from os import environ
from oxarchive import OxArchiveWs, WsOptions

async def main():
    ws = OxArchiveWs(WsOptions(api_key=environ["OXARCHIVE_API_KEY"]))

    ws.on_historical_data(lambda symbol, timestamp, data: print(symbol, timestamp))
    ws.on_gap(lambda channel, symbol, start, end, minutes: print("gap", channel, symbol, minutes))

    await ws.connect()
    await ws.replay(
        "orderbook",
        "BTC",
        start=1704067200000,
        end=1704153600000,
        speed=10,
    )

asyncio.run(main())
```

<CardGroup cols={2}>
  <Card title="Connection" icon="plug" href="/websocket/connection">
    Raw WebSocket connection pattern.
  </Card>

  <Card title="Replay" icon="rotate-ccw" href="/websocket/replay">
    Historical playback commands and gap handling.
  </Card>
</CardGroup>

## SDK Responsibilities

An SDK WebSocket helper should reduce boilerplate without hiding stream risk. The caller still needs to know when the socket opened, which channels are active, whether a replay is running, and whether a gap or reconnect made local state unsafe.

Use helpers for connection setup, subscription state, typed messages, and reconnection. Keep application-level policy in your code: whether to pause, resync, rebuild a book, retry a replay window, or mark output incomplete. That separation keeps market-data correctness visible in code review.

## Connection Contract

Use connection callbacks to record stream state instead of treating `connect()` as the whole workflow.

```typescript theme={"theme":"github-dark"}
ws.connect({
  onOpen: () => console.log("connected"),
  onClose: (code, reason) => console.log("closed", code, reason),
  onError: (error) => console.error("websocket error", error)
});
```

Track active subscriptions, latest message time, reconnect count, and unsafe symbols in application state. SDK reconnect behavior can restore transport, but the app still decides whether a local book, alert, or replay output is safe after a close or gap.

## Replay And Gap Callbacks

Historical replay data arrives through replay-specific callbacks, not through the same live subscription callbacks.

```typescript theme={"theme":"github-dark"}
ws.onHistoricalData((symbol, timestamp, data) => {
  console.log(new Date(timestamp).toISOString(), symbol, data);
});

ws.onGap((channel, symbol, gapStart, gapEnd, durationMinutes) => {
  console.warn("gap", channel, symbol, gapStart, gapEnd, durationMinutes);
});

ws.replay("orderbook", "BTC", {
  start: Date.now() - 86_400_000,
  end: Date.now(),
  speed: 10
});
```

Store replay channel, symbol, start, end, speed, gap callbacks, and output destination with the result. Use [WebSocket replay](/websocket/replay) when the event sequence is the product requirement.

## SDK Event Checklist

SDK helpers may wrap raw WebSocket messages, but the underlying event model still matters.

| Event class      | What to preserve                                                                  |
| ---------------- | --------------------------------------------------------------------------------- |
| Connection       | open time, close code, close reason, retry count, and active subscriptions        |
| Live data        | channel, symbol, venue family, timestamp, and latest applied state                |
| Replay start     | channel or channels, symbol, start, end, speed, and output destination            |
| Replay snapshots | `replay_snapshot` baseline before `historical_data` messages                      |
| Replay data      | timestamp, channel, symbol, and emitted order                                     |
| Gaps             | `gap_detected` interval, duration, affected output, and rebuild decision          |
| Terminal state   | `replay_completed`, `replay_stopped`, retry budget exhausted, or consumer stopped |

If the SDK only exposes higher-level callbacks, attach this checklist in the application logs or result manifest.

## Testing A Stream

Test with one channel and one symbol before widening. Confirm open, message, close, reconnect, unsubscribe, and gap paths. For replay, store the input window and speed with the output. For live streams, store the first snapshot timestamp and the latest applied update timestamp.

## Subscription Methods

Keep helper names tied to venue family.

| Workflow                    | Example helper                                         |
| --------------------------- | ------------------------------------------------------ |
| Hyperliquid core order book | `ws.subscribeOrderbook("BTC")`                         |
| Live trades                 | `ws.subscribeTrades("ETH")`                            |
| HIP-4 outcome market        | `ws.subscribeHip4("hip4_orderbook", "0")`              |
| Spot pair                   | `ws.subscribeSpot("orderbook", "HYPE-USDC")`           |
| Replay                      | `ws.replay("orderbook", "BTC", { start, end, speed })` |

If a helper does not cover a route family, fall back to the raw WebSocket docs or REST/OpenAPI until the package surface supports it.

## Review Rule

WebSocket helper examples should never end at `console.log`. They should explain what happens after the message arrives: update UI state, append to a replay output, apply a book diff, mark a gap, or trigger a resync.

Pair helpers with tests that simulate close, reconnect, replay snapshots, historical data, gap messages, and terminal replay events. A stream helper should show how the application behaves when history is incomplete, a socket closes, a replay pauses, or a resync starts.
