> ## Documentation Index
> Fetch the complete documentation index at: https://sonar-cf3aeac7.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# WebSocket overview

> Stream live DEX trades, token and market data, and OHLCV candles over one WebSocket connection.

The ChainQuery WebSocket API pushes trades to you as they are indexed, so you don't have to poll the REST API. One connection can carry many subscriptions across four channels.

## Endpoint

```text theme={null}
wss://api.example.com/v1/ws
```

* No authentication is needed. Open the socket and start subscribing.
* All frames are JSON text, in both directions. A binary frame or invalid JSON gets a `BAD_REQUEST` error, and the connection stays open.

> [!NOTE]
>
> The [Pulse stream](https://sonar-cf3aeac7.mintlify.site/pulse/stream.md) (`/v1/ws/pulse`) and the [multi-events stream](https://sonar-cf3aeac7.mintlify.site/streams/overview.md) (`/streams/v1/ws`) are separate endpoints with their own protocols. This section covers `/v1/ws` only.

## The welcome message

The server sends a `welcome` message as soon as the connection opens:

```json theme={null}
{"type":"welcome","connectionId":"3f0c5a2e-6d0b-4b8e-9f43-2a1d7c9e8b11","heartbeatMs":30000}
```

| Field | Type | Description |
| - | - | - |
| `connectionId` | string | Random UUID for this connection. Log it when you report problems. |
| `heartbeatMs` | number | How often, in milliseconds, the server sends a WebSocket protocol ping. |

## Channels

Every channel is fed by the same ordered stream of trades for one chain. Each `event` is produced by one trade. The channels differ in how a trade is selected and what is sent for it.

| Channel | Subscribe by | Each event contains | Use it for |
| - | - | - | - |
| [`fast-trade`](https://sonar-cf3aeac7.mintlify.site/websocket/channels/fast-trade) | one `token` and/or one `pool` | The trade | Trade feeds, tape, large-trade alerts |
| [`token-details`](https://sonar-cf3aeac7.mintlify.site/websocket/channels/token-details) | up to 100 `tokens` | The trade plus the token's details and stats | Watchlists and token pages that show price, market cap and volume |
| [`market-details`](https://sonar-cf3aeac7.mintlify.site/websocket/channels/market-details) | up to 100 `pools` | The trade plus the pool's market data and reserves | Pair pages and pool dashboards |
| [`ohlcv`](https://sonar-cf3aeac7.mintlify.site/websocket/channels/ohlcv) | one `pool` or `token` and a `period` | The current candle after the trade | Live charts |

Only swaps classified as trades are streamed. Liquidity adds and removals, MEV swaps and other non-trade swaps are left out.

### WebSocket or REST?

* Use **REST** for anything historical or one-off: token and market snapshots, candle history, past trades. See the [REST API overview](https://sonar-cf3aeac7.mintlify.site/api-reference/overview.md).
* Use **WebSocket** to keep that data up to date afterwards. A common pattern is to load history from REST, then subscribe and apply live events on top. For example, load candles from [`GET /token/ohlcv`](https://sonar-cf3aeac7.mintlify.site/api-reference/token/get-token-ohlcv), then follow the [`ohlcv`](https://sonar-cf3aeac7.mintlify.site/websocket/channels/ohlcv) channel.
* The WebSocket API keeps only about 10 minutes of history for resuming (see [Cursors and resuming](https://sonar-cf3aeac7.mintlify.site/websocket/cursors-and-resume.md)). It does not replace the REST history endpoints.

## Chain identifiers

On the WebSocket API, `chain` must be a string in the form `evm:<chainId>`, for example `"evm:1"` or `"evm:8453"`. A bare number such as `"8453"` or `8453` is rejected:

```json theme={null}
{"type":"error","id":"my-sub","code":"INVALID_PARAMETERS","message":"chain: Invalid blockchain ID. Expected format: \"evm:<chainId>\" (e.g. \"evm:1\", \"evm:137\")","details":[{"field":"chain","message":"Invalid blockchain ID. Expected format: \"evm:<chainId>\" (e.g. \"evm:1\", \"evm:137\")"}]}
```

> [!WARNING]
>
> This differs from REST, which also accepts a bare `1`. Also, any well-formed `evm:<n>` passes validation. On `fast-trade`, `token-details` and `market-details`, a chain that ChainQuery does not index subscribes without error and then never sends events. `ohlcv` checks that the pool or token exists, so it fails the subscribe instead. See [Chains and identifiers](https://sonar-cf3aeac7.mintlify.site/concepts/chains-and-identifiers.md) for the supported chains.

Addresses are case-insensitive and are lowercased by the server. All addresses in events are lowercase.

## End-to-end example

This example subscribes to every trade of one token on Base and prints each one.

```javascript Browser theme={null}
const ws = new WebSocket("wss://api.example.com/v1/ws");

ws.onmessage = (frame) => {
  const msg = JSON.parse(frame.data);

  switch (msg.type) {
    case "welcome":
      ws.send(JSON.stringify({
        op: "subscribe",
        id: "weth-trades",
        channel: "fast-trade",
        params: {
          chain: "evm:8453",
          token: "0x4200000000000000000000000000000000000006",
        },
      }));
      break;
    case "subscribed":
      console.log("subscribed", msg.id, "at", msg.cursor);
      break;
    case "event":
      console.log(msg.data.type, msg.data.tokenAmount, "@", msg.data.tokenPrice);
      break;
    case "error":
      console.error(msg.code, msg.message);
      break;
  }
};
```

```javascript Node.js (ws) theme={null}
// npm install ws
import WebSocket from "ws";

const ws = new WebSocket("wss://api.example.com/v1/ws");

ws.on("message", (raw) => {
  const msg = JSON.parse(raw.toString());

  if (msg.type === "welcome") {
    ws.send(JSON.stringify({
      op: "subscribe",
      id: "weth-trades",
      channel: "fast-trade",
      params: {
        chain: "evm:8453",
        token: "0x4200000000000000000000000000000000000006",
      },
    }));
  } else if (msg.type === "event") {
    console.log(msg.data.type, msg.data.tokenAmount, "@", msg.data.tokenPrice);
  } else if (msg.type === "error") {
    console.error(msg.code, msg.message);
  }
});

ws.on("close", (code, reason) => console.log("closed", code, reason.toString()));
```

```python Python (websockets) theme={null}
# pip install websockets
import asyncio
import json

import websockets

async def main():
    async with websockets.connect("wss://api.example.com/v1/ws") as ws:
        welcome = json.loads(await ws.recv())
        print("connected", welcome["connectionId"])

        await ws.send(json.dumps({
            "op": "subscribe",
            "id": "weth-trades",
            "channel": "fast-trade",
            "params": {
                "chain": "evm:8453",
                "token": "0x4200000000000000000000000000000000000006",
            },
        }))

        async for raw in ws:
            msg = json.loads(raw)
            if msg["type"] == "event":
                d = msg["data"]
                print(d["type"], d["tokenAmount"], "@", d["tokenPrice"])
            elif msg["type"] == "error":
                print("error", msg["code"], msg["message"])

asyncio.run(main())
```

```bash wscat theme={null}
npx wscat -c wss://api.example.com/v1/ws
# then type:
{"op":"subscribe","id":"weth-trades","channel":"fast-trade","params":{"chain":"evm:8453","token":"0x4200000000000000000000000000000000000006"}}
```

The conversation looks like this (`->` is sent by you, `<-` by the server, event data shortened):

```json theme={null}
<- {"type":"welcome","connectionId":"3f0c5a2e-6d0b-4b8e-9f43-2a1d7c9e8b11","heartbeatMs":30000}
-> {"op":"subscribe","id":"weth-trades","channel":"fast-trade","params":{"chain":"evm:8453","token":"0x4200000000000000000000000000000000000006"}}
<- {"type":"subscribed","id":"weth-trades","channel":"fast-trade","cursor":"38123456-0"}
<- {"type":"event","id":"weth-trades","channel":"fast-trade","cursor":"38123457-0:4","data":{"token":"0x4200000000000000000000000000000000000006","type":"buy","tokenAmount":1.25,"tokenPrice":3412.57,"...":"..."}}
<- {"type":"cursor","id":"weth-trades","cursor":"38123610-0"}
```

The `id` you choose is echoed on every message for that subscription, so you can route events when several subscriptions share one connection.

## Heartbeats

Every `heartbeatMs` (30 s by default) the server sends a WebSocket **protocol** ping frame. If it did not receive a pong since the previous ping, it drops the connection without a close frame, and your client sees close code `1006`.

* Browsers, Node `ws` and Python `websockets` answer protocol pings automatically. You don't need to do anything.
* If you turned automatic pongs off in your client library, you must answer pings yourself.
* The application-level `{"op":"ping"}` message is optional. It returns `{"type":"pong"}` and is useful for measuring round-trip time, but it does **not** count as a heartbeat answer. It also counts toward the [message rate limit](https://sonar-cf3aeac7.mintlify.site/websocket/limits-and-errors.md).

## Reconnecting

Subscriptions belong to a connection. When the connection closes for any reason, all its subscriptions are removed, and you must subscribe again on the new connection.

To continue without missing trades, store the latest cursor of each subscription and pass it as `since` when you resubscribe. See [Cursors and resuming](https://sonar-cf3aeac7.mintlify.site/websocket/cursors-and-resume.md) for the full reconnect loop.

## Next steps

> [card] [Message reference](https://sonar-cf3aeac7.mintlify.site/websocket/messages.md)
>
> Every client op and server message type, with fields.

> [card] [Cursors and resuming](https://sonar-cf3aeac7.mintlify.site/websocket/cursors-and-resume.md)
>
> Resume after a disconnect without gaps or duplicates.

> [card] [Limits and errors](https://sonar-cf3aeac7.mintlify.site/websocket/limits-and-errors.md)
>
> Message limits, close codes and error codes.

> [card] [fast-trade channel](https://sonar-cf3aeac7.mintlify.site/websocket/channels/fast-trade.md)
>
> Start with the simplest channel.


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