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 and the REST and ConnectRPC market-data reads stay available. They serve the same trade identifiers, prices, and quantities.
Endpoint and access
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.
- Upgrade with
GET. A request that cannot be upgraded gets anapplication/problem+jsonbody: another method answers405 METHOD_NOT_ALLOWEDwithAllow: GET, and aGETwithout WebSocket upgrade headers answers426 UPGRADE_REQUIREDwithUpgrade: websocket. Read the problem'scode, 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, on the branch for
your network:
sbe/marketstream-v<version>.xmlis the schema file.manifest.jsonnames it underpaths.marketDataSbe, and itsmarketDataWebSocketSbeblock gives theschemaId,schemaVersion,semanticVersion, and the file'ssha256.
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 lists every field offset, enough to decode the messages by hand.
Conventions
- Header: 8 bytes before every message:
blockLength,templateId,schemaId(20), andversion, each auint16. - Repeating group: a 4-byte header (
blockLengthandnumInGroup, each auint16), thennumInGroupentries ofblockLengthbytes. symbolId: auint32, the Pair's numeric ID fromGetSpotConfig.- Prices (
*PriceTicks): anint64in quote-Asset units times 109. A null price is-9223372036854775808. - Quantities (
*QtyScaled): anint64in base-Asset units scaled by the Pair'sbaseQuantityScalefromGetSpotConfig. See Scaled integers. - Times (
*TsNs): auint64in Unix nanoseconds, UTC.transactTsNsis when the book update happened, andsendTsNsis when the server encoded the message, sosendTsNs - transactTsNsestimates the server-side latency. Side: auint8,BUY=1andSELL=2: the side of the order that took liquidity.
Messages
You send:
Subscribe(1): arequestId, thenitems, each asymbolIdand astream.Unsubscribe(2): ends streams, with the same layout asSubscribe.Ping(3): an application-level liveness check, carrying arequestId.
The server sends:
SubscribeResponse(20): answers oneSubscribeorUnsubscribe, with oneresultper item, in request order.Pong(21): answers onePing, with the server'ssendTsNs.Trades(22,tradesstream): up to 256 trades of one book update, in match order.BestBidOffer(23,bbostream): the best bid and offer.DepthSnapshot(24,depth20anddepthstreams): a full replacement of the stream's levels.levelsPerSideis the stream's window size.DepthUpdate(25,depthstream): the level changes fromfirstUpdateIdtolastUpdateId.MarketStatus(26, every stream of the Pair): the feed state,LIVEorSTALE.TradesSkipped(27,tradesstream): trades this subscription will not receive live.TradesThrough(28,tradesstream): the trade frontier, first as the subscription's baseline, then every second.
Streams
trades(StreamTypeTRADES=1)
Every trade in real time, with a frontier every second. Trades a slow client misses are named in aTradesSkipped; 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:
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.
Sequence numbers
bookEpochnumbers the Pair's book. It increases when the book is rebuilt, and a new epoch replaces everything you hold for the Pair.updateIdnumbers the book update a message reflects. It increases strictly within an epoch but is not contiguous.bbo,depth20,depth, andtradesshare it, so aBestBidOfferand aDepthSnapshotwith the samebookEpochandupdateIdshow the same book.tradeIdis the trade identifier the REST and ConnectRPC trade history return asmatchId. 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
Send Subscribe
Connect and send one Subscribe with a requestId of your choice and one item per symbolId and stream.
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 anUnsubscribeitem 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.
Read each stream's first message
Each stream's first message follows its OK:
bboanddepth20: the newest state at once.trades: aTradesThrough, the subscription's baseline.depth: aDepthSnapshot, 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 ofbookEpochup tolastTradeIdhas been delivered on the subscription or named in aTradesSkipped. Before an epoch's first trade,lastTradeIdis(bookEpoch - 1) × 2^40.Tradesdelivers each trade at most once. A book update with more than 256 trades arrives as severalTradesmessages with the sameupdateId.TradesSkipped(bookEpoch,firstTradeId,lastTradeId) names trades the subscription will not receive live, both bounds inclusive. A nulllastTradeId(0) means every trade ofbookEpochfromfirstTradeIdon; the trade history reports where that epoch ended.
Recover skipped trades from the trade history by trade identifier:
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 andnextAfterTradeIdended, asepochandlastTradeId.
afterTradeId can't be combined with a time range, a side filter, or a page token. limit is at
most 1,000.
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.
Read a page
Call GetTrades with afterTradeId set to the cursor. Take the trades in order, then set the
cursor to nextAfterTradeId.
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.
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
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.
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.
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.
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.
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
1008and the reasonslow 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'sblockLength, and each group entry's by the group'sblockLength, and it skips messages whosetemplateIdit 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
versionand the minor part ofsemanticVersion. - 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
1007for a later one. Themanifest.jsonof 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.
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.