Endpoint
TypeScript SDK helpers and React hooks are available for WebSocket subscriptions. Use them when you want typed channel helpers, reconnect handling, and cleanup helpers. See TypeScript WebSockets and React hooks.
Connection Setup
- Open one connection to the WebSocket endpoint and reuse it for all subscriptions. New connections are rate-limited per client address.
- Subscribe with channel strings; unsubscribe with the same channel strings.
- Channel parameters use trading pair UUIDs, not symbols.
- Public market channels do not require authentication.
- Account channels require a session-key WebSocket authentication message before subscribing.
- Use
*only where listed to leave a filter open.
Message Format
Subscribe and unsubscribe with the same channel strings.Subscribe with one Subscribed acknowledgement listing only the channels that request changed — the ones it actually added, in the order you sent them.
- A channel the connection already holds is a no-op — it is not re-subscribed, no snapshot is replayed, and it is left out of the ack.
- A channel that is malformed, fails validation, requires authentication you have not completed, or exceeds the per-connection subscription cap gets its own
Errorframe (with a machine-readablecodeand the rejectedchannel) and is left out of the ack. The ack still follows, so a partially-accepted request yields the error frames first and then the accepted subset. "channels": []therefore means the request added nothing, whatever the reason: every channel was rejected, you already held them all, some mix of the two, or the request named no channels at all.
Snapshot frame, or a SNAPSHOT_UNAVAILABLE error, as soon as that channel’s baseline is read, and its live frames follow right behind it. A channel without one (see Slow-client disconnect) gets neither frame, and its live frames start once the server has checked it for a snapshot. The channels of one request do not wait for each other, so their snapshots can arrive in any order: route each by its channel. No live frame for a channel arrives before that channel’s snapshot. The server reads your next request only after every snapshot of this one is sent.
A per-channel Error frame names the channel it concerns in channel, echoed exactly as you sent it — including a string the server could not parse — so you can pair each rejection with your request without reading the human-readable message. A channel longer than 128 bytes (never a valid channel) is echoed as its first 128 UTF-8 bytes, cut at a character boundary:
INVALID_SUBSCRIPTION, AUTH_REQUIRED, SUBSCRIPTION_LIMIT, SNAPSHOT_UNAVAILABLE, RFQ_DISABLED, FORBIDDEN, and SERVICE_UNAVAILABLE carry a channel. A SNAPSHOT_UNAVAILABLE channel was accepted — it is in the ack and its live frames flow — so its channel tells you which baseline to refetch. Channels served from the market-data service are the exception: depth, bbo, and trades:{trading_pair_id} or orderbook when the server serves them from it (their frames carry seq or book_seq). They stream nothing until their snapshot arrives, and the server keeps retrying and sends it when the book can be read, so stay subscribed and wait (see Keeping a local book). If you cannot tell which source serves an orderbook or trades channel, refetch the REST baseline and still take any later Snapshot as the new baseline. Connection-wide failures (AUTH_FAILED, ACCOUNT_DEACTIVATED, ACCOUNT_RESTRICTED, CONNECTION_LIMIT, INVALID_MESSAGE, SESSION_INVALID, MESSAGE_RATE_LIMIT) concern no single channel and have no channel key.
Do not read the ack as the connection’s full subscription list; it is the delta for that one request. Track what you hold client-side.
Authenticated channels require a session-key handshake first. The signature covers WS-AUTH\n<public_key>\n<timestamp> with the session private key.
timestamp is epoch milliseconds and is bound into the signature. The server rejects a handshake whose timestamp is outside a ±30s clock-skew window (stale or future-dated), so sign with the current time and re-sign on every reconnect — never cache and replay an old Authenticate payload.Heartbeat (Ping/Pong)
Liveness runs at two layers. The server sends a transport-level WebSocket ping control frame about every 25 seconds so proxies keep the connection open; your WebSocket implementation answers it with a pong frame automatically, and it never surfaces as an application message. At the application level, the client sends{"type":"Ping"} on its own timer and the server replies {"type":"Pong"}. The server never sends a JSON Ping, so do not wait for one. A raw client should treat a connection that delivers nothing, not even a Pong, for its idle window as dead and reconnect. Ping/Pong is a liveness signal only: unsigned, non-transactional, and it neither authenticates an action nor refreshes a session.
Slow-client disconnect (close code 1013)
When the server detects that a connection’s broadcast receiver missed events that one of its subscriptions owns (see below), it closes the whole connection, including every other subscription on it, with code1013 (“try again later”) and reason slow consumer: stream gapped, resync required. This close frame is the machine-readable resync signal; no additional JSON Error frame precedes it. Sending the close is best-effort: a broken socket may surface only an abnormal transport close, and still releases server resources.
The same close, with the same reason, is also sent when events may have been lost before they reached the WebSocket server: the matching engine dropped a frame under load, a publish failed, or the server’s upstream event feed dropped, reconnected, or fell behind. Which events were lost is unknown, so every connection on that server that holds at least one subscription and was open when the events were lost is closed, whatever it subscribes to; a connection with no subscription, or one opened after the loss (for example during a matching engine restart), stays open. These closes are spaced at least about one second apart, so a burst of losses closes a connection once. Periodic frames whose next frame restates their full state (market_stats and position valuation frames) never cause one: a later frame repairs a lost one.
A gap closes the connection only if one of its subscriptions owns it. A subscription to orders, conditional_orders, twap_orders, positions, balances, account, instrument, liquidations, or a single market’s market_stats:<tradingPairId> owns every gap, because its subscribe snapshot may not yet reflect an event that the gap overwrote. So does a subscription the server serves from the market-data service (depth, bbo, orderbook, and a single market’s trades), because its snapshot travels the same queue as its live frames. A subscription to any other channel (trades:*, ohlcv, movements, all-markets market_stats) owns only gaps that reach events published after its Subscribed acknowledgement. An earlier gap just means its stream starts after it. For example, a public market-data connection that falls behind while its handshake or an earlier Subscribe is still being processed keeps streaming instead of reconnecting into the same backlog.
The ring drops arbitrary events, not superseded values for each key. A lost position close, candle, balance, or instrument update may have no later replacement. Even a connection holding only absolute-state channels must reconnect and reconcile. Healthy peers continue consuming independently; delivery is at-most-once and is not replayed on reconnect.
Reconnect, authenticate, and resubscribe before reconciling REST reads with incoming events. Subscribe snapshots exist for balances, orders, conditional_orders, twap_orders, liquidations, positions, instrument, account, and market_stats (per-market and all-markets); they describe current state, not every missed lifecycle transition. A per-market trades subscription also gets one: the market’s newest 50 trades, a recent-history baseline rather than current state (see Trades). So does rfq_trades: the market’s newest 50 RFQ prints (see RFQ trades). So does an ohlcv subscription to one market, interval and price series: its newest 350 candles, also a recent-history baseline (see OHLCV). An orderbook subscription gets its market’s current book (see Orderbook), and depth and bbo get the full book and the top of book they continue from (see Depth and BBO). Apply each channel’s baseline semantics: complete maps such as positions and instruments can replace their prior set. For persisted resting orders, merge by per-order version; snapshot absence is not a tombstone because persistence can lag a newer local event. Retain such local rows and resolve them with getOrder before applying the version rule. An order version is not a contiguous replay cursor. See the SDK reconciliation guidance.
The remaining channels do not provide a subscribe-time snapshot — the append-only movements and market_liquidations streams. Applications must explicitly refresh the relevant REST state/history, including quiet keys that may never emit again. A per-market market_stats subscription whose market has not yet produced a frame (or on a transient matching-engine read failure), and the all-markets channel for a brief window during initial startup or after a server restart (until the producer commits its first full generation, or on the same read failure), return SNAPSHOT_UNAVAILABLE instead of a baseline — treat it as a transient resync signal, not a failure: keep the subscription open (no auth or session reset), and let a later published live frame seed the baseline once one is produced. Account keepalives cover active accounts only, so a flat account whose collateral does not move stays silent on the live stream — the account subscribe snapshot includes it, and so establishes a complete baseline for the authenticated application. It is not a full replacement set for the channel: live account delivery is user-scoped and can carry accounts from other applications (see Account), which the snapshot deliberately omits. Merge it per margin_account_id rather than replacing the whole channel map, or those cross-application keys are discarded. A resumed stream alone does not establish a complete baseline for the other channels.
For additive history such as public trades and movements, use the available REST history and its documented pagination/retention limits. The trades snapshot covers only the newest 50 trades, and the ohlcv snapshot only the newest 350 candles; neither is a gap-free replay. There is no universal WebSocket replay cursor or guarantee that an arbitrary outage can be reconstructed completely. Surface an unrecovered gap when the required history is unavailable; do not assume a fresh current-state snapshot reproduces missed events.
The TypeScript SDK automatically reconnects when enabled and invokes onResync({ code: 1013, slowClient: true }) after sending authentication/subscription requests. It does not wait for acknowledgements or snapshots and does not automatically perform REST refetches; the application owns recovery. It also offers the resync capability by default and reports Resynced channels through the same callback, as onResync({ code: 1013, slowClient: true, reason: "resynced", channels }), once the server’s delay has passed (see Scoped resync).
Scoped resync without a disconnect (opt-in)
A client can ask the server to keep its connection open through an upstream loss it can attribute to one publisher, and to name the channels that need repair instead. Offer theresync capability on a Subscribe or an Authenticate:
capabilitiesis optional onSubscribeandAuthenticateonly. The capability holds for the life of the connection: sending it again, sending[], or re-authenticating (even as another user) changes nothing, and there is no way to withdraw it short of reconnecting. Values the server does not know are ignored, and a server that predates the capability ignores the field entirely, so sending it is always safe. Acapabilitiesthat is not a list of strings makes the whole message anINVALID_MESSAGE.- There is no acknowledgement. Handle both outcomes below; the
1013close remains possible on every connection.
Resynced frame for each of its channels that may have lost frames:
channelis the channel string exactly as you subscribed to it. The subscription stays active and its live frames keep flowing; refetch that channel’s REST state afterretry_after_msmilliseconds and reconcile it with the live stream, as you would after a reconnect.retry_after_msis drawn per connection (1–5 seconds by default) so that the clients of one server spread their refetches.- Public channels with a subscribe-time snapshot that the matching engine feeds (
instrumentandohlcv) are repaired in place instead: usually two to three seconds after the loss (up to about 17 seconds on a busy server) the server sends a freshSnapshotfor the channel, like the subscribe-time one but with"resynced": truebesidedata, and holds that channel’s live frames until it is out, so none precedes it. Apply it with that channel’s baseline semantics, exactly as on subscribe: aninstrumentsnapshot is current state and can replace it, while anohlcvsnapshot is recent history that persistence may trail, so merge it and keep newer candles you already hold. The held frames follow it and may restate what it already covers, as after a subscribe-time snapshot: apply them idempotently. Sending aSubscribewhile a repair is pending turns it into aResyncedinstead, followed by the held frames. If the snapshot cannot be read, or the server cannot re-read snapshots, the channel gets aResyncedinstead. Every other channel keeps streaming meanwhile. - Channels a publisher loss cannot affect get nothing:
depth,bbo,orderbookandtrades(the server repairs its own copy of the book or trade chain and re-sends a snapshot), and the self-healingmarket_statschannels. A connection holding only those is left alone. - A burst of losses resyncs each channel once: a later loss before your refetch is due is covered by that refetch.
- A channel whose subscribe-time
Snapshotis still on its way when the loss happens gets itsResyncedright after thatSnapshot, never before it. - A loss the server cannot attribute to one publisher (its upstream event feed dropped, fell behind, or was re-established) still closes every connection subscribed before it with
1013, opted in or not, and so does a connection’s own slow-client gap.
1013.
Inbound message rate (close code 1008)
Every application frame you send —Authenticate, Subscribe, Unsubscribe, Ping, or anything unparseable — draws from a per-connection budget. The defaults are 20 messages per second sustained with a burst of 1,200; both values are operator-configurable, so a deployment may run different numbers. Protocol-level Ping frames count too (each costs the server a Pong write), and so does every fragment of a fragmented message; protocol Pong (your reply to the server heartbeat) and Close are not counted. Frames are also metered by size: a per-connection byte budget admits a full re-subscribe frame at connect plus normal traffic, but refuses a burst of very large frames even well under 20 per second. The first frame past either budget receives an Error frame with code MESSAGE_RATE_LIMIT, and the connection is then closed with 1008 (“policy violation”) and reason message rate limit exceeded (or message byte limit exceeded when the byte budget ran out). The budget is per connection, so it is unaffected by other connections from the same account.
A normal client never approaches it: subscribe to everything you need in as few Subscribe frames as possible (one frame carries many channels) and let the ~25 s heartbeat idle. The TypeScript SDK sends every held channel in a single Subscribe frame when the socket opens and on every reconnect; a channel added while the socket is already open is sent as its own frame, and the default burst (1,200) is sized above the default subscription cap (1,024 channels) so even adding a full subscription set one channel at a time on a live connection stays within budget. The SDK reconnects through 1008 with backoff and re-sends its authentication and subscriptions; an application that re-subscribes in a hot loop on every reconnect will trip the cap again, so treat MESSAGE_RATE_LIMIT in onError as a signal to slow down, not to retry immediately.
New-connection rate (HTTP 429)
Each client address may open 6 new connections per minute, with a burst of 20, per server instance; the values are operator-configurable. Only opening a connection counts: a connection that stays open costs nothing, however long it lives. An upgrade past the budget is refused with HTTP429 Too Many Requests and a Retry-After header (whole seconds) before the WebSocket is established, so there is no close code: a browser reports a failed connection, and Node’s ws an unexpected response.
A normal client never approaches it: open one connection, keep it for the whole session, and reconnect only when it drops, with backoff. The TypeScript SDK does this; it treats a refused upgrade like any other failed connect and retries with jittered exponential backoff (up to 30 s between attempts). A client that opens a fresh connection per request, or reconnects in a tight loop, will be refused; wait at least Retry-After before the next attempt.
Compression
The server supports the standardpermessage-deflate WebSocket extension. Browsers and most WebSocket clients, including Node.js, Bun and the ws package, offer it automatically, so frames arrive compressed and are decompressed by the client before your code sees them. There is nothing to configure, and messages are the same JSON either way. A client that does not offer the extension receives uncompressed frames.
You may also send compressed messages on a connection that negotiated the extension. The inbound limits above count a compressed message at its uncompressed size, or at its compressed size when that is larger.
Connect
- Browser
- Node.js
- Python
Unsubscribe with the same channel string and close the socket when no subscriptions remain.
Unsubscribed mirrors Subscribed: it lists only the channels that request actually removed. A channel the connection was not subscribed to is an idempotent no-op and is left out, and a channel string the server cannot parse gets an INVALID_SUBSCRIPTION Error frame whose channel is that string, exactly as you sent it.
Channel Catalog
Public Channels
Authenticated Channels
Channel Details
Trades
Executed trades for one pair, including price, quantity, maker side, and execution time.Subscribe-time snapshot
On subscribe to a single market, before any live trade, the server sends aSnapshot frame whose data is an array of that market’s newest 50 trades, newest first — the same trades, in the same order, as the first page of the REST trades read with pageSize 50. Each row is the live trade frame’s inner data object (trade_id, price, quantity, quantity_raw, maker_side, executed_at); the market is the channel’s, so the event_type, trading_pair_id and trading_mode envelope is not repeated per row. Decimal values are JSON strings. A market with no trades, or an unknown trading_pair_id, gets an empty array. A trades:* subscription gets no snapshot. A read failure returns SNAPSHOT_UNAVAILABLE and leaves the subscription active.
trade_id when merging the snapshot with live frames, and use the REST trades read for anything older or for a complete history.
Sequenced trades
The server servestrades from the market-data service. Each live frame carries four top-level fields, beside data, that place the trade in its market’s chain:
Keys need not be dense: a step whose fills are not all public trades skips their indexes.
A single market’s subscribe-time snapshot also carries a
cursor beside data: the key of the newest trade the live frames continue from, or null when the server has applied no trade since it last read the market’s history, in which case the first live trade is the base.
trades:{trading_pair_id} the server forwards only trades that link: the first live trade after a snapshot has (prev_seq, prev_match_index) equal to the cursor (or is the base when the cursor is null), and each later one links to the trade before it. A trade at or below the key you hold is already reflected and can be dropped. When the server loses its place in the chain it sends a fresh Snapshot and continues from its cursor; replace your recent-trades view with it, keeping newer trades you already hold. A SNAPSHOT_UNAVAILABLE here also heals by itself: the server retries and sends the snapshot, so stay subscribed. A trade that arrives on your side with a link that does not match the key you hold means a frame was lost on your connection; resubscribe to get a fresh snapshot.
trades:* carries the same four fields on every trade but has no snapshot, no cursor and no link check: the first trade you see for each market is that market’s base.
Two limits of the snapshot remain:
- It reads recorded trades, so a trade executed just before you subscribed and not yet recorded can be missing from it. The live chain still links past it.
- Trades that share one
executed_atare ordered in the snapshot bytrade_id, not by(seq, match_index). Order live trades by their key.
RFQ trades
Public, anonymised prints of RFQ block fills for one pair. Each frame’sdata carries trading_pair_id, trading_mode and the print (data: execution_id, price, quantity, executed_at, published_at), and no account, counterparty, quote or RFQ id. RFQ fills never print on trades.
data.data (execution_id, price, quantity, executed_at, published_at), not the live frame’s outer data. Like the trades snapshot it is recent history, not a gap-free replay: merge it and keep newer prints you already hold. A print is published once its fill is durable, and a failed publish is retried, so a print can arrive late or more than once, and a connection can still miss one: deduplicate on execution_id, and recover gaps from GET /api/v1/trades/{tradingPairId}?executionSource=RFQ, which pages the market’s recent RFQ fills newest first (older ones stay on the unfiltered pages, tagged executionSource: "RFQ"). See Public prints.
RFQ
Pushes for RFQ (authenticated). While RFQ is switched off, every subscription is refused withRFQ_DISABLED (“RFQ is switched off”). A delegated agent session acts for its owner: with an RFQ_MAKER delegation its connection keeps the owner’s quotes alive, with any other active delegation it only receives pushes, and without an active delegation it is refused with FORBIDDEN. If the delegation cannot be read, the subscription is refused with SERVICE_UNAVAILABLE; retry it.
data is one push, tagged by type. The wire keys are already camelCase, and decimals are exact strings:
RfqRequested: a new RFQ you can quote, sent to everyrfqsubscriber except the requester’s wallet family. It never names the requester. On a one-way request it carriesquoteSide, the only side you may quote.RfqView: to the taker, its view moved. Pushes can arrive out of order: keep the view with the highestsequence. When quotes change quickly, views in between may be skipped, but the last view pushed always reflects the latest change.RfqSelected: to a selected maker, its last-look prompt: the selected quantity, its frozen price, capacity and maker fee rate, its builder add-on maximum, the estimated net, and the deadline, withacceptedAtMs(the acceptance the deadline runs from) andpublishedAtMs(when Monaco sent the push), both optional.RfqOutcome: how an RFQ you are party to ended. The taker’s push carries itsoutcome. A maker’s push carriesownFillsinstead: only its own fills (executionId, itsside,price,quantity), so it can hedge without reading the RFQ. It is on every maker’s push, empty when the maker filled nothing; a push without it comes from a server that does not send it, so read the RFQ.ownFillshas no fee: the fee charged is on the receipt,GET /api/v1/rfqs/{rfqId}.
GET /api/v1/rfqs/{rfqId}. The server pings rfq connections every 5 seconds and closes one that hasn’t answered within 15 seconds. A maker’s resting quotes depend on its rfq connection: see Disconnects.
Market Liquidations
Public liquidation events for one margin pair, with wallet attribution and valuation from the event-time mark. This stream is distinct from the authenticated account-levelliquidations:{trading_pair_id} alert channel.
startTime and exclusive endTime; after each subscribe acknowledgement, clients can refetch from the latest seen event timestamp and deduplicate by event_id to recover rows that persisted during a reconnect.
side describes the liquidated position, not the liquidation execution’s buy/sell direction. mark_notional equals position_size × mark_price in the quote asset.
Orderbook
Live bid/ask depth with optional aggregation and base or quote quantity formatting.Trading mode. A missing or
* mode resolves to the market’s own mode; use * when keeping later segments.Price-level grouping. Supported values are
0.000001, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000, 10000, and *.Quantity denomination.
base returns base-token quantities; quote returns quote-token notional quantities.Subscribe-time snapshot
On subscribe, before any live update, the server sends aSnapshot frame whose data is an array holding one object: the market’s current book, rendered from the market-data service’s copy of it exactly as a live orderbook_update frame’s data is, grouped by the channel’s magnitude and quoted in its denomination, so you can apply it with the same code. Its sequence_number and book_seq are the watermark the book is exact as of. A market the server does not list gets SNAPSHOT_UNAVAILABLE. When the book cannot be read the server also returns SNAPSHOT_UNAVAILABLE, leaves the subscription active, and sends the snapshot once it can.
Book sequence fields
The server renders this channel from the market-data service’s copy of the full book. Grouping covers the whole book (up to 1000 levels per side, capped at 20 buckets per side); with no magnitude a frame carries the best 20 levels per side. Every live frame and snapshot row carries two top-level fields beside the book:book_seq(integer): the durable-log sequence the levels are exact as of. It is the same watermark thedepthchannel carries, and it is identical on every server. It is a u64, so parse it without losing precision (the TypeScript SDK surfaces it as the decimal stringbookSeq).prev_book_seq(integer): thebook_seqof the previous frame this server sent for the book,0before the first. If it is at or below thebook_seqyou hold, no state was skipped. It is informational only: every frame restates the whole book.
sequence_number equals book_seq, and price_change is always null. Live frames are sent at most once every 100 ms per market. A frame whose book_seq is not past the one you last applied on the same channel can be ignored. The watermark belongs to the book, so each magnitude and denomination you subscribe to starts from its own snapshot. A scoped resync never re-snapshots or Resynceds orderbook: an upstream loss the server repairs on its own copy of the book is followed by a fresh Snapshot for the channel, with no client action.
Every live frame restates the whole book, so the snapshot needs no merge: replace your book with it, then with each live frame. A frame published while the snapshot was being read can arrive just after it and be older; the next frame corrects it.
The REST orderbook’s sequenceNumber is the matching engine’s own counter, which restarts at 1 when the engine restarts; do not compare it with this channel’s sequence_number.
To keep a book at full precision rather than grouped, use depth.
Depth
The exact order book for one market, level by level: a snapshot of up to 1000 levels per side, then sequenced frames carrying only the levels that changed. Use it to keep a local book.Snapshot
The first frame of everydepth subscription is a Snapshot, and nothing else on the channel arrives before it. data is one object:
Live frames
Changes are collected over 100 ms windows of exchange time, so each frame covers at most one window per market and a quiet market sends nothing.
BBO
The best bid and ask of one market, with their sizes, sent each time either price or size changes. Changes deeper in the book, or in order count alone, send nothing.Snapshot whose data is the current top of book at book_seq; each live frame then restates the whole top. A side with no orders has null price and size.
book_seq, timestamp_ms and stale mean what they mean on depth; prev_book_seq is the book_seq of the market’s previous BBO frame. Because each frame restates the whole top, apply any frame whose book_seq is past the one you hold. A BBO frame can arrive slightly before the depth frame that covers the same change.
Keeping a local book
depth and bbo follow one set of rules. The TypeScript SDK applies them for you.
- Subscribe and take the snapshot. Replace your book with the
Snapshotand hold itsbook_seq. Live frames never arrive before it. - Drop what the snapshot already has. Ignore any frame whose
book_seqis at or below the one you hold. - Check the link. A frame continues your book when its
prev_book_seqis at or below thebook_seqyou hold: its levels restate everything that changed sinceprev_book_seq, so applying it over a slightly newer book is safe. Apply its levels, then hold itsbook_seq. - On a broken link, a frame whose
prev_book_seqis above thebook_seqyou hold, a frame was lost on your side: the server checks the same links and only sends you frames that continue the book, re-sending aSnapshotitself when it has to start over. Discard the book, then unsubscribe and subscribe again for a fresh snapshot. Onbbo, which restates the whole top, any newer frame is safe to apply. - Every
Snapshotreplaces the book, including one that arrives mid-stream. The server sends one whenever it reloads the book, for example after it lost frames from the market-data service.
SNAPSHOT_UNAVAILABLE: the book cannot be read right now. Stay subscribed. The server retries and sends the snapshot when it can, with no action from you. Resubscribing does not help: it lands on the same book. The one case that never heals is a trading pair ID with no active market in that mode, so if no snapshot arrives, check the ID and mode against the markets list.- An incomplete side (
bids_completeorasks_completefalse) has unknown levels beyond the last one in the snapshot. When removals thin it out, the levels that should move up are not in your book. Treat only the levels you hold as known: ignore live levels priced beyond the snapshot’s deepest level on that side, since a removal there could hide a level you never saw, and resubscribe for a fresh snapshot when the side runs low (the SDK does both, refreshing once a side falls below half its snapshot depth). - Channel strings. The
Snapshotechoes your subscribe string exactly as you sent it. LiveEventframes use the canonical form: lowercase hyphenated pair ID and uppercase mode. Match both, for example by subscribing with the canonical form. - Disconnects. Upstream problems in the market-data service never close your connection: the server reloads the book and sends a fresh
Snapshot. Your connection can still be closed with1013like any other: when it falls behind; when the matching engine loses frames, unless you opted into scoped resync; and, opted in or not, when the server’s upstream event feed drops or falls behind. After a reconnect, resubscribe and start from the new snapshot.
depth and bbo are the base for a local book. A REST or gRPC orderbook read carries a bookSeq, but it is a point-in-time read and a staleness check, not a base for applying depth frames: it can come from a different copy of the book than the stream.
OHLCV
Live candle updates for charting and market analytics.Optional price series. Omit it (the four-token form) or use
trade for the
trade-derived candles. mark selects the close-only mark-price series (open =
high = low = close = mark, zero volume), published on 1m for margin pairs.
reference selects full OHLC of the mark price over each bucket, with zero
volume and zero trades, on every interval for margin pairs. Use it to chart
a market with little trading. Use * to receive every series. A four-token
subscription receives only the trade series.open_interest_base and
open_interest_notional from the newest stored open-interest sample before the
candle end, the same pair REST returns for that candle. Samples are taken once a
minute and the server picks them up within 15 seconds, so a live frame can trail
the newest sample briefly. Both fields are null on spot pairs and while no
sample is available.
Example
Subscribe-time snapshot
On subscribe to one market, interval and price series, before any live candle, the server sends aSnapshot frame whose data is an array of that series’ newest 350 candles, oldest first — the same candles, in the same order, as the REST candlesticks read with limit 350 and the same interval and priceType, including its flat candles for periods with no trades. Each row is the live candle frame’s inner data object (open, high, low, close, volume, quote_volume, trades_count, period_start, period_end, open_interest_base, open_interest_notional); the channel fixes the market, interval and series, so the envelope is not repeated per row. Decimal values are JSON strings, period_start and period_end are Unix milliseconds, and period_end is period_start plus the interval, as on a live candle. quote_volume is null for a candle whose quote volume was not recorded. Open-interest values use the latest paired sample at or before the candle end; the quote notional uses the price captured with that sample, not the candle close. Either field can be null when unavailable.
- The four-token form is the
tradeseries. Amodeof*is served. - A
*market, interval or price type gets no snapshot, because one frame carries one series. - An unknown
trading_pair_id, amodethat is not the market’s (SPOTon a margin market, orMARGINon a spot market), andmarkorreferenceon a spot market get an empty array: no live candle comes for them. A margin market with no reference history yet also gets an emptyreferencearray. markis served on every interval listed above, but live mark updates stream on1monly, so amarksnapshot on another interval is a baseline with no live updates after it.- A read failure returns
SNAPSHOT_UNAVAILABLEand leaves the subscription active.
1m candle is the last closed minute, and longer intervals can lag, so the snapshot’s newest candle can be partial or missing. A live candle is the full current state of its period. Upsert by period_start when merging: a live candle replaces the snapshot candle with the same period_start, or appends a newer one. Use the REST candlesticks read for anything older.
Market stats
Periodic market statistics, public (no session handshake). A per-market subscription delivers frames with index / mark / mid prices, best bid/ask, open interest and its limit, last trade price, 24h volume / high / low and absolute and percentage price change, funding state (current rate, estimated next rate, next funding timestamp, funding interval, last funding time, premium, and clamp bounds), and amarket_status label. Subscribing to the bare market_stats channel (or market_stats:*) instead delivers, on a slower cadence, a single frame carrying a reduced per-market summary for every published market — a market that has not yet assembled its first frame is omitted, and the subscribe-time snapshot carries the same set — including a market_status label (TRADABLE, POST_ONLY, HALTED, NOT_READY, or UNKNOWN). A market’s per-market frame and its all-markets row carry the same label.
The 24h volume, high, low, price change, and last trade price count a trade within about a second of its execution. The REST market endpoints can trail them by a couple of minutes after a trade, so expect the WebSocket figures to lead briefly.
SPOT markets flow through both channels carrying orderbook, last trade, 24h stats, and a TRADABLE / HALTED label; the perp-only fields (index/mark price, open interest and limit, funding rate/timestamp/interval/last funding time/premium, base interest rate, funding clamps) are omitted for spot.
On subscribe, before any live frame, the server sends a Snapshot frame carrying the channel’s current baseline as an array: for a per-market subscription, one element with that market’s latest complete frame (the same shape as a live per-market data); for the all-markets channel, one reduced summary per active market with retained data, ordered by trading-pair id (the same shape as the live markets elements). A per-market subscription whose market has not yet produced a frame — or on a transient matching-engine read failure — receives a SNAPSHOT_UNAVAILABLE error instead of a fabricated frame, and the subscription stays active so a later published live frame seeds it once the market produces one. The all-markets channel returns SNAPSHOT_UNAVAILABLE in the same way for a brief window during initial startup or after a server restart (until the producer commits its first full generation), and on any transient snapshot read failure against the matching engine, rather than a partial baseline; treat it as a resync signal and let the next periodic all-markets push deliver the baseline. Both channels stay active through it. Where a deployment does not run the market-stats snapshot service, neither channel sends a snapshot or a SNAPSHOT_UNAVAILABLE frame at all — the first live push seeds state, so do not wait on either.
Trading pair ID for a per-market subscription. Omit the segment (or use
*) for the all-markets summary.channel — there is no inner event-type discriminator. Every decimal price/quantity is a JSON string; funding_timestamp and last_funding_time are numeric millisecond epochs; funding_interval_seconds is a whole number of seconds; keys are snake_case; optional fields are omitted (not null) when absent.
Per-market frame (market_stats:{trading_pair_id}) — the envelope data carries a trading_pair_id and a nested data object. Perp-only fields (index_price, mark_price, open_interest, open_interest_limit, open_interest_headroom, current_funding_rate, funding_rate, funding_timestamp, funding_interval_seconds, last_funding_time, premium, base_interest_rate, funding_clamp_small/funding_clamp_big) are omitted for spot markets. market_status is present on every frame, perp and spot: TRADABLE, POST_ONLY, HALTED, NOT_READY, or UNKNOWN for perps, TRADABLE or HALTED for spot. funding_interval_seconds is the funding settlement interval. funding_clamp_small and funding_clamp_big both carry the maximum funding rate per settlement (0.0125% by default — the ±0.75% premium bound divided by the premium divisor of 60 — the same for every market): a settled rate is capped to ±that value. premium is the open window’s running mean premium; funding_rate estimates the next settled rate — that mean divided by the premium divisor (60), or the already-settled rate once the window has closed. base_interest_rate is always "0", because funding has no interest-rate component. funding_timestamp is the next funding boundary, always after the frame was built: once a boundary passes, it moves to the following one. last_funding_time is when the latest funding window settled, as a millisecond epoch (REST getFundingState returns the same instant as an RFC 3339 string); it is omitted until the market’s first settlement. open_interest is one-sided LONG open interest (each open contract counted once) in base units; open_interest_limit (the market’s gross open-interest cap) and open_interest_headroom (open_interest_limit − gross open interest × mark_price, never below zero; the cap counts both sides, so this is not derivable from open_interest alone) are USD notional and present only when the market has a cap. Until a perp’s open interest is known, open_interest and open_interest_headroom are omitted (never zero) while every other field is still sent; once known, every frame carries the most recent value. At zero headroom, orders that open exposure are refused until open interest or the mark falls:
daily_volume_by_source: the 24h volume split into its order-book and RFQ parts, each total being the order-book part plus the RFQ part (order_book_base_token_volume, rfq_base_token_volume, and order_book_quote_token_volume and rfq_quote_token_volume, which are omitted when the 24h quote volume is unavailable). The object is omitted while any candle in the 24h window has no recorded split.
All-markets summary frame (market_stats / market_stats:*) — the envelope data carries a markets array of reduced per-market summaries, each with a market_status label. index_price, funding_rate, premium and open_interest_notional are perp-only and omitted for spot. funding_rate is the estimated next-window rate (current_funding_rate is the last settled one). open_interest_notional is the one-sided open_interest × mark_price, falling back to the last trade price when there is no mark, in quote units; it is omitted until both open interest and a price are known, never sent as zero. Each row also carries daily_volume_by_source, the same 24h split as the per-market frame:
Instrument
Trading-pair lifecycle and configuration changes, public (no session handshake): new listings, delistings, non-activation edits to tick size, quantity step, order-size bounds, or category, and edits to a perp market’s margin ladder. Each perp frame carries the whole ladder asrisk_tiers (see the payload below). Fee edits do not emit a frame. Every frame also carries the base and quote asset icon URLs, so a client can join a position’s trading_pair_id to the instrument row and render both icons without a REST call. A per-market subscription (instrument:{trading_pair_id}) delivers frames for one pair; the bare instrument channel (or instrument:*) streams every market. A single subscribe-time Snapshot frame carries the configuration of every listed market as an array of per-market baselines (each element a listing), and arrives before the live Event diffs — a raw client must handle the Snapshot frame, not only Event, to receive that baseline (see the two envelopes below). The snapshot includes inactive (delisted) markets, each flagged is_active: false, so positions, orders and history on a delisted market can still resolve its metadata; filter on is_active for the tradable set. Markets not yet launched are not included. A per-market snapshot for a delisted market returns that market’s row.
Trading pair ID for a per-market subscription. Omit the segment (or use
*) to stream every market.Event frame carries one market’s full current configuration, not just the changed fields, and the subscribe-time Snapshot frame carries an array of those same per-market configs (one element per listed market, active or not) — so consume each event, and each element of the snapshot array, as a per-market terminal-state snapshot, never an additive delta; changed_fields names which fields the mutation touched, for callers that want to react selectively. Frames are routed by channel. Every decimal value is a JSON string; keys are snake_case; the perp-only fields (min_leverage, max_leverage, initial_margin_rate, maintenance_margin_rate, risk_tiers) are omitted (not null) for spot markets, which have no leverage or margin parameters. risk_tiers is the market’s margin ladder, ascending by tier_level, with the same fields and values as the REST perp config’s riskTiers: tier_level (a JSON integer), lower_bound_notional, max_leverage, initial_margin_ratio, maintenance_margin_ratio, initial_margin_deduction, maintenance_margin_deduction and max_position_notional, with max_leverage and max_position_notional omitted when the tier has none. max_leverage, initial_margin_rate and maintenance_margin_rate at the top level are tier 1’s values. The base_icon_url and quote_icon_url fields differ: they apply to every market and are always present, carrying an explicit null when an asset has no icon configured (never a synthesized URL) rather than being omitted. Every market’s frame also carries its asset identity, always present: base_asset_id / quote_asset_id (UUID strings), base_token / quote_token (ticker symbols), base_asset_name / quote_asset_name, and base_decimals / quote_decimals (JSON integers), named as on the REST TradingPair.
change is one of listing (on a live frame, a market became tradable — created active or re-activated; every snapshot element is a listing baseline whatever its is_active), delisting (deactivated), halt / unhalt (trading halted / resumed — reserved for a future market-regime producer, not emitted by admin trading-pair edits), or config_change (a non-activation edit). A margin-ladder edit that changes any tier, or the position cap that bounds the top tier, emits a config_change whose changed_fields names risk_tiers, plus max_leverage, initial_margin_rate and maintenance_margin_rate when tier 1 changed. Saving an unchanged ladder emits nothing. The payload nests under the channel envelope’s data, which carries a trading_pair_id and a nested data object:
Snapshot frame — type: "Snapshot", with a server-capture timestamp — whose data is an array of per-market InstrumentEventData (each with change: "listing"), not the per-pair { trading_pair_id, data } wrapper the Event frames use. Live changes then follow as the Event frames above. Handle both type values — a loop that ignores every non-Event message never receives the baseline:
@0xmonaco/types ships the InstrumentEvent, InstrumentEventData, and InstrumentChangeKind types for this channel, and @0xmonaco/core exposes the typed sdk.ws.instruments(handler, tradingPairId?) subscription, which parses the snake_case wire keys onto those types and fans the Snapshot baseline out as one event per market. A raw WebSocket client reads the snake_case wire keys directly, or maps them onto InstrumentEventData itself (trading_pair_id → tradingPairId, is_active → isActive, tick_size → tickSize, base_icon_url → baseIconUrl, quote_icon_url → quoteIconUrl, base_asset_id → baseAssetId, base_decimals → baseDecimals, min_leverage → minLeverage, risk_tiers → riskTiers (and each tier’s keys likewise, tier_level → tierLevel), changed_fields → changedFields, and so on; that type describes the ergonomic shape, not these raw keys).
Orders
Order lifecycle events for the authenticated user, including placement, fills, cancellations, rejections, and expirations.Trading mode filter. Use
orders:{trading_pair_id}:* to filter by pair across all modes.origin, what placed the order: USER for an order the account placed, LIQUIDATION for a liquidation slice, ADL for an auto-deleveraging close, and SYSTEM, which is reserved and not sent today. It is the same value GET /api/v1/orders/{orderId} returns. An absent key means the server did not report it, never USER.
Balances
Balance state changes for the authenticated user.balance_update carries one spot balance row: its available, locked and total amounts, its version, the reason, and a reference. A spot order whose remainder rests sends lock, and the release of that lock (a cancel, partial cancel, expiry, a replace whose replacement doesn’t rest on the same row, batch cancel or cancel-all, a self-trade-prevention cancel, or a TWAP parent’s cancel of its child) sends unlock. One step sends one frame per row with the row’s state after the step: a step that also fills on the row sends only its trade frame. Market, IOC and FOK orders never rest, so they send neither. Margin collateral is not a spot balance and is not emitted here: a margin-routed deposit, a perpetual fill, a funding settlement, a liquidation and an auto-deleveraging close send no balance_update. Read margin collateral on the account channel.
Movements
Ledger-style balance movement entries for the authenticated user.GET /api/v1/accounts/movements), while its live signal is a versioned balance_update on the balances channel for each spot-owned leg. A margin fill sends no balance_update; its collateral arrives on the account channel.
Positions
Margin position changes, for cross and isolated risk buckets alike, including size, status, mark price, PnL, and liquidation fields.OPEN frame for every open position in each risk bucket it touched, taker and makers alike: the bucket of the position each side’s order is bound to. In a cross risk bucket that is every position of the bucket, in any pair, because a trade in one pair moves the liquidation price of the others; an isolated risk bucket holds a single position. Positions in the account’s other risk buckets are not re-sent, even in the same pair. Each position is sent at most once per fill, and every frame carries the fill’s version. Each frame names its own trading_pair_id, so positions:{trading_pair_id} receives the frames for positions in that pair even when the trade was in another one. Liquidation slices and auto-deleveraging refresh the liquidated account’s risk bucket and each counterparty’s risk bucket the same way.
Collateral transfers use margin_added or margin_reduced. A direct isolated-position margin add or reduction sends that position with the transfer’s version. Cross-risk-bucket ALLOCATE/RELEASE refreshes every open position in the affected cross risk bucket without a version because that command does not write position rows. Wallet IN/OUT, plain isolated-risk-bucket allocation without a position collateral delta, and empty scopes send no position frame. Successful frames use the command’s captured post-command state and are released only after its durable acknowledgement.
Where enabled, the channel also carries position_valuation frames: about every five seconds, each open position’s mark_price, unrealized_pnl, liquidation_price (null when none can be derived), initial_margin_required and maintenance_margin_required, and its estimated_next_funding_payment (signed size × mark × the market’s estimated next funding rate; positive = pays, omitted while the market has no estimate), with valued_at, the time the server read it. A frame is sent when any of these changed, and otherwise periodically, normally at least once a minute. It carries no size, status or version: apply it only to a position you hold as OPEN whose updated_at is earlier than the frame’s valued_at (a valuation read before the position’s last mutation is stale), ignore it for an unknown or terminal one, and never close a position from one. See Position Valuation Frames.
Non-zero funding payments emit ranked OPEN frames from state captured inside the funding command; zero payments emit no position frame. A settlement’s frames on every channel (these position frames and the funding movements) are sent at a paced rate after the settlement. On a large book they can therefore arrive several seconds after it, after frames for later fills, and in any order across channels. Each position frame keeps the funding command’s version, so the version rule ranks it below a later fill’s frame, which already includes the funding. A position that has closed by the time its account’s funding frames are sent gets no funding position frame (its funding movement is still sent). A close in the last moment before the send can still be followed by its funding OPEN frame, so never reopen a position you hold as terminal: rank by version. Funding sends no balances frame: margin collateral arrives on the account channel. Full closes, liquidation victims/backstop exits and ADL closes normally emit ranked terminal frames with lifetime reduced quantity — the sum of every reducing execution — and the exact terminal classification: ordinary closes and flattened ADL counterparties are CLOSED, while liquidation exits and the bankrupt ADL side are LIQUIDATED. After restart, a terminal frame rebuilt from pre-upgrade reduction history omits version when that history lacks the size or margin fields needed to reconstruct complete lifetime values; incomplete size history carries only the known partial total. Reconcile that frame by full field comparison. Detect terminal state from status, never from size === "0".
Every position_update frame, and every snapshot row, can carry funding_paid: the position’s lifetime funding since it opened, as a decimal string (positive = paid, negative = received). On an open position it is the funding accrued on the size still open plus the funding its partial closes settled; a terminal frame carries the closed position’s whole-life total, the earlier closes’ shares plus the final close’s share. That equals the last open value, which already held the final close’s share as its accrual, and matches fundingPaid on a REST read of the closed position. A snapshot row carries the value the position’s live frames carry. The key is omitted, never zero, when the value cannot be served whole: the position’s earlier reductions are not fully accounted for, or its history is still catching up. Keep the last value you hold rather than clearing it. position_valuation frames do not carry it.
Snapshot rows also carry estimated_next_funding_payment for an open position, the same estimate REST serves; live position_update frames omit it and position_valuation frames refresh it, so keep the last value you hold. See Estimated next funding payment.
Conditional Orders
Take-profit, stop-loss and trailing-stop lifecycle changes for the authenticated user. A trailing stop additionally emitsreason: "armed" when tracking begins
and reason: "ratcheted" on every trigger move, each frame carrying the new
triggerPrice and watermarkPrice (see Trailing Stop).
TWAP Orders
Owner-scoped TWAP parent-order updates. Every mutation emits onetwap_order_update carrying the full parent snapshot (configuration plus
progress: executed quantity/notional, average fill price, slice counters,
next-slice cursor, state, execution_style, the conditional-trigger fields,
and any terminal reason such as end-of-window shortfall or trigger expired).
The reason field names the mutation: created, slice_placed,
slice_skipped, cancelled, or completed for every parent;
passive_child_placed, child_repriced, and passive_fill for a PASSIVE
parent working a resting post-only child (its deadline sweeps and crossing
takes still arrive as slice_placed); and triggered or trigger_expired for
a conditional parent. Two of the passive reasons are looser than they read:
child_repriced is also emitted by the cancel-only fallback, with no child
left resting, and the maker fill that completes a parent reports completed
rather than passive_fill. Only the authenticated owner’s parents are ever
delivered. See TWAP orders for the execution
mechanics, including passive execution.
On subscribe, before any live frame, the server sends a Snapshot frame on the
twap_orders channel whose data is an array with one TwapOrderEventData row
per owned non-terminal parent — PENDING (awaiting its start window, or, for
a conditional parent, still awaiting its price trigger) or ACTIVE (triggered
and slicing) — honouring the optional pair filter. Each row is the same shape as a
live twap_order_update data, with reason: "snapshot". An owner with no live
parents receives an empty array, not no frame. Terminal parents (COMPLETED /
CANCELLED) are excluded as history — read those from the REST TWAP order
listing. The baseline reflects persisted state, so a parent that reached a
terminal state just before the subscription opened can still appear
ACTIVE/PENDING until that transition is persisted, and its terminal event —
sent before the subscription existed — does not re-fire; consume the snapshot as
a seed to merge and reconcile against the REST read, not as an authoritative
replacement set. A repository read failure returns SNAPSHOT_UNAVAILABLE and
leaves the subscription active (live diffs still flow); treat it as a transient
resync signal, not a failure.
Live updates and snapshot rows can carry an optional version, derived from the
sequencer step that wrote that parent. Reconcile only rows with the same
twap_order_id: accept >=, reject lower versions, and let the snapshot win an
equal-version tie. Gaps are normal. An absent version means unknown legacy
state, not zero, and versions from different parents are unrelated.
Liquidations
Liquidation-risk alerts and liquidation status changes for the authenticated user.Subscribe-time snapshot
On subscribe, before any live alert, the server sends aSnapshot frame on the
bare liquidations channel whose data is an array with one
LiquidationEventData row per in-flight liquidation record the authenticated
user owns — one the matching engine is still actively liquidating (status: "UNRESOLVED"). These are exactly the records the live channel keeps reconciling:
the engine emits a liquidation_alert on each transition, including the terminal
one. A COMPLETED record, and a BAD_DEBT record (an insolvent account whose
insurance resolution is a settlement-side process the live channel does not
report), are excluded. Each row is the same shape as a live liquidation_alert
data. An owner with no in-flight liquidation receives an empty array, not no
frame.
A liquidation record is account-scoped and carries no trading pair, so a snapshot
row’s position_id, trading_pair_id, liquidation_price, and mark_price are
always null — the live alert fills those from the live position the snapshot
lacks. risk_bucket_state is Liquidating on every row: an in-flight record is a
risk bucket under active liquidation, and the record does not persist the exact
live bucket state, so the next live alert carries the precise value. Because a snapshot
row cannot be attributed to a pair, a pair-scoped
liquidations:{trading_pair_id} subscription baselines with an empty array;
subscribe to the bare liquidations channel for the account-wide baseline.
The baseline reflects persisted state, so consume it as a seed to merge and
reconcile against a REST read, not as an authoritative replacement set: a record
that terminalized just before the subscription opened can still appear
non-terminal until that transition is persisted, and its terminal alert — sent
before the subscription existed — does not re-fire. A repository read failure
returns SNAPSHOT_UNAVAILABLE and leaves the subscription active (live alerts
still flow); treat it as a transient resync signal, not a failure.
Recovered episodes
A liquidation episode that recovers ends with a terminalliquidation_alert
too, not only one that liquidates to completion. When a breached risk bucket
heals back over its maintenance requirement — on a liquidation step, or with no
step at all on an oracle mark, a funding settlement, or an auto-deleveraging
close that lifts a counterparty’s bucket — the episode’s record closes as
status: "COMPLETED" and the owner receives one alert with that status and
risk_bucket_state: "Normal", carrying the same liquidation_id as the earlier
alerts for the episode. The alert describes the recovered bucket’s own
position, so a pair-scoped liquidations:{trading_pair_id} subscription on that
bucket’s pair receives it; a bucket with no open position carries null
position fields. Treat it as the episode’s terminal frame: it supersedes any
in-flight (UNRESOLVED) row a subscribe-time snapshot seeded.
Account
Margin-account health for the authenticated user: equity, collateral, free collateral, margin ratio, maintenance requirement, initial margin required, withdrawable collateral, and realized PnL. There is no per-pair variant — one subscription covers every margin account the user owns. Frames flow while an account is active (it holds an open position or a resting order reserve): when its last position and reserve clear, one final frame carries the released state (maintenance requirement back to zero, free collateral restored), and after that the account sends no keepalive while it stays flat. A flat account still gets a frame after its collateral moves: a transfer between the spot wallet and margin, an on-chain deposit into margin or a withdrawal from it, a transfer between your margin accounts, closing a sub-account, or an insurance payout. Moves that land before the producer’s next tick collapse into one frame carrying the latest state, and that frame normally arrives on the next tick, within ~2s of the move. The producer reads at most 512 flat accounts per tick, so a burst wider than that spreads over the following ticks. The frame carries the account’s current collateral on the same per-accountsequence as every other frame, so the usual ordering rule applies. On-chain deposits and withdrawals also appear on the movements channel. The producer samples on a ~2s tick, so a position or reserve that opens and fully closes inside one tick is below the sampling cadence — no frame marks it, and the account’s previous state stands until its next activity.
The server-side producer that emits live
account_update frames runs on every deployment, mainnet included. Enablement is a deployment switch rather than a delivery guarantee, so confirm you are receiving frames before depending on the live stream. The subscribe-time snapshot below is served by the WebSocket API rather than that producer, so it is unaffected by the switch.updated_at, newest wins; sequence (a plain JSON number) only breaks ties between frames carrying the same updated_at (those come from the same producer run). A snapshot row is not ranked this way — any live frame supersedes it. sequence resets to 0 on a producer restart (which can happen while your socket stays connected), may skip values, and is never a gap detector or a cross-restart order. A subscription made while an account is flat receives no LIVE frame for it until the account re-activates, because keepalives cover only active accounts — but the subscribe-time snapshot below includes it, so the baseline is complete. Every decimal value is a JSON string; wire keys are snake_case (like every other raw frame on this page), and the payload nests under the channel envelope’s data:
Subscribe-time snapshot
On subscribe, before any live frame, the server sends aSnapshot frame on the account channel whose data is an array with one row per margin account the authenticated user owns in the session’s application — including flat accounts, which the live producer emits for only when their collateral moves. Each row’s updated_at is the instant that account’s state was persisted, not the time the snapshot was read, so rows of one frame legitimately differ.
Live delivery is per user and carries no application filter, so a wallet trading through more than one application also receives live frames for its other accounts. Those are terminal-state payloads, so such an account baselines itself from its next frame (within the ~30s keepalive) despite not appearing in this list. Each row carries that account’s current persisted health. An account that is flat and otherwise empty — no positions and no open risk bucket — reports its deposited collateral as both equity and free_collateral, with maintenance_requirement and margin_ratio at 0. An account that is flat but still holds an open risk bucket keeps that bucket’s allocated collateral and unsettled realized PnL, so its equity need not equal its collateral. A user who owns no margin account receives "data": [], not a missing frame.
A snapshot row is the live data payload with sequence omitted:
sequence is the live producer’s process-local per-account counter and the WebSocket API is a different service, which cannot mint one; 0 is not available either, because it is indistinguishable from a restarted producer’s first frame and would make a consumer applying the dedupe rule discard real live frames. Absent means unknown — never read it as zero. Ranking still works without it, but not by comparing a snapshot row’s updated_at against a live frame’s. A live frame always supersedes a snapshot row for the same margin account, whatever the timestamps say: the snapshot is stamped when its state was persisted (database write time) and a live frame when the engine sampled it, so under persistence lag a later-written row can carry older state. Use updated_at to order live frames against each other — newest wins — with sequence breaking ties inside one producer run, which a snapshot is not part of. A durable per-account version would make the two surfaces genuinely comparable; until then the snapshot is a seed, not an authority. That rule also applies to live frames emitted before your subscription activated: the connection buffers them while the snapshot read runs and delivers them after it, so one can supersede a newer snapshot row. A later frame normally corrects this within the ~30s keepalive. The exception is an account that went flat during that window and whose final frame never reached you — the producer emits one, but it derives departures from in-process state, so a producer restart across the transition emits none — in which case you keep a stale active account until you reconnect and re-seed. Reconnecting and re-seeding is the recovery for this, as it is for dropped events.
margin_ratio is the maintenance margin required divided by equity; it is 0 for an account with no open positions. It saturates to a maximum-distress sentinel (a very large decimal string, Decimal::MAX ~7.9e28) whenever the ratio cannot be computed or represented: a maintenance requirement still owed at zero or negative equity, and equally at near-zero positive (dust) equity where the true ratio exceeds the decimal range. Treat a value at or above the liquidation threshold as maximal distress and clamp it for display. equity is mark-inclusive (collateral + unrealized PnL + funding).
initial_margin_required, withdrawable_collateral, and realized_pnl are the same values the margin-account summary returns for the account’s parent row (initialMarginRequired, withdrawableCollateral, realizedPnl), on live frames and snapshot rows alike:
initial_margin_requiredis the initial margin your open positions and resting orders require. Placing or cancelling a resting order moves it (andwithdrawable_collateral) without moving equity, and the next frame, normally within ~2s, carries the new values.withdrawable_collateralis the largest amount a withdrawal or transfer out of the margin account accepts. It is floored at zero and rounded toward zero at 6 decimal places, so a transfer of exactly this amount is accepted. It is notfree_collateral: free collateral is equity headroom for new positions and can exceed what you can move out.realized_pnlis realized PnL settled to the margin account plus net funding. Realized PnL still held by an open risk bucket is not in it; the margin-account PnL endpoint reports that part.
sdk.ws.account(handler) helper (see TypeScript WebSockets) subscribes and hands you the camelCased AccountEvent shape. To consume the channel over the raw WebSocket protocol above instead, send a Subscribe frame naming the account channel and read the snake_case wire keys directly — or map them yourself onto the AccountEvent type in @0xmonaco/types (event_type → eventType, margin_account_id → marginAccountId, free_collateral → freeCollateral, and so on; that type describes the ergonomic shape the helper exposes, not these raw keys).
