# Market data

Stream each Pair's trades, best bid and offer, top-20 depth, and a live order book as SBE messages over one public WebSocket, and recover from every gap.

The SBE market-data WebSocket is a binary feed for latency-sensitive clients such as market makers. It serves each Pair's trades, best bid and offer, top-20 depth, and a live order book window as Simple Binary Encoding (SBE) messages over one WebSocket.

The [realtime channels](https://testnet.polyester.com/docs/developer-docs/market-data/realtime-channels) and the REST and ConnectRPC market-data reads stay available. They serve the same trade identifiers, prices, and quantities.

## Endpoint and access

```text
wss://api.testnet.polyester.com/ws/market.sbe
```

- **Open access.** No API key, signature, or login is needed.
- **Binary only.** Every message, in both directions, is one SBE message in one binary WebSocket frame. A text frame closes the connection with code `1003`. The connection uses no compression.
- **One connection, many streams.** One connection carries any mix of Pairs and streams, up to the [subscription limit](#limits).
- **Upgrade with `GET`.** A request that cannot be upgraded gets an `application/problem+json` body: another method answers `405 METHOD_NOT_ALLOWED` with `Allow: GET`, and a `GET` without WebSocket upgrade headers answers `426 UPGRADE_REQUIRED` with `Upgrade: websocket`. Read the problem's `code`, not its text.

Mainnet is coming soon.

## The schema

The messages are defined by the public SBE schema `marketstream`, schema ID `20`, version `0` (`semanticVersion` `1.0.0`), little-endian. It is published byte for byte in the public contracts repository, [polyester-proto](https://github.com/Fabric-Labs/polyester-proto), on the branch for your network:

- `sbe/marketstream-v<version>.xml` is the schema file.
- `manifest.json` names it under `paths.marketDataSbe`, and its `marketDataWebSocketSbe` block gives the `schemaId`, `schemaVersion`, `semanticVersion`, and the file's `sha256`.

Generate a codec with Real Logic's `sbe-tool`, which has Java, C++, C#, Go, and Rust targets. For other languages, the [Market data reference](https://testnet.polyester.com/docs/developer-docs/sbe-websocket/market-data-reference) lists every field offset, enough to decode the messages by hand.

### Conventions

- **Header:** 8 bytes before every message: `blockLength`, `templateId`, `schemaId` (`20`), and `version`, each a `uint16`.
- **Repeating group:** a 4-byte header (`blockLength` and `numInGroup`, each a `uint16`), then `numInGroup` entries of `blockLength` bytes.
- **`symbolId`:** a `uint32`, the Pair's numeric ID from [`GetSpotConfig`](https://testnet.polyester.com/docs/api-docs/connect/marketdata.v1.MarketDataService/GetSpotConfig).
- **Prices (`*PriceTicks`):** an `int64` in quote-Asset units times 109. A null price is `-9223372036854775808`.
- **Quantities (`*QtyScaled`):** an `int64` in base-Asset units scaled by the Pair's `baseQuantityScale` from `GetSpotConfig`. See [Scaled integers](https://testnet.polyester.com/docs/developer-docs/connectrpc/scaled-integers).
- **Times (`*TsNs`):** a `uint64` in Unix nanoseconds, UTC. `transactTsNs` is when the book update happened, and `sendTsNs` is when the server encoded the message, so `sendTsNs - transactTsNs` estimates the server-side latency.
- **`Side`:** a `uint8`, `BUY` = `1` and `SELL` = `2`: the side of the order that took liquidity.

### Messages

You send:

- **`Subscribe`** (`1`): a `requestId`, then `items`, each a `symbolId` and a `stream`.
- **`Unsubscribe`** (`2`): ends streams, with the same layout as `Subscribe`.
- **`Ping`** (`3`): an application-level liveness check, carrying a `requestId`.

The server sends:

- **`SubscribeResponse`** (`20`): answers one `Subscribe` or `Unsubscribe`, with one `result` per item, in request order.
- **`Pong`** (`21`): answers one `Ping`, with the server's `sendTsNs`.
- **`Trades`** (`22`, `trades` stream): up to 256 trades of one book update, in match order.
- **`BestBidOffer`** (`23`, `bbo` stream): the best bid and offer.
- **`DepthSnapshot`** (`24`, `depth20` and `depth` streams): a full replacement of the stream's levels. `levelsPerSide` is the stream's window size.
- **`DepthUpdate`** (`25`, `depth` stream): the level changes from `firstUpdateId` to `lastUpdateId`.
- **`MarketStatus`** (`26`, every stream of the Pair): the feed state, `LIVE` or `STALE`.
- **`TradesSkipped`** (`27`, `trades` stream): trades this subscription will not receive live.
- **`TradesThrough`** (`28`, `trades` stream): the trade frontier, first as the subscription's baseline, then every second.

## Streams

- **`trades`** (`StreamType` `TRADES` = `1`)\
  Every trade in real time, with a frontier every second. Trades a slow client misses are named in a `TradesSkipped`; recover them over REST or ConnectRPC.
- **`bbo`** (`BBO` = `2`)\
  The best bid and offer whenever either side's best price or quantity changes, and again every second. A slow client receives only the newest.
- **`depth20`** (`DEPTH20` = `3`)\
  The best 20 levels per side as a full snapshot, at most every 20 milliseconds while they change, and at least every second. A slow client receives only the newest.
- **`depth`** (`DEPTH` = `4`)\
  A snapshot of the live window when you subscribe, then contiguous updates. A slow client receives a replacement snapshot.

The `depth` window is currently 1,000 levels per side. Every `DepthSnapshot` states it in `levelsPerSide`, so read it from there rather than assuming it. For deeper levels, the REST and ConnectRPC order book serves snapshots at the deepest tier, 5,000 levels per side:

```text
GET https://api.testnet.polyester.com/v1/orderbook/{symbol}?depth=5000
POST https://api.testnet.polyester.com/orderbook.v1.OrderbookService/GetOrderBook
  {"symbolId": <symbolId>, "depth": "DEPTH_5000"}
```

See [Order book](https://testnet.polyester.com/docs/developer-docs/market-data/order-book).

### Sequence numbers

- **`bookEpoch`** numbers the Pair's book. It increases when the book is rebuilt, and a new epoch replaces everything you hold for the Pair.
- **`updateId`** numbers the book update a message reflects. It increases strictly within an epoch but is not contiguous. `bbo`, `depth20`, `depth`, and `trades` share it, so a `BestBidOffer` and a `DepthSnapshot` with the same `bookEpoch` and `updateId` show the same book.
- **`tradeId`** is the trade identifier the REST and ConnectRPC trade history return as `matchId`. Within an epoch, trade identifiers are contiguous, starting at `(bookEpoch - 1) × 2^40 + 1`, and every trade of a later epoch has a higher identifier. A trade's epoch is `(tradeId >> 40) + 1`.

## Subscribe

1. Send Subscribe

   Connect and send one `Subscribe` with a `requestId` of your choice and one item per `symbolId` and `stream`.

2. Read the SubscribeResponse

   The server answers with one `SubscribeResponse` that echoes `requestId` and holds one result per item, in request order:

   - `OK` (`1`): subscribed; the stream's messages follow.
   - `UNKNOWN_SYMBOL` (`2`): the Pair is not served.
   - `LIMIT_EXCEEDED` (`3`): the connection already holds the most subscriptions it may; nothing changed.
   - `ALREADY_SUBSCRIBED` (`4`): the connection already holds this subscription; nothing changed.
   - `NOT_SUBSCRIBED` (`5`): answers an `Unsubscribe` item the connection does not hold; nothing changed.
   - `SYMBOL_DISABLED` (`7`): the Pair is listed but disabled; subscribe again once it is enabled.

   The value `6` is not used.

3. Read each stream's first message

   Each stream's first message follows its `OK`:

   - `bbo` and `depth20`: the newest state at once.
   - `trades`: a `TradesThrough`, the subscription's baseline.
   - `depth`: a `DepthSnapshot`, the base for every later update.

   If the Pair is stale when the connection first subscribes to it, a `MarketStatus` with `STALE` follows the `SubscribeResponse`.

A Pair disabled while you are subscribed keeps its streams, so you see its book drain.

To end streams, send an `Unsubscribe` with one item per `symbolId` and `stream`. Its `SubscribeResponse` answers `OK` for each stream it ended, or `NOT_SUBSCRIBED`, and no message of an ended stream follows that response. Subscribing again starts the stream afresh: a new `DepthSnapshot` for `depth`, and a new `TradesThrough` baseline for `trades`. Closing the connection ends all of its subscriptions.

These close the connection with code `1007`: a message the server cannot decode, an unknown `stream` value or `templateId`, a header whose `schemaId` is not `20`, a `Subscribe` or `Unsubscribe` without items, and a `version` above the one the server serves.

## Recovery rules

### Feed state

A `MarketStatus` with `feed` = `STALE` means the server has lost the Pair's current state. While a Pair is stale, `bbo`, `depth20`, and `depth` send nothing for it. On recovery, `depth` subscribers first receive a replacement `DepthSnapshot`, and only then a `MarketStatus` with `LIVE`: once you see `LIVE`, your depth book is current. `bbo` and `depth20` resume with the newest state, and trades missed meanwhile are named in a `TradesSkipped`.

### `bbo` and `depth20`: latest only

Every message is the full state. Keep the message with the highest `bookEpoch`, then the highest `updateId`:

- A higher pair replaces what you hold.
- A once-a-second re-send repeats the current state. It can carry the same `updateId`, or a higher one when the book moved without changing what the stream shows. Either way it confirms the feed is alive.
- A lower pair is older: ignore it.

There is nothing to recover. A client that reads slowly receives only the newest state, never a backlog.

### `trades`: frontier, skipped ranges, and backfill

Trades are never silently missing. For every subscription:

- `TradesThrough` (`bookEpoch`, `lastTradeId`) arrives first, as the baseline, then every second whether or not anything traded. Every trade of `bookEpoch` up to `lastTradeId` has been delivered on the subscription or named in a `TradesSkipped`. Before an epoch's first trade, `lastTradeId` is `(bookEpoch - 1) × 2^40`.
- `Trades` delivers each trade at most once. A book update with more than 256 trades arrives as several `Trades` messages with the same `updateId`.
- `TradesSkipped` (`bookEpoch`, `firstTradeId`, `lastTradeId`) names trades the subscription will not receive live, both bounds inclusive. A null `lastTradeId` (`0`) means every trade of `bookEpoch` from `firstTradeId` on; the trade history reports where that epoch ended.

Recover skipped trades from the trade history by trade identifier:

```text
GET https://api.testnet.polyester.com/v1/spot/markets/{symbol}/trades?afterTradeId=<cursor>&limit=1000
POST https://api.testnet.polyester.com/marketdata.v1.MarketDataService/GetTrades
  {"symbolId": <symbolId>, "afterTradeId": "<cursor>", "limit": 1000}
```

With `afterTradeId`, the response lists the trades after the cursor in ascending identifier order, without gaps, and adds:

- `completeThroughTradeId`: every trade up to it is available.
- `nextAfterTradeId`: the cursor for the next call. It never moves backwards, and it also advances across epoch ends and empty epochs.
- `epochEnds`: where each epoch between the cursor and `nextAfterTradeId` ended, as `epoch` and `lastTradeId`.

`afterTradeId` can't be combined with a time range, a side filter, or a page token. `limit` is at most 1,000.

1. Start the cursor

   Start with the cursor at `firstTradeId - 1`. After a reconnect, start from the last `tradeId` you hold, and walk to the new subscription's baseline `TradesThrough`.

2. Read a page

   Call `GetTrades` with `afterTradeId` set to the cursor. Take the trades in order, then set the cursor to `nextAfterTradeId`.

3. Stop at the end of the range

   Stop when the cursor reaches the `lastTradeId` of the skipped range or baseline. For an open-ended `TradesSkipped`, stop when `epochEnds` lists that epoch with a `lastTradeId` at or below the cursor.

4. Wait for the trade history

   If `nextAfterTradeId` equals the cursor you sent, the trade history has not caught up with the live stream yet. That is normal for a fresh gap: retry with backoff, for example from 100 milliseconds doubling to 2 seconds, for as long as it takes.

Deduplicate live `Trades` against the backfill by `tradeId`.

### `depth`: snapshot, then exact-base updates

1. Install the snapshot

   After `OK`, a `DepthSnapshot` of the live window arrives at a `bookEpoch` and an `updateId`, `U`. It replaces any book you hold for the Pair.

2. Apply contiguous updates

   `DepthUpdate` messages follow, contiguous: the first has `firstUpdateId` = `U + 1`, and each next one has a `firstUpdateId` equal to the previous `lastUpdateId + 1`. Each level sets that price's total quantity, and quantity `0` removes the level.

   Apply an update only to a book at exactly `firstUpdateId - 1`. Never apply it to a book at any other position, including one inside its range, and never to a book from another source.

3. Truncate to the window

   After every update, truncate each side to the `levelsPerSide` best levels of the last `DepthSnapshot`. A level pushed out of the window by a better new level is not removed on the wire. A side with fewer levels holds every level of that side.

4. Accept replacement snapshots

   A new `DepthSnapshot` on the subscription, for a new `bookEpoch`, a recovery, or a client that fell behind, replaces the book whatever it held.

5. Resubscribe after a gap

   If an update's `firstUpdateId` is not your book's position plus one, or its `bookEpoch` differs from your book's, discard the book, send an `Unsubscribe` for the stream, then a `Subscribe`. The new subscription starts with a fresh `DepthSnapshot`. Never patch across a gap.

The deep REST or ConnectRPC snapshot (`GetOrderBook`) is a separate, frozen view at its own `bookEpoch` and `bookSeq`. Never apply `DepthUpdate` messages to it. To show depth beyond the live window, show its levels only beyond the window's worst price, only while that live side holds a full window, and drop it when its `bookEpoch` differs from the stream's. A snapshot with `available` `false` has no levels to show.

## Limits

- **Open connections:** 100 per IP address, counted together with the realtime and private WebSockets.
- **New connections:** 10 per second per IP address, with a burst of 50.
- **Subscriptions:** 128 per connection, each one Pair and stream. An item past the limit is answered `LIMIT_EXCEEDED`.
- **Client messages:** at most 4 KiB. A larger message closes the connection.
- **Liveness:** the server sends a WebSocket ping every 20 seconds, and drops a connection that sends no pong within 60 seconds.
- **Slow consumer:** a connection that reads nothing for 5 seconds while the server has data for it is closed with code `1008` and the reason `slow consumer`.

An upgrade over either connection limit is refused with HTTP `429`; back off before you reconnect. A client that reads slowly but keeps reading is never closed: `bbo` and `depth20` send only the newest state, `depth` sends a replacement snapshot, and `trades` names what it skipped.

## Versions

- The server always encodes the current version of schema `20`. A decoder generated from an earlier version reads later versions: it skips fixed fields it does not know by the header's `blockLength`, and each group entry's by the group's `blockLength`, and it skips messages whose `templateId` it does not know. Treat an unknown enum value the same way: ignore the item or the message.
- New fields, messages, and enum values are added without breaking existing clients. Each raises `version` and the minor part of `semanticVersion`.
- Encode your own messages with the version your codec was generated from. The server accepts any version up to the one it serves and closes the connection with code `1007` for a later one. The `manifest.json` of your network's branch names the version your network serves.
- A change that existing decoders cannot read comes with migration notes for the release that ships it. Regenerate your codec from that release's schema.

## Example (Python)

A minimal client that subscribes to one Pair's `bbo` and `trades` streams and prints them. It decodes by hand and uses each header's `blockLength`, so it keeps working when later versions add fields. It needs `pip install websockets`.

```python
import asyncio
import struct

import websockets

URL = "wss://api.testnet.polyester.com/ws/market.sbe"
SCHEMA_ID, VERSION = 20, 0
TRADES, BBO = 1, 2
NULL_PRICE = -(1 << 63)


def subscribe(request_id, items):
    msg = struct.pack("<HHHHQ", 8, 1, SCHEMA_ID, VERSION, request_id)
    msg += struct.pack("<HH", 5, len(items))
    for symbol_id, stream in items:
        msg += struct.pack("<IB", symbol_id, stream)
    return msg


async def main(symbol_id):
    async with websockets.connect(URL, compression=None) as ws:
        await ws.send(subscribe(1, [(symbol_id, BBO), (symbol_id, TRADES)]))
        async for frame in ws:
            block, template, schema, _ = struct.unpack_from("<HHHH", frame)
            if schema != SCHEMA_ID:
                continue
            body = frame[8:]
            if template == 20:  # SubscribeResponse
                size, count = struct.unpack_from("<HH", body, block)
                for i in range(count):
                    sym, stream, result = struct.unpack_from("<IBB", body, block + 4 + i * size)
                    print("subscribe", sym, stream, "OK" if result == 1 else result)
            elif template == 23:  # BestBidOffer
                _, epoch, update, _, _, bid, bid_qty, ask, ask_qty = struct.unpack_from("<IQQQQqqqq", body)
                bid = None if bid == NULL_PRICE else bid / 1e9
                ask = None if ask == NULL_PRICE else ask / 1e9
                print("bbo", epoch, update, bid, bid_qty, ask, ask_qty)
            elif template == 22:  # Trades
                size, count = struct.unpack_from("<HH", body, block)
                for i in range(count):
                    trade_id, price, qty, side = struct.unpack_from("<QqqB", body, block + 4 + i * size)
                    print("trade", trade_id, price / 1e9, qty, "BUY" if side == 1 else "SELL")
            elif template == 27:  # TradesSkipped: backfill with GetTrades
                _, epoch, first, last = struct.unpack_from("<IQQQ", body)
                print("skipped", epoch, first, last or "end of epoch")
            elif template == 28:  # TradesThrough
                _, epoch, through = struct.unpack_from("<IQQ", body)
                print("through", epoch, through)


asyncio.run(main(1))
```

Prices print as decimals for readability only; keep them as integers in production code. Quantities print in scaled units: divide by 10 to the power of the Pair's `baseQuantityScale` from `GetSpotConfig` to get base-Asset units.
