# Market data reference

Every template, field, offset, null value, and enum of the SBE market-data WebSocket, from the published market-data schema.

This reference lists every message of the market-data schema (ID `20`) with its fields, offsets, types, null values, and meaning. Each field shows its name, then its byte offset and type. Offsets count from the start of the message's fixed block, after the 8-byte header; group entry offsets count from the start of the entry. Each description starts with the field's presence and null value, followed by the schema's own description. How to subscribe and recover is on [Market data](https://testnet.polyester.com/docs/developer-docs/sbe-websocket/market-data).

> **The XML is authoritative**
>
> These tables follow the schema of the current Polyester release. An environment can run another version during an upgrade, so the XML from your network's branch always wins. Generate codecs from it rather than from these tables; see [The schema](https://testnet.polyester.com/docs/developer-docs/sbe-websocket/market-data#the-schema).

Null values are written by name: `INT64_MIN` is `-9223372036854775808`. A field holding its null value is absent.

## Template index

Requests are the messages you send:

| Request       | Template | Notes                                     |
| ------------- | -------: | ----------------------------------------- |
| `Subscribe`   |        1 | Subscribe to streams of one or more Pairs |
| `Unsubscribe` |        2 | End streams                               |
| `Ping`        |        3 | Liveness check                            |

Responses and stream messages are the messages the server sends:

| Message             | Template | Notes                                               |
| ------------------- | -------: | --------------------------------------------------- |
| `SubscribeResponse` |       20 | One result per requested item, in request order     |
| `Pong`              |       21 | Answer to `Ping`                                    |
| `Trades`            |       22 | Up to 256 trades of one book update                 |
| `BestBidOffer`      |       23 | Best bid and offer                                  |
| `DepthSnapshot`     |       24 | Full replacement of the `depth20` or `depth` levels |
| `DepthUpdate`       |       25 | Contiguous changes to the `depth` window            |
| `MarketStatus`      |       26 | Feed state of a Pair, `LIVE` or `STALE`             |
| `TradesSkipped`     |       27 | Trades the subscription will not receive live       |
| `TradesThrough`     |       28 | Trade frontier: the baseline, then every second     |

## Encoding composites

Every message starts with `messageHeader`, and repeating groups start with `groupSizeEncoding`. The schema has no variable-length fields. All values are little-endian.

**`messageHeader`**, 8 bytes, before every message:

| Field, offset and type     | Meaning                                                                                                       |
| -------------------------- | ------------------------------------------------------------------------------------------------------------- |
| `blockLength` 0 · `uint16` | Length of the message's fixed block, excluding the header and repeating groups                                |
| `templateId` 2 · `uint16`  | Message template                                                                                              |
| `schemaId` 4 · `uint16`    | Always `20`                                                                                                   |
| `version` 6 · `uint16`     | Schema version the sender encoded with; a reader skips fixed-block bytes past those it knows by `blockLength` |

**`groupSizeEncoding`**, 4 bytes, before every repeating group:

| Field, offset and type     | Meaning                            |
| -------------------------- | ---------------------------------- |
| `blockLength` 0 · `uint16` | Length of each entry's fixed block |
| `numInGroup` 2 · `uint16`  | Number of entries that follow      |

## Requests

Messages you send. Each carries a `requestId` the server echoes.

### Subscribe

Template ID `1` · block length `8` bytes. Client request to subscribe to streams; answered by one SubscribeResponse with one result per item, in order.

| Field, offset and type   | Description                                                         |
| ------------------------ | ------------------------------------------------------------------- |
| `requestId` 0 · `uint64` | Required. Client-chosen identifier echoed in the SubscribeResponse. |

**Group `items`** (`groupSizeEncoding`: `uint16` entry block length, `uint16` count). Streams to subscribe to.

Entry block length `5` bytes.

