# Market data WebSocket — `/v1/market-data/ws`

Event-driven `bbo` and full `l2Book` updates for Hyperliquid venues and
Lighter, plus matched `trades` for Hyperliquid venues.

Production URL: `wss://production.mosaiq.0d.finance/v1/market-data/ws`.

## Authentication

The upgrade requires an API key. A missing or invalid key returns HTTP `401`.
A Para JWT does not work. A browser cannot set the header, and must not hold
the key.

```ts
import WebSocket from 'ws'

const ws = new WebSocket('wss://production.mosaiq.0d.finance/v1/market-data/ws', {
  headers: { Authorization: `Bearer ${process.env.MOSAIQ_API_KEY}` },
})
```

This socket has the rate limits and heartbeats of the
[user-data WebSocket](/api/websocket#rate-limits). It drops, without an answer,
a client frame beyond the incoming message budget.

This socket also takes `{"type": "maintenance"}`, the announcements of a Mosaiq
stop and of a venue maintenance. The messages are the same on every socket:
[Maintenance announcements](/api/exchange-websocket#maintenance-announcements).

## Subscribe

```json
{ "method": "subscribe", "subscription": { "type": "bbo", "venue": "hyperliquid:xyz", "coins": ["TSLA", "SILVER"] } }
{ "method": "subscribe", "subscription": { "type": "l2Book", "venue": "hyperliquid", "coins": ["BTC", "ETH"] } }
{ "method": "subscribe", "subscription": { "type": "l2Book", "venue": "lighter", "coins": ["BTC", "ETH"] } }
{ "method": "subscribe", "subscription": { "type": "trades", "venue": "hyperliquid:io", "coins": ["PRL"] } }
```

| Field | Rule |
| --- | --- |
| `type` | `bbo`, `l2Book`, or `trades`. `trades` is open on Hyperliquid venues only: `hyperliquid` and `hyperliquid:*`. |
| `venue` | An exact venue code of `assetData.universe[].venues[]` in [`clearinghouseState`](/api/clearinghouse-state#market-catalog). |
| `coins` | A non-empty list of canonical asset symbols, at most 100. |

There is no `unsubscribe`. Each topic keeps its own subscription set. A new
subscription for a topic and a venue replaces the coin set of that venue, and
leaves the other venues and the other topics as they are.

### Refused whole

A problem of the message itself refuses the whole subscribe. The previous
subscription stays active. The answer is an error frame with the `topic` and
no `venue`, and its `code` is `invalid_request`:

| `detail` | The message |
| --- | --- |
| `invalid_websocket_subscription` | Its payload does not parse, `coins` is empty, the venue or a coin is blank, or `trades` names a non-Hyperliquid venue. |
| `too_many_coins` | It lists more than 100 coins, duplicates and refused coins included, or the connection would hold more than 100 distinct markets of the topic. |
| `unknown_venue` | The venue is not a venue code of the catalog. |

```json
{
  "data": {
    "code": "invalid_request",
    "detail": "unknown_venue",
    "msg": "unknown venue: lightr"
  },
  "server_time_ms": 1788646149474,
  "status": "error",
  "topic": "l2Book"
}
```

Malformed JSON, a JSON array, and a user-data topic get `invalid_request`, the
detail `websocket_error`, and no `topic`. A subscription message must be a JSON
object. See [Errors](/api/errors).

### The subscribe answer

Every other subscribe gets one `subscribed` message, after Mosaiq replaces the
subscription. Mosaiq trims, uppercases, and deduplicates the coins. Each coin
of the request is in `accepted` or in `refused`, once, in request order.

`accepted` is the coin set of the topic on that venue from now on. An empty
`accepted` clears the set. `accepted` confirms the subscription, not the data:
it holds a paused market and a market whose feed is down.

A refused coin carries the `code` and `detail` of its
[error object](/api/errors#error-object), without `msg`:

| `code` | `detail` | The coin |
| --- | --- | --- |
| `invalid_request` | `unknown_asset` | The catalog lists no such asset. |
| `invalid_request` | `symbol_mapping_missing` | The venue lists no perp market of the asset. |
| `trading_restricted` | `market_settled` | The venue settled the market. A relist is a new listing, which a new subscribe follows. |
| `temporarily_unavailable` | `market_data_not_carried` | This gateway carries no book of the market until it restarts. |

```json
{
  "status": "ok",
  "topic": "l2Book",
  "venue": "lighter",
  "data": {
    "type": "subscribed",
    "accepted": [
      "BTC",
      "NOK",
      "ARM"
    ],
    "refused": [
      {
        "coin": "SNDK",
        "code": "trading_restricted",
        "detail": "market_settled"
      },
      {
        "coin": "DOGEE",
        "code": "invalid_request",
        "detail": "unknown_asset"
      }
    ]
  },
  "server_time_ms": 1788646149474
}
```

A `lifecycle` message follows the answer for each accepted market that does
not trade, in request order. `updates` says whether its updates flow. `code` and
`detail` are the ones that an order on the market gets:

| The market | `updates` | `code` / `detail` |
| --- | --- | --- |
| The venue takes only reduce-only orders. | `live` | `trading_restricted` / `market_reduce_only` |
| The venue paused it. Its books resume by themselves. | `paused` | `trading_restricted` / `inactive_market` |

```json
{
  "status": "ok",
  "topic": "bbo",
  "venue": "lighter",
  "data": {
    "type": "lifecycle",
    "coin": "NOK",
    "listing": 1,
    "updates": "paused",
    "code": "trading_restricted",
    "detail": "inactive_market"
  },
  "server_time_ms": 1788646149474
}
{
  "status": "ok",
  "topic": "l2Book",
  "venue": "lighter",
  "data": {
    "type": "lifecycle",
    "coin": "ARM",
    "listing": 1,
    "updates": "live",
    "code": "trading_restricted",
    "detail": "market_reduce_only"
  },
  "server_time_ms": 1788646149474
}
```

## Messages

```ts
interface WebSocketMessage<T> {
  status: 'ok'
  topic: 'bbo' | 'l2Book' | 'trades'
  data: T
  server_time_ms: number
}

interface Bbo {
  coin: string
  venue: string
  time: number
  blockTime?: number // Hyperliquid block time, in Unix milliseconds
  bbo: [Level | null, Level | null] // [bid, ask]
}

interface L2Book {
  coin: string
  venue: string
  time: number
  blockTime?: number // Hyperliquid block time, in Unix milliseconds
  localTimeNs?: number // 64-bit integer (exceeds 2^53; parse as BigInt in JS)
  bootId?: number // 64-bit integer (exceeds 2^53; parse as BigInt in JS)
  levels: [Level[], Level[]] // [bids, asks], best price first
}

interface Level {
  px: string
  sz: string
  n: number
}

interface Trades {
  coin: string
  venue: string
  trades: MarketTrade[]
}

interface MarketTrade {
  side: 'B' | 'A' // taker side: 'B' buy, 'A' sell
  px: string
  sz: string
  hash: string
  time: number
  localTimeNs?: number // 64-bit integer (exceeds 2^53; parse as BigInt in JS)
  bootId?: number // 64-bit integer (exceeds 2^53; parse as BigInt in JS)
  tid: number // 64-bit integer (may exceed 2^53; parse as BigInt in JS)
  users: [string, string] // [buyer, seller]
  makerCloid?: string
  takerCloid?: string
}

interface WebSocketErrorMessage {
  status: 'error'
  topic?: 'bbo' | 'l2Book' | 'trades'
  data: { code: string; detail: string; msg: string }
  server_time_ms: number
}

// A frame about the coins of one subscription. Its data has a type; a book or trades frame's has none.
interface CoinsMessage {
  status: 'ok'
  topic: 'bbo' | 'l2Book' | 'trades'
  venue: string
  data: Subscribed | Lifecycle
  server_time_ms: number
}

interface Subscribed {
  type: 'subscribed'
  accepted: string[]
  refused: Array<{ coin: string; code: string; detail: string }>
}

interface Lifecycle {
  type: 'lifecycle'
  coin: string
  listing?: number // the market catalog's lifecycle.listing, when a listing is on file
  updates: 'live' | 'paused' | 'ended'
  code?: string // absent while the market trades
  detail?: string
}
```

Route each `status: 'ok'` frame on `data.type`. Ignore a type that you do not
know: a newer server can add one.

```ts
ws.on('message', (raw) => {
  // Use json-bigint or lossless-json instead of JSON.parse to decode the 64-bit
  // localTimeNs, bootId, and tid fields (see "Order l2Book and trades" below).
  const m = JSON.parse(raw)
  if (m.status === 'error') return onError(m)
  switch (m.data.type) {
    case undefined:
      return onMarketData(m.topic, m.data)
    case 'subscribed':
      return onSubscribed(m.topic, m.venue, m.data)
    case 'lifecycle':
      return onLifecycle(m.topic, m.venue, m.data)
    default:
      return
  }
})
```

```json
{
  "status": "ok",
  "topic": "bbo",
  "data": {
    "coin": "BTC",
    "venue": "hyperliquid",
    "time": 1788646149401,
    "blockTime": 1788646149315,
    "bbo": [
      {
        "px": "64999",
        "sz": "1.25",
        "n": 3
      },
      {
        "px": "65000",
        "sz": "0.8",
        "n": 2
      }
    ]
  },
  "server_time_ms": 1788646149474
}
```

```json
{
  "status": "ok",
  "topic": "l2Book",
  "data": {
    "coin": "BTC",
    "venue": "hyperliquid",
    "time": 1788646149401,
    "blockTime": 1788646149315,
    "localTimeNs": 1788646149401123456,
    "bootId": 4680762407708856145,
    "levels": [
      [
        {
          "px": "64999",
          "sz": "1.25",
          "n": 3
        },
        {
          "px": "64998",
          "sz": "2",
          "n": 1
        }
      ],
      [
        {
          "px": "65000",
          "sz": "0.8",
          "n": 2
        },
        {
          "px": "65001",
          "sz": "3.1",
          "n": 4
        }
      ]
    ]
  },
  "server_time_ms": 1788646149474
}
```

```json
{
  "status": "ok",
  "topic": "trades",
  "data": {
    "coin": "BTC",
    "venue": "hyperliquid",
    "trades": [
      {
        "side": "B",
        "px": "65000",
        "sz": "0.25",
        "hash": "0x0000000000000000000000000000000000000000000000000000000000000001",
        "time": 1788646149401,
        "localTimeNs": 1788646149401100123,
        "bootId": 4680762407708856145,
        "tid": 9007199254740993,
        "users": [
          "0x1111111111111111111111111111111111111111",
          "0x2222222222222222222222222222222222222222"
        ],
        "makerCloid": "0x0bd340c4a4ced01208e09a23cff02761",
        "takerCloid": "0x9f2b7c1e4d6a80357c1b2e9a0d4f6c81"
      }
    ]
  },
  "server_time_ms": 1788646149474
}
```

### Timestamps and order

Topics are independent of each other and of user-data topics. A `bbo` or
`l2Book` frame carries timestamps from several clocks.

| Field | Clock | Unit |
| --- | --- | --- |
| `data.blockTime` | The exchange time of the Hyperliquid block that produced the book or quote. It can be absent. Lighter frames never carry it. | Unix milliseconds |
| `data.time` | The clock of the source frame. On Hyperliquid, it is the clock of Mosaiq's node, except on a `bbo` from Hyperliquid's public API, where it is the block time. On Lighter, it is Lighter's clock. | Unix milliseconds |
| `data.localTimeNs` | The local clock of Mosaiq's node, on Hyperliquid `l2Book`. See [Order `l2Book` and `trades` with the node clock](#order-l2book-and-trades-with-the-node-clock). | Unix nanoseconds |
| `data.bootId` | The node process that stamped `localTimeNs`. | 64-bit ID |
| `server_time_ms` | The gateway's clock when it first serializes the frame for its subscribers. | Unix milliseconds |

`server_time_ms` is an observation timestamp, not a cursor. BBO timestamps can
repeat or decrease. Apply BBO updates in arrival order for each
`(venue, coin)`. Do not use `data.time` or `data.blockTime` as a sequence
number or as a unique update ID. One block can change a book several times, so
several frames can carry the same `blockTime`. A Hyperliquid `bbo` comes from
Mosaiq's node while the node is current, and from Hyperliquid's public API
otherwise. When the source switches, `blockTime` can decrease.

#### Measure latency from the block

Subtract the timestamps of a frame to split its delay. In the table,
`received` is your clock, in Unix milliseconds, when the frame arrives.

| Difference | What it measures |
| --- | --- |
| `received - data.blockTime` | From the exchange block to your client. |
| `server_time_ms - data.blockTime` | From the exchange block to the gateway, through whichever upstream delivered the frame (Mosaiq's node, or Hyperliquid's public API on `bbo` fallback). |
| `received - server_time_ms` | From the gateway to your client. |
| `data.time - data.blockTime` | On a Hyperliquid `bbo` from Mosaiq's node, from the exchange block to when the node stamped the frame (propagation to the node plus node processing). Zero on a public-API `bbo` when `blockTime` is present (`time` equals `blockTime`). |
| `server_time_ms - data.time` | On a Hyperliquid `bbo` from Mosaiq's node, from the node to the gateway. On a public-API `bbo` with `blockTime`, this equals `server_time_ms - data.blockTime`. |

On `l2Book`, use `localTimeNs` divided by 1,000,000 as the node's time in
milliseconds, in place of `data.time`. Divide it as a `BigInt`, then convert
the result to a `number`. The `data.time` splits above apply only when you
know that the frame came from Mosaiq's node.

Read these differences with their limits:

* A difference between the clocks of two hosts includes the offset between
  those clocks. Keep your clock synchronized, for example with NTP.
* The gateway stamps `server_time_ms` once, when it first serializes the frame.
  For a later subscriber, `received - server_time_ms` also includes its wait in
  the gateway.
* On a Hyperliquid `bbo` from Hyperliquid's public API, `blockTime` equals
  `time` whenever `time` is non-zero (and is omitted if `time` is 0). No field
  names the source of a frame, so `time - blockTime` of 0 does not prove that
  the node had no lag.
* Hyperliquid `l2Book` omits `blockTime` on a resync snapshot and when the
  node cannot read the block time. Skip a frame without `blockTime` when you
  measure.
* A slow client skips snapshots (see [Slow clients](#slow-clients)), so it
  measures only the frames that it receives.
* `blockTime` is below `2^53`, so a JavaScript `number` holds it exactly.
  Unlike `localTimeNs` and `bootId`, it needs no `BigInt`.

### `bbo`

Each `bbo` message carries a complete bid and ask. A `null` bid or ask means
that side is empty: clear its previous value. An empty side does not mean that
the feed is unavailable.

### `l2Book`

Every `l2Book` message is a full snapshot. Replace the previous book. Do not
combine levels from different messages.

* Hyperliquid books keep the exact price and size strings, without bucketing,
  up to 500 levels per side.
* Lighter publishes no order counts, so its levels have `n: 1`.
* A new subscription starts with the next update, without replaying an earlier
  value. Replacing a subscription keeps the pending updates of the markets that
  stay subscribed.

### `trades`

Each `trades` message carries one or more matched Hyperliquid trades of one
`(venue, coin)`, in node execution order.

| Field | Meaning |
| --- | --- |
| `side` | The taker side: `"B"` for buy, `"A"` for sell. |
| `px`, `sz` | The exact decimal strings of the venue. |
| `hash` | The transaction hash. |
| `time` | The exchange block time, in Unix milliseconds. |
| `tid` | The Hyperliquid trade ID. |
| `users` | `[buyer, seller]`. |
| `makerCloid`, `takerCloid` | The Hyperliquid cloids (`0x` and 32 lowercase hex digits) of the maker and the taker order, as the node wrote them. Each is absent when that order has no cloid. On a Mosaiq client order, the cloid is the `venueCloid` ([Keyed venue cloids](/api/optimizing-latency#keyed-venue-cloids)). |
| `localTimeNs`, `bootId` | The node clock, for [ordering against `l2Book`](#order-l2book-and-trades-with-the-node-clock). Each can be absent. |

A new `trades` subscription starts with the next matched trade, without
replaying earlier trades. Replacing a subscription keeps the unread trades of
the markets that stay subscribed.

### Slow clients

A slow `bbo` or `l2Book` client can skip intermediate snapshots and receive
only the latest one of each market. `trades` never skips a trade for a
connected client. If the client falls behind the trade buffer of a market, or
cannot keep up for two seconds, the server closes the connection. Reconnect
instead of missing trades.

### Order `l2Book` and `trades` with the node clock

Hyperliquid `l2Book` frames and `trades` entries carry `localTimeNs` and
`bootId` when Mosaiq's Hyperliquid node publishes them. When the node omits a
field, Mosaiq omits it too, never with `null` or a default value. Lighter books
never carry either field.

| Field | On `l2Book` | On `trades` |
| --- | --- | --- |
| `localTimeNs` | The node's local clock (`local_time`, in nanoseconds since the Unix epoch) of the last raw book diff applied before the snapshot. Absent on a resync snapshot, and when the node cannot parse the line timestamp. | The node `local_time` of the maker order's raw book diff, or of the later fill line for a settlement. Absent when the node cannot find that line, for example after a clock step or during the catch-up at startup. |
| `bootId` | A random unsigned 64-bit integer, below `2^63`, drawn once per upstream node process. Mosaiq serves `l2Book` and `trades` from the same node connection, so the frames of one node session share one `bootId`. | Same as on `l2Book`. |

A trade is in an `l2Book` snapshot of the same `(venue, coin)` if and only if:

1. both carry the same `bootId`,
2. both carry `localTimeNs`, and
3. `trade.localTimeNs <= book.localTimeNs`.

You cannot compare frames with different `bootId` values. Treat a trade
without `localTimeNs` as unknown when you order it against books.

`localTimeNs`, `bootId`, and `tid` are unsigned 64-bit JSON integers.
`localTimeNs` and `bootId` always exceed `2^53`, and `tid` can. Decode them as
64-bit integers, for example as `BigInt` with `json-bigint` or `lossless-json`
in JavaScript. A double rounds `localTimeNs` and can flip the `<=` comparison.

## Market lifecycle

A subscribed market can stop trading, and trade again, while you hold it.
Each connection that holds the coin gets one `lifecycle` message per change of
its market, before the next book or trades frame of the coin. Its `code` and `detail` are the
ones that an order on the market gets, and they are absent while it trades.
`listing` is the [market catalog](/api/clearinghouse-state#market-lifecycle)'s
`lifecycle.listing`, when a listing is on file.

| The market's `lifecycle.state` | At subscribe | While subscribed | `updates` | `code` / `detail` |
| --- | --- | --- | --- | --- |
| `trading` | Accepted. No message. | A message when it trades again. | `live` | Absent. |
| `reduce_only` | Accepted, and a message. | A message. Its books go on. | `live` | `trading_restricted` / `market_reduce_only` |
| `halted` | Accepted, and a message. | A message. The coin stays subscribed, and its books resume by themselves. | `paused` | `trading_restricted` / `inactive_market` |
| `settling` or `settled` | Refused. | A last message. The coin leaves the subscription. | `ended` | `trading_restricted` / `market_settled` |

```json
{
  "status": "ok",
  "topic": "bbo",
  "venue": "lighter",
  "data": {
    "type": "lifecycle",
    "coin": "NOK",
    "listing": 1,
    "updates": "live"
  },
  "server_time_ms": 1788646149474
}
{
  "status": "ok",
  "topic": "l2Book",
  "venue": "lighter",
  "data": {
    "type": "lifecycle",
    "coin": "SNDK",
    "listing": 1,
    "updates": "ended",
    "code": "trading_restricted",
    "detail": "market_settled"
  },
  "server_time_ms": 1788646149474
}
```

`ended` is the last frame of the coin on that connection. A relist of a
settled market is a new listing, with a greater `listing`: subscribe to the
coin again. Two markets get `ended` with `temporarily_unavailable` /
`market_data_not_carried`, because no book of them reaches this gateway until
it restarts:

* A market that the venue listed again under a new market id.
* A Hyperliquid `bbo` market that did not trade when the gateway started.

Mosaiq follows the lifecycle of the market catalog. A change can reach this
socket up to about a minute after the venue made it.

## Availability and recovery

Track availability separately for each `(topic, venue, coin)`.

| Market | When it publishes |
| --- | --- |
| Lighter `bbo` | After its first valid BBO update. A quiet market keeps a valid BBO: the time since its last message does not make the quote invalid. The healthy markets keep publishing while one market has none. |
| Hyperliquid `l2Book` | A new subscription waits for the market's next snapshot. A healthy quiet market can stay pending without an outage error, with no maximum wait. After a feed interruption, the market publishes again from a new valid snapshot. |
| Hyperliquid `trades` | A new subscription waits until Mosaiq's own node subscription is active, then starts with the next matched trade. A healthy quiet market sends no frame until a trade occurs. |

Mosaiq serves Hyperliquid `l2Book` and `trades` only while its node is proven
fresh, by the same check that selects the BBO source. Subscribed `l2Book` and
`trades` clients receive a `temporarily_unavailable` error with the detail
`upstream_unavailable`, instead of stale data, when:

* The node falls more than two seconds behind.
* The upstream node connection drops.
* For `trades` only, the node reports lagged trade batches, so trades in
  between can be missing.

A client that subscribes during the outage gets the error too. After the node
recovers, each `l2Book` market resumes on its next snapshot and each `trades`
market on its next matched trade. A quiet market stays silent until its book
changes or a trade occurs.

A paused market and a market that left the subscription count in no
availability: their outage raises no topic error and holds none.

### The topic error

```json
{
  "data": {
    "code": "temporarily_unavailable",
    "detail": "upstream_unavailable",
    "msg": "BBO feed temporarily unavailable"
  },
  "server_time_ms": 1788646149474,
  "status": "error",
  "topic": "bbo"
}
```

| `topic` | `msg` |
| --- | --- |
| `bbo` | `BBO feed temporarily unavailable` |
| `l2Book` | `L2 book feed temporarily unavailable` |
| `trades` | `Trades feed temporarily unavailable` |

The error names the topic only. It has no `coin`, `venue`, `market_id`, or
list of unavailable markets. It says that at least one subscribed market became
unavailable, or was unavailable at subscription. It does not mean that every
market stopped. A brief outage can recover before the error is sent, and the
gateway still reports it.

* Only connections subscribed to an affected market get the error for that
  topic.
* A subscribe while a requested market is unavailable gets the error at once,
  unless the connection already got the error for the same outage of the topic.
* The subscription stays active, and the healthy markets of the subscription
  keep publishing. Keep processing their messages.
* Recovery resumes the updates of the recovered market, with no recovery
  message and no replay of earlier values.

Mosaiq sends at most one error per connection and topic, across all subscribed
markets and venues. It sends no other error for that topic until it sees every
subscribed market of the topic available again. Replacing a subscription also
resets this when every remaining market is available.

An update confirms data for its own market only. Neither an update nor the
absence of an error proves that the other subscribed markets are ready.

One feed outage can affect several markets at once. Hyperliquid BBO
availability is shared by all `hyperliquid*` venue codes. Hyperliquid `l2Book`
and `trades` track each requested market separately. Hyperliquid and Lighter
outages are independent, and so are the `bbo`, `l2Book`, and `trades` topics.

## Connection lifecycle

| Close | Code | Reason |
| --- | --- | --- |
| Controlled restart. New upgrades can return HTTP `503` while the server drains. | `1012` | `service restart; reconnect` |
| The API key was revoked, rotated, or expired. | `1008` | `api key revoked` |

After any close, reconnect with jittered exponential backoff, authenticate, and
send every subscription again. The answer to each subscribe lists the coins
that it kept in `accepted`, and names in `refused` the ones that closed since
your previous connection.

A live heartbeat does not prove that every market is producing data. Treat a
`temporarily_unavailable` error for a topic, or a connection close, as the
signal that your data may be stale. Updates are event-driven, so the age of the
last message is not an expiry deadline.
