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

# WebSocket API

> Use one WebSocket surface for live subscriptions, historical replay, gap signals, and connection continuity.

Use WebSocket when you need a stream instead of a single REST response. The same surface supports live subscriptions and replay workflows.

<CardGroup cols={2}>
  <Card title="Connect" icon="plug" href="/websocket/connection">
    Open the socket, authenticate, keep it alive, and reconnect cleanly.
  </Card>

  <Card title="Connecting" icon="cable" href="/websocket/connecting">
    Startup checklist for URL, auth, close handling, and reconnect rules.
  </Card>

  <Card title="Keep Alive" icon="heart-pulse" href="/websocket/keep-alive">
    Ping/pong, idle timeout, backoff, and resubscription discipline.
  </Card>

  <Card title="Channels" icon="radio" href="/websocket/channels">
    Subscribe to order books, trades, L4 diffs, HIP-3, HIP-4, and Lighter channels.
  </Card>

  <Card title="Real-Time Streams" icon="radio-tower" href="/websocket/real-time">
    Choose WebSocket when live updates and sequence matter.
  </Card>

  <Card title="L4 Order Book" icon="blocks" href="/websocket/l4-orderbook">
    Maintain stateful L4 books with snapshots, diffs, gaps, and replay.
  </Card>

  <Card title="Replay" icon="rotate-ccw" href="/websocket/replay">
    Play historical sequences at a controlled speed and handle gap messages.
  </Card>

  <Card title="Backtesting" icon="history" href="/websocket/backtesting">
    Use replay windows for deterministic research and strategy checks.
  </Card>

  <Card title="Message schema" icon="braces" href="/websocket/schema">
    Use documented command and event shapes for clients and agents.
  </Card>

  <Card title="Limits" icon="gauge" href="/websocket/limits">
    Size subscriptions, replay jobs, and reconnection behavior for your plan.
  </Card>

  <Card title="Tier Limits" icon="badge-check" href="/websocket/tier-limits">
    Match subscription count, replay speed, and concurrency to plan limits.
  </Card>
</CardGroup>

```mermaid theme={"theme":"github-dark"}
sequenceDiagram
  participant Client
  participant API as 0xArchive WebSocket
  Client->>API: connect with API key
  Client->>API: subscribe or replay command
  API-->>Client: snapshot or replay_snapshot
  API-->>Client: live update or historical_data
  API-->>Client: gap_detected when history has an interruption
```

## Minimal Connection

```javascript theme={"theme":"github-dark"}
const ws = new WebSocket("wss://api.0xarchive.io/ws?apiKey=0xa_your_api_key");

ws.onopen = () => {
  ws.send(JSON.stringify({ op: "subscribe", channel: "orderbook", symbol: "BTC" }));
};

ws.onmessage = (event) => {
  const message = JSON.parse(event.data);
  console.log(message);
};
```

## When To Use WebSocket

Use WebSocket when sequence matters. Live subscriptions are useful for monitors, dashboards, and local books that need updates after an initial state. Replay is useful for backtests, incident review, reconstruction, and workflows where event order carries meaning. If the job only needs one current order-book snapshot or one bounded trade list, REST is usually simpler and easier to retry.

Every WebSocket client should implement four paths: open and authenticate, subscribe or start replay, handle messages, and recover from close or gap signals. A client that only handles happy-path messages will eventually corrupt a local stateful workflow. Keep reconnection and resubscription explicit, and route gap handling to the same data-quality policy used by REST jobs.

## Stream Execution Packet

Before writing WebSocket code or handing the task to an agent, capture the stream packet.

| Field              | Example                                                                                           |
| ------------------ | ------------------------------------------------------------------------------------------------- |
| Mode               | Live subscription or historical replay                                                            |
| Venue family       | Hyperliquid core, Spot, HIP-3, HIP-4, or Lighter                                                  |
| Channel and symbol | `orderbook` + `BTC`, HIP-3 L4 diffs + `km:US500`, or Lighter order book + `BTC`                   |
| State model        | Snapshot only, local book, alert stream, replay output, or dashboard state                        |
| Gap policy         | Mark unsafe, rebuild from snapshot, rerun replay, or stop the job                                 |
| Limit              | One channel-symbol pair, bounded replay window, retry budget, and output destination              |
| Metadata           | Connection id, active subscription packet, timestamps, gap events, and request or correlation IDs |

If the packet is incomplete, start with REST or a one-channel sample instead of a broad streaming client.

## Contract Boundaries

WebSocket is a command-and-event surface. Client commands use `op` values such as `subscribe`, `unsubscribe`, `replay`, `replay.pause`, `replay.resume`, `replay.seek`, `replay.stop`, and `ping`. Server replay events use event names such as `replay_started`, `replay_snapshot`, `historical_data`, `replay_completed`, and `gap_detected`.

Use [WebSocket Message Schema](/websocket/schema) before building typed handlers. Do not infer event names from the replay-control command names; `replay.pause` is a client command, while `replay_paused` is a server event.

## Message Discipline

Do not mix venue families inside one channel assumption. A HIP-3 channel should use HIP-3 symbols such as `km:US500`. Lighter channels should stay in the Lighter namespace. If the stream feeds a model, alert, or strategy harness, store enough message metadata to reconstruct what channel, symbol, time window, and request produced the state.

## Review Rule

Choose WebSocket because a stream is needed, not because it feels more advanced than REST. If a snapshot route answers the question, use REST. If local state, replay order, or live updates matter, WebSocket is the right primitive.