| Field, offset and type                   | Description                                                                          |
| ---------------------------------------- | ------------------------------------------------------------------------------------ |
| `symbolId` 0 · `uint32`                  | Required. Numeric trading pair identifier as returned by the spot configuration API. |
| `stream` 4 · [`StreamType`](#streamtype) | Required. Stream to subscribe to.                                                    |

### Unsubscribe

Template ID `2` · block length `8` bytes. Client request to end subscriptions; answered by one SubscribeResponse with one result per item, in order. No message of an unsubscribed stream follows the response.

| Field, offset and type   | Description                                                         |
| ------------------------ | ------------------------------------------------------------------- |
| `requestId` 0 · `uint64` | Required. Client-chosen identifier echoed in the SubscribeResponse. |

**Group `items`** (`groupSizeEncoding`: `uint16` entry block length, `uint16` count). Streams to unsubscribe from.

Entry block length `5` bytes.

| Field, offset and type                   | Description                                                                          |
| ---------------------------------------- | ------------------------------------------------------------------------------------ |
| `symbolId` 0 · `uint32`                  | Required. Numeric trading pair identifier as returned by the spot configuration API. |
| `stream` 4 · [`StreamType`](#streamtype) | Required. Stream to unsubscribe from.                                                |

### Ping

Template ID `3` · block length `8` bytes. Client liveness probe; answered by one Pong.

| Field, offset and type   | Description                                            |
| ------------------------ | ------------------------------------------------------ |
| `requestId` 0 · `uint64` | Required. Client-chosen identifier echoed in the Pong. |

## Responses

Answers to your requests.

### SubscribeResponse

Template ID `20` · block length `8` bytes. Server answer to one Subscribe or Unsubscribe; a subscribed stream's first message follows its OK result, and an unsubscribed stream's messages end before it.

| Field, offset and type   | Description                                                 |
| ------------------------ | ----------------------------------------------------------- |
| `requestId` 0 · `uint64` | Required. The Subscribe or Unsubscribe request's requestId. |

**Group `results`** (`groupSizeEncoding`: `uint16` entry block length, `uint16` count). One result per requested item, in request order.

Entry block length `6` bytes.

| Field, offset and type                             | Description                                   |
| -------------------------------------------------- | --------------------------------------------- |
| `symbolId` 0 · `uint32`                            | Required. The item's trading pair identifier. |
| `stream` 4 · [`StreamType`](#streamtype)           | Required. The item's stream.                  |
| `result` 5 · [`SubscribeResult`](#subscriberesult) | Required. The item's outcome.                 |

### Pong

Template ID `21` · block length `16` bytes. Server answer to one Ping.

| Field, offset and type   | Description                                                                       |
| ------------------------ | --------------------------------------------------------------------------------- |
| `requestId` 0 · `uint64` | Required. The Ping request's requestId.                                           |
| `sendTsNs` 8 · `uint64`  | Required. Server time at which this message was encoded, in Unix nanoseconds UTC. |

## Stream messages

Messages of the streams you subscribed to.

### Trades

Template ID `22` · block length `36` bytes. Trades of the trades stream: up to 256 fills of one book update in match order. A larger update is several messages with the same updateId. Each trade is delivered at most once per subscription; a trade that cannot be delivered is named in a TradesSkipped.

| Field, offset and type       | Description                                                                                                                               |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `symbolId` 0 · `uint32`      | Required. Numeric trading pair identifier.                                                                                                |
| `bookEpoch` 4 · `uint64`     | Required. Book epoch of the trades; it increases when the pair's book is rebuilt.                                                         |
| `updateId` 12 · `uint64`     | Required. Book update that executed the trades; the depth stream numbers its state with the same sequence within bookEpoch.               |
| `transactTsNs` 20 · `uint64` | Required. Time of the book update that executed the trades, in Unix nanoseconds UTC.                                                      |
| `sendTsNs` 28 · `uint64`     | Required. Server time at which this message was encoded, in Unix nanoseconds UTC; minus transactTsNs, an estimate of server-side latency. |

**Group `entries`** (`groupSizeEncoding`: `uint16` entry block length, `uint16` count). Trades in ascending tradeId order.

Entry block length `25` bytes.

| Field, offset and type           | Description                                                                                                                                                                                            |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `tradeId` 0 · `uint64`           | Required. Trade identifier, the matchId the trade history API returns. Contiguous per pair within a bookEpoch, starting at (bookEpoch-1)\*2^40+1; trades of a later bookEpoch have higher identifiers. |
| `priceTicks` 8 · `int64`         | Required. Execution price in quote-asset units scaled by 1e9.                                                                                                                                          |
| `qtyScaled` 16 · `int64`         | Required. Executed quantity in base-asset units scaled by the pair's base_quantity_scale.                                                                                                              |
| `takerSide` 24 · [`Side`](#side) | Required, `0` invalid. Side of the order that took liquidity.                                                                                                                                          |

### TradesSkipped

Template ID `27` · block length `36` bytes. Trades of the trades stream that this subscription will not receive live. Recover them from the trade history API by trade identifier.

| Field, offset and type       | Description                                                                                                                                                                              |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `symbolId` 0 · `uint32`      | Required. Numeric trading pair identifier.                                                                                                                                               |
| `bookEpoch` 4 · `uint64`     | Required. Book epoch of the skipped trades.                                                                                                                                              |
| `firstTradeId` 12 · `uint64` | Required. First skipped trade identifier, inclusive.                                                                                                                                     |
| `lastTradeId` 20 · `uint64`  | Optional, null `0`. Last skipped trade identifier, inclusive; null (0) means every trade of bookEpoch from firstTradeId on, whose end the trade history API reports once the epoch ends. |
| `sendTsNs` 28 · `uint64`     | Required. Server time at which this message was encoded, in Unix nanoseconds UTC.                                                                                                        |

### TradesThrough

Template ID `28` · block length `28` bytes. Trade frontier of the trades stream: every trade of bookEpoch with tradeId at or below lastTradeId has been delivered on this subscription or named in a TradesSkipped. Sent first on subscribe as the subscription's baseline, then every second.

| Field, offset and type      | Description                                                                                                        |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| `symbolId` 0 · `uint32`     | Required. Numeric trading pair identifier.                                                                         |
| `bookEpoch` 4 · `uint64`    | Required. Current book epoch.                                                                                      |
| `lastTradeId` 12 · `uint64` | Required. Highest trade identifier of bookEpoch accounted for; (bookEpoch-1)\*2^40 before the epoch's first trade. |
| `sendTsNs` 20 · `uint64`    | Required. Server time at which this message was encoded, in Unix nanoseconds UTC.                                  |

### BestBidOffer

Template ID `23` · block length `68` bytes. Best bid and offer of a bbo subscription, sent when the best price or quantity of either side changes and re-sent unchanged every second. Only the newest is sent to a subscriber that falls behind. Keep the message with the highest (bookEpoch, updateId); an equal pair is a re-send that confirms liveness.

| Field, offset and type       | Description                                                                                                                                                                  |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `symbolId` 0 · `uint32`      | Required. Numeric trading pair identifier.                                                                                                                                   |
| `bookEpoch` 4 · `uint64`     | Required. Book epoch; it increases when the pair's book is rebuilt.                                                                                                          |
| `updateId` 12 · `uint64`     | Required. Book update whose state this message shows; the same sequence numbers depth20 and trades within bookEpoch, strictly increasing between changes but not contiguous. |
| `transactTsNs` 20 · `uint64` | Required. Time of the book update this message shows, in Unix nanoseconds UTC.                                                                                               |
| `sendTsNs` 28 · `uint64`     | Required. Server time at which this message was encoded, in Unix nanoseconds UTC; minus transactTsNs, an estimate of server-side latency.                                    |
| `bidPriceTicks` 36 · `int64` | Optional, null `INT64_MIN`. Best bid price in quote-asset units scaled by 1e9; null when the book has no bids.                                                               |
| `bidQtyScaled` 44 · `int64`  | Required. Total resting quantity at the best bid in base-asset units scaled by the pair's base_quantity_scale; 0 when the book has no bids.                                  |
| `askPriceTicks` 52 · `int64` | Optional, null `INT64_MIN`. Best ask price in quote-asset units scaled by 1e9; null when the book has no asks.                                                               |
| `askQtyScaled` 60 · `int64`  | Required. Total resting quantity at the best ask in base-asset units scaled by the pair's base_quantity_scale; 0 when the book has no asks.                                  |

### DepthSnapshot

Template ID `24` · block length `39` bytes. Full replacement of the best price levels of a depth20 or depth subscription. On depth20, keep the message with the highest (bookEpoch, updateId); an equal pair is an unchanged re-send that confirms liveness. On depth, it replaces the book whatever it held, and the DepthUpdates that follow continue from its updateId.

| Field, offset and type                   | Description                                                                                                                                                                                                                                                    |
| ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `symbolId` 0 · `uint32`                  | Required. Numeric trading pair identifier.                                                                                                                                                                                                                     |
| `stream` 4 · [`StreamType`](#streamtype) | Required. Stream this snapshot belongs to.                                                                                                                                                                                                                     |
| `bookEpoch` 5 · `uint64`                 | Required. Book epoch; it increases when the pair's book is rebuilt.                                                                                                                                                                                            |
| `updateId` 13 · `uint64`                 | Required. Book update whose state this snapshot shows; strictly increasing within bookEpoch but not contiguous.                                                                                                                                                |
| `transactTsNs` 21 · `uint64`             | Required. Time of the book update this snapshot shows, in Unix nanoseconds UTC.                                                                                                                                                                                |
| `sendTsNs` 29 · `uint64`                 | Required. Server time at which this message was encoded, in Unix nanoseconds UTC.                                                                                                                                                                              |
| `levelsPerSide` 37 · `uint16`            | Required. Most price levels per side the stream holds: 20 for depth20; for depth, the live window N, to which a subscriber truncates each side, keeping the N best, after applying every DepthUpdate. A side with fewer levels holds every level of that side. |

**Group `bids`** (`groupSizeEncoding`: `uint16` entry block length, `uint16` count). Bid levels, best (highest price) first; at most levelsPerSide.

Entry block length `16` bytes.

| Field, offset and type   | Description                                                                                                 |
| ------------------------ | ----------------------------------------------------------------------------------------------------------- |
| `priceTicks` 0 · `int64` | Required. Level price in quote-asset units scaled by 1e9.                                                   |
| `qtyScaled` 8 · `int64`  | Required. Total resting quantity at the level in base-asset units scaled by the pair's base_quantity_scale. |

**Group `asks`** (`groupSizeEncoding`: `uint16` entry block length, `uint16` count). Ask levels, best (lowest price) first; at most levelsPerSide.

Entry block length `16` bytes.

| Field, offset and type   | Description                                                                                                 |
| ------------------------ | ----------------------------------------------------------------------------------------------------------- |
| `priceTicks` 0 · `int64` | Required. Level price in quote-asset units scaled by 1e9.                                                   |
| `qtyScaled` 8 · `int64`  | Required. Total resting quantity at the level in base-asset units scaled by the pair's base_quantity_scale. |

### DepthUpdate

Template ID `25` · block length `44` bytes. Incremental update of a depth subscription's window. Apply it only to a book at exactly firstUpdateId-1 of the same bookEpoch: the previous DepthUpdate's lastUpdateId, or the DepthSnapshot's updateId. On any other position, discard the book and resubscribe (Unsubscribe, then Subscribe); never apply it to a book taken from another source or to a position inside the range. Each level is a SET of its total quantity, and quantity 0 removes the level. After applying it, truncate each side to the DepthSnapshot's levelsPerSide best levels: a level pushed out of the window by better levels is not removed on the wire.

| Field, offset and type        | Description                                                                                                                                              |
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `symbolId` 0 · `uint32`       | Required. Numeric trading pair identifier.                                                                                                               |
| `bookEpoch` 4 · `uint64`      | Required. Book epoch; it increases when the pair's book is rebuilt, and a new epoch always starts with a DepthSnapshot.                                  |
| `firstUpdateId` 12 · `uint64` | Required. First book update this message covers: the update after the position it applies to.                                                            |
| `lastUpdateId` 20 · `uint64`  | Required. Last book update this message covers, the book's position once applied. A range whose updates changed no level of the window carries no level. |
| `transactTsNs` 28 · `uint64`  | Required. Time of the book update lastUpdateId, in Unix nanoseconds UTC.                                                                                 |
| `sendTsNs` 36 · `uint64`      | Required. Server time at which this message was encoded, in Unix nanoseconds UTC; minus transactTsNs, an estimate of server-side latency.                |

**Group `bids`** (`groupSizeEncoding`: `uint16` entry block length, `uint16` count). Changed bid levels of the window: levels that changed inside it, entered it from below, or left it because they emptied.

Entry block length `16` bytes.

| Field, offset and type   | Description                                                                                                                      |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------- |
| `priceTicks` 0 · `int64` | Required. Level price in quote-asset units scaled by 1e9.                                                                        |
| `qtyScaled` 8 · `int64`  | Required. Total resting quantity at the level in base-asset units scaled by the pair's base_quantity_scale; 0 removes the level. |

**Group `asks`** (`groupSizeEncoding`: `uint16` entry block length, `uint16` count). Changed ask levels of the window: levels that changed inside it, entered it from below, or left it because they emptied.

Entry block length `16` bytes.

| Field, offset and type   | Description                                                                                                                      |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------- |
| `priceTicks` 0 · `int64` | Required. Level price in quote-asset units scaled by 1e9.                                                                        |
| `qtyScaled` 8 · `int64`  | Required. Total resting quantity at the level in base-asset units scaled by the pair's base_quantity_scale; 0 removes the level. |

### MarketStatus

Template ID `26` · block length `13` bytes. Feed state of a trading pair, sent to every subscription of the pair when it changes and when a subscription starts while the pair is stale.

| Field, offset and type               | Description                                                                       |
| ------------------------------------ | --------------------------------------------------------------------------------- |
| `symbolId` 0 · `uint32`              | Required. Numeric trading pair identifier.                                        |
| `feed` 4 · [`FeedState`](#feedstate) | Required. Whether the pair's streams are current.                                 |
| `sendTsNs` 5 · `uint64`              | Required. Server time at which this message was encoded, in Unix nanoseconds UTC. |

## Enums

### Side

`uint8`. `0` means not set. Direction of the order that took liquidity in a trade.

| Name and value | Description                      |
| -------------- | -------------------------------- |
| `BUY` · 1      | The taker bought the base asset. |
| `SELL` · 2     | The taker sold the base asset.   |

### StreamType

`uint8`. Market-data stream of one trading pair.

| Name and value | Description                                                                                                                                                                                                                       |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `TRADES` · 1   | Every trade of the pair in real time, with a trade frontier and explicit skipped ranges.                                                                                                                                          |
| `BBO` · 2      | The best bid and offer of the pair in real time; a subscriber that falls behind receives only the newest.                                                                                                                         |
| `DEPTH20` · 3  | The best 20 price levels per side as full replacement snapshots, sent at most every 20 milliseconds when they change and at least every second.                                                                                   |
| `DEPTH` · 4    | A live window of the best price levels per side: a DepthSnapshot on subscribe, then a DepthUpdate for every book update. A subscriber that falls behind, or a book the server must rebuild, receives a replacement DepthSnapshot. |

### SubscribeResult

`uint8`. Outcome of one subscription item.

| Name and value           | Description                                                                                                                                                                                                                                                                                                              |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `OK` · 1                 | For a Subscribe item, the stream is subscribed and its messages follow on this connection. For an Unsubscribe item, the stream is unsubscribed and none of its messages follow the response; subscribing again starts the stream afresh, with a new DepthSnapshot for depth and a new TradesThrough baseline for trades. |
| `UNKNOWN_SYMBOL` · 2     | The trading pair is not served on this endpoint.                                                                                                                                                                                                                                                                         |
| `LIMIT_EXCEEDED` · 3     | The connection already holds the most subscriptions it may; this item is not subscribed and the connection is unchanged.                                                                                                                                                                                                 |
| `ALREADY_SUBSCRIBED` · 4 | The connection already holds this subscription; it is unchanged.                                                                                                                                                                                                                                                         |
| `NOT_SUBSCRIBED` · 5     | Answers an Unsubscribe item the connection does not hold; the connection is unchanged.                                                                                                                                                                                                                                   |
| `SYMBOL_DISABLED` · 7    | The trading pair is listed but disabled; subscribe again once it is enabled.                                                                                                                                                                                                                                             |

### FeedState

`uint8`. Whether the server holds the current state of a trading pair's market data.

| Name and value | Description                                                                                                                                                                                             |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `LIVE` · 1     | The pair's streams are current.                                                                                                                                                                         |
| `STALE` · 2    | The server lost the pair's current state; best bid and offer and depth messages pause until it recovers, when each depth subscription receives a replacement DepthSnapshot and trade gaps are reported. |
