Skip to content

Streams

Subscribe to live trades, books, candles, tickers, marks and numbered account reports over WebSocket, merge order-book updates, resume account streams after a reconnect, and recover cleanly from gaps.

On this page

A stream is a subscription on one WebSocket connection. You open it with atlas.subscribe, the server pushes stream.* notifications tagged with your subscriptionId, and it ends when you unsubscribe, the server sends stream.closed, or the connection drops. A market stream has no replay: if you miss something, you resubscribe and start from a fresh snapshot. The two account streams number their reports, so you can resume them where you left off.

Market streams
Account streams
One subscribe
Ordering
Order book
Recovery

Available streams

streamPush methodParamsEndpointPayloadSnapshot first?
tradesstream.tradesmarketId/market/wsTrade[]Yes
order_bookstream.order_bookmarketId, optional interval/market/wsOrderBookUpdateYes, then deltas
candlesstream.candlesmarketId, interval/market/wsCandle[]Yes
tickerstream.tickermarketId/market/wsTickerYes
mark_pricestream.mark_pricemarketId (perps)/market/wsMarkPriceYes, if one exists
bbostream.bbomarketId/market/wsBBOYes
ordersstream.ordersaccountAddress, optional types and afterReportNo/account/wsNumbered order and fill reportsYes, unless you resume
accountstream.accountaccountAddress, optional types and afterReportNo/account/wsNumbered balance, position, payment, wallet-state and account reportsYes, unless you resume

Funding payments arrive on stream.account as payment reports; there is no separate funding stream. Account health and advanced (TP/SL and TWAP) orders have no stream: read them with atlas.getAccountState and atlas.getAdvancedOrders.

If you need both market and account streams, open two connections: one to /market/ws, one to /account/ws.

Subscribing

atlas.subscribe

atlas.subscribeWebSocket/market/ws, /account/ws

Creates one subscription on this connection. Takes a named params object.

streamenumrequired
marketIdinteger
intervalstring
accountAddressAccountAddress
typesstring[]
afterReportNoUint64String

A market stream refuses a symbol param with -32602: select the market by marketId.

Result

subscribe result

subscriptionIdSubscriptionIdrequired
snapshotSupportedbooleanrequired
Try itatlas.subscribeWebSocket
paramsedit me
const ws = new WebSocket("wss://<ws-host>/market/ws");

ws.onopen = () => ws.send(JSON.stringify({
    "jsonrpc": "2.0",
    "id": 1,
    "method": "atlas.subscribe",
    "params": {
      "stream": "order_book",
      "marketId": 4294967297
    }
  }));

ws.onmessage = (ev) => {
  const msg = JSON.parse(ev.data);
  if (msg.id === 1) console.log(msg.result ?? msg.error);
};
Sent to testnet by the docs server, which adds the API key
Response
Press Send to see the response.
ErrorWhen
-32602Unknown stream, a stream not served on this endpoint, a missing or malformed marketId, interval, accountAddress, types or afterReportNo, a symbol on a market stream, or an interval the service doesn't publish
-20008Unknown market id
-20003The market catalog can't be read. Retry with backoff
-20005This connection already holds the most subscriptions it may. Unsubscribe one first

To subscribe to several streams, send several atlas.subscribe requests. You can send them back to back without waiting for each response.

atlas.unsubscribe

atlas.unsubscribeWebSocket/market/ws, /account/ws
subscriptionIdSubscriptionIdrequired
Try itatlas.unsubscribeWebSocket
paramsedit me
const ws = new WebSocket("wss://<ws-host>/market/ws");

ws.onopen = () => ws.send(JSON.stringify({
    "jsonrpc": "2.0",
    "id": 1,
    "method": "atlas.unsubscribe",
    "params": {
      "subscriptionId": "sub_7f3a"
    }
  }));

ws.onmessage = (ev) => {
  const msg = JSON.parse(ev.data);
  if (msg.id === 1) console.log(msg.result ?? msg.error);
};
Sent to testnet by the docs server, which adds the API key
Response
Press Send to see the response.

After the success response, no more events arrive for that subscriptionId. An unknown id returns -20004.

Account streams and sign-in

Account streams need no sign-in. To sign a connection in anyway, see Sign in to a WebSocket.

Every event

Each notification's params object always carries these three fields, plus the stream's payload.

Every notification

subscriptionIdSubscriptionIdrequired
seqSeqStringrequired
snapshotbooleanrequired

Times inside payloads (timestamp, T, createdAt and so on) are JSON integers of Unix milliseconds. Prices, sizes and amounts are decimal strings.

Sequence and snapshots

Every subscription starts with a response carrying its subscriptionId, then a snapshot at seq "1" (except an account stream you resume, and mark_price before its first tick), then updates. The session under Recovering from a gap shows each frame.

  • Track seq separately for each subscription, and compare it as an integer.
  • When snapshot is true, replace your local state for that subscription. The server may send another snapshot later. Treat each one the same way.
  • When snapshot is false, apply it as an update according to the stream's rules below.

Recovering from a gap

If seq skips, repeats or goes backwards, your state for that subscription is wrong. Waiting for the next snapshot is not enough.

  1. Discard

    Throw away local state for that subscription. On an account stream, keep the last reportNo you applied.
  2. Unsubscribe

    Send atlas.unsubscribe for the old id, if the connection is still up.
  3. Subscribe again

    Send a fresh atlas.subscribe. You get a new subscriptionId and seq restarts at "1". On an account stream, pass afterReportNo to resume instead of starting over.
  4. Rebuild

    Rebuild from the new snapshot, or apply the resumed reports.

If the connection closes, every subscription on it is gone. Reconnect and subscribe again.

Play the session below, then try both failure modes. A gap costs you one subscription; a dropped connection costs you all of them.

WebSocketOrder book: gaps and reconnectsopen
wss://<ws-host>/market/ws 1 4
  1. + 0ms●connection open
Books trimmed to two levels a side. After the snapshot, each frame carries only the levels that changed.
Gap-safe subscription (TypeScript)
type Sub = { stream: string; marketId?: number; interval?: string; accountAddress?: string };
 
const ws = new WebSocket("wss://<ws-host>/market/ws");
let nextId = 1;
const pending = new Map<number, Sub>();          // request id -> subscribe params
const lastSeq = new Map<string, bigint>();       // subscriptionId -> last seq
const subs = new Map<string, Sub>();             // subscriptionId -> params
 
function subscribe(params: Sub) {
  const id = nextId++;
  pending.set(id, params);
  ws.send(JSON.stringify({ jsonrpc: "2.0", id, method: "atlas.subscribe", params }));
}
 
function resubscribe(subId: string) {
  const params = subs.get(subId)!;
  subs.delete(subId);
  lastSeq.delete(subId);
  ws.send(JSON.stringify({ jsonrpc: "2.0", id: nextId++, method: "atlas.unsubscribe", params: { subscriptionId: subId } }));
  subscribe(params);
}
 
ws.onopen = () => subscribe({ stream: "order_book", marketId: 4294967297 });
 
ws.onmessage = (ev) => {
  const msg = JSON.parse(ev.data);
 
  if ("id" in msg) {                              // a response
    const params = pending.get(msg.id);
    if (params && msg.result) subs.set(msg.result.subscriptionId, params);
    pending.delete(msg.id);
    return;
  }
 
  const { subscriptionId, seq, snapshot } = msg.params;
  if (msg.method === "stream.closed") {          // server ended it
    subs.delete(subscriptionId);
    return;
  }
 
  const n = BigInt(seq);                          // compare as integers, not strings
  const prev = lastSeq.get(subscriptionId);
  if (prev !== undefined && n !== prev + 1n) return resubscribe(subscriptionId);
  lastSeq.set(subscriptionId, n);
 
  if (snapshot) {
    // replace local state with msg.params.data
  } else {
    // apply msg.params.data as an update (see each stream's rules)
  }
};

Market streams

stream.trades

Public trades for one market.

  • First event (snapshot: true): the most recent trades, up to 50, newest first. Replace your cached tape.
  • Then (snapshot: false): data holds one new trade.
  • A later snapshot means the server resynced and trades may have been missed. Treat it as replacement state: replace your tape with it, don't append it. It is not a replay of everything you missed; read atlas.getTrades to fill a gap.
  • Payload: Trade[]. See atlas.getTrades. liquidation: true marks a liquidation's trade, so filtering on it gives a venue-wide liquidation feed.
{
  "jsonrpc": "2.0",
  "method": "stream.trades",
  "params": {
    "subscriptionId": "sub_19c2",
    "seq": "214",
    "snapshot": false,
    "data": [{ "marketId": 4294967297, "symbol": "BTCUSDT-PERP", "price": "70150", "size": "0.05", "side": "buy", "timestamp": 1791210612345, "tradeId": "core:1335088:11" }]
  }
}

stream.order_book

The book for one market: one snapshot, then incremental updates. Levels are [price, size] pairs of decimal strings, best first.

  • First event (snapshot: true): up to 500 levels per side, and the updateId of the book state it shows.
  • Then (snapshot: false): a delta for each interval in which the book changed. It holds only the levels that changed, each at its new absolute size. Size "0" removes the level.
  • The server may send a new snapshot at any time. Apply it like the first one.

OrderBookUpdate

marketIdintegerrequired
symbolSymbolrequired
updateIdUint64Stringrequired
prevUpdateIdUint64String
bidsPriceLevel[]required
asksPriceLevel[]required
timestampTimestampMsrequired

To merge, keep a book keyed by price and the updateId it shows:

  1. On a snapshot

    Replace the whole book and take its updateId.
  2. On a delta, check it

    If its updateId is not above your book's, skip it. If its prevUpdateId is above your book's updateId, a delta is missing: resubscribe.
  3. Apply it

    Otherwise (prevUpdateId ≤ your updateId < its updateId), set each listed level to its size, remove the levels whose size is "0", and take the delta's updateId.

The first delta's prevUpdateId can be below the snapshot's updateId, as in the example; it still applies, because sizes are absolute. A delta can name levels deeper than the snapshot's 500 per side, so a deep level appears only once it changes. Trim your book to the depth you display.

Merge order-book frames (TypeScript)
type Level = [string, string];
type Book = { updateId: bigint; bids: Map<string, string>; asks: Map<string, string> };
let book: Book | undefined;
 
function onOrderBook(params: { snapshot: boolean; data: { updateId: string; prevUpdateId?: string; bids: Level[]; asks: Level[] } }) {
  const { snapshot, data } = params;
  const id = BigInt(data.updateId);
  if (snapshot) {
    book = { updateId: id, bids: new Map(data.bids), asks: new Map(data.asks) };
    return;
  }
  if (!book || id <= book.updateId) return;                        // stale: skip
  if (BigInt(data.prevUpdateId!) > book.updateId) return resync(); // a delta is missing
  for (const [side, levels] of [[book.bids, data.bids], [book.asks, data.asks]] as const) {
    for (const [price, size] of levels) {
      if (/^0(\.0+)?$/.test(size)) side.delete(price); else side.set(price, size);
    }
  }
  book.updateId = id;
}
 
function resync() { book = undefined; /* unsubscribe and subscribe again */ }

The sketch keys levels by the price string as sent. If you mix in prices from elsewhere, normalize them to one form first (for example the market's priceScale decimals) so "70200" and "70200.0" hit the same level. Sort by numeric value when you render.

{
  "jsonrpc": "2.0",
  "method": "stream.order_book",
  "params": {
    "subscriptionId": "sub_7f3a",
    "seq": "2",
    "snapshot": false,
    "data": {
      "marketId": 4294967297,
      "symbol": "BTCUSDT-PERP",
      "prevUpdateId": "1361390",
      "updateId": "1362215",
      "bids": [],
      "asks": [["70200", "0"], ["70400", "1.2"]],
      "timestamp": 1791210612480
    }
  }
}

This delta removes the 70,200 ask and sets 1.2 at 70,400. For a one-off snapshot over HTTP, use atlas.getOrderBook, which returns levels as { price, size } objects.

stream.candles

Candles for one market and interval. Payload: Candle[], the same shape as atlas.getCandles.

  • First event (snapshot: true): recent history. Each candle's x says whether it is final.
  • Then (snapshot: false): one candle, either the live one updating (x: false) or a window closing (x: true).
  • Upsert by t. A later frame for the same t replaces the earlier one, even after x: true.
  • An interval with no trades has no candle, so the next t can skip ahead. The closing frame can arrive a moment after T.
{
  "jsonrpc": "2.0",
  "method": "stream.candles",
  "params": {
    "subscriptionId": "sub_c41d",
    "seq": "88",
    "snapshot": false,
    "data": [{ "marketId": 4294967297, "t": 1791210000000, "T": 1791210060000, "s": "BTCUSDT-PERP", "i": "1m", "o": "70120", "h": "70160", "l": "70100", "c": "70150", "v": "2.315", "n": 41, "x": false }]
  }
}

stream.ticker

Payload: Ticker, the same shape as atlas.getTicker: top of book, last trade, the full rolling 24-hour window (including tradeCount24h, the number of trades in it), mode, mark and index price, and for perps funding, impact prices and open interest. Every frame carries the full ticker, so replace your cached ticker each time. A frame is pushed when the ticker changes.

stream.bbo

Payload: BBO (marketId, s, b, B, a, A, T), the same shape as atlas.getBBO. Sent when the top of book changes. Every frame is the full current BBO, so replace your cached value each time. Like the ticker, it is a latest-state stream: if you fall behind, the server may skip intermediate values and send only the latest. A side with no orders reads "0". For every price level, use stream.order_book.

stream.mark_price

Perps only. A light bundle of the mark price, index price and funding, restated periodically. No book or 24h stats. A spot pair's mark is on its ticker.

  • First event (snapshot: true): the latest tick, if one exists. If none has been produced yet, no snapshot is sent.
  • Then (snapshot: false): one event per tick.

stream.mark_price params

subscriptionIdSubscriptionIdrequired
seqSeqStringrequired
snapshotbooleanrequired
dataMarkPricerequired
›Show 7 child fields
marketIdintegerrequired
symbolSymbolrequired
markPricePricerequired
indexPricePrice | nullrequired
fundingRateDecimalString
nextFundingTimeTimestampMs
timestampTimestampMsrequired
{
  "jsonrpc": "2.0",
  "method": "stream.mark_price",
  "params": {
    "subscriptionId": "sub_e902",
    "seq": "3",
    "snapshot": false,
    "data": { "marketId": 4294967297, "symbol": "BTCUSDT-PERP", "markPrice": "70148.5", "indexPrice": "70139.2", "fundingRate": "0.0001", "nextFundingTime": 1791212400000, "timestamp": 1791210612000 }
  }
}

fundingRate is a decimal fraction here, on stream.account payment reports and on atlas.getFundingHistory. atlas.getFundingRateHistory still reports rateBps in basis points.

indexPrice here is for display only.

Account streams

stream.orders and stream.account deliver an account's reports in order, each one numbered. A subscription starts with a snapshot of the current state, then sends every report after it. If you disconnect, subscribe again with the last report number you hold and the stream picks up after it.

StreamReportsSnapshot
ordersorder, fillEvery open order of the account, in openOrders
accountbalance, position, payment, walletState, accountReportThe account state, as atlas.getAccountState returns it, in account

Every other frame arrives on both streams: snapshot, heartbeat, gapNotice and reject. Shapes inside a report are identical to what the matching HTTP read returns: atlas.getOpenOrders and atlas.getFills for orders and fills, atlas.getBalances and atlas.getPositions for balances and positions, atlas.getFundingHistory for payments.

Report numbers

Each report frame carries:

Report fields

reportNoUint64Stringrequired
gkobjectrequired
logTimeTimestampMsrequired
txIdTxId
causeenum

The two streams are numbered and ordered separately. Within stream.orders an order report and the fill it follows never arrive out of order, and within stream.account the same holds for a balance, a position and the reports around them. Nothing orders a frame of one stream against a frame of the other, so an order report and the balance it moves can arrive in either order. If you hold both subscriptions, don't join their frames by reportNo or gk.

Snapshots

A subscription without afterReportNo starts with a snapshot frame (snapshot: true). Replace what you hold for the account with it, then apply every report numbered above its reportNo.

snapshot data

typestringrequired
reportNoUint64Stringrequired
coveredThroughUint64Stringrequired
openOrdersOrder[]
accountAccountState

The server can also send a snapshot later, for example after a gapNotice, or on stream.account after a change no other report shows. A later snapshot is numbered like a report. Apply every snapshot the same way.

Resuming after a reconnect

Keep the highest reportNo you have applied, separately for each account and each stream. To resume, subscribe again with it as afterReportNo:

{ "jsonrpc": "2.0", "id": 7, "method": "atlas.subscribe", "params": { "stream": "orders", "accountAddress": "0x8f3a6c1e2b9d4f7a0c5e8b1d3f6a9c2e4b7d0f15", "afterReportNo": "1842" } }
  • Within reach: if the missing reports are still retained (currently about an hour), you get every report after afterReportNo, once and in order, with no snapshot first.
  • Out of reach: otherwise the stream sends a gapNotice naming the reports it can't deliver, then a replacement snapshot. Replace your state with it and continue from its reportNo.
  • History unavailable: if the account's reports can't be read, the subscription is closed with stream.closed and -20003 (Service unavailable). Retry with backoff.

Report numbers belong to the stream, not to RPC paging: don't pass a reportNo as a history cursor, or a cursor as afterReportNo. atlas.getOpenOrders pagination is separate.

Filtering report types

Pass types to receive only some report types, for example ["fill"] on orders or ["balance", "payment"] on account. snapshot, gapNotice and heartbeat frames always arrive.

A filter doesn't renumber the stream: the reports you don't receive keep their numbers, so reportNo jumps. That jump is not a loss. Track progress with the heartbeat's scannedThrough instead, and resume from the higher of your last reportNo and the last scannedThrough.

Heartbeats, gaps and rejects

Control framesone of 3, by data.type
typestringrequired
watermarkUint64Stringrequired
logTimeTimestampMsrequired
scannedThroughUint64Stringrequired

stream.orders

Order and fill reports for one account.

stream.orders params

subscriptionIdSubscriptionIdrequired
seqSeqStringrequired
snapshotbooleanrequired
accountAddressAccountAddressrequired
dataobjectrequired

Each report also carries the report fields: reportNo, gk, logTime, and txId or cause.

stream.orders reportsone of 2, by data.type
typestringrequired
orderOrderrequired
{
  "jsonrpc": "2.0",
  "method": "stream.orders",
  "params": {
    "subscriptionId": "sub_a001",
    "seq": "16",
    "snapshot": false,
    "accountAddress": "0x8f3a6c1e2b9d4f7a0c5e8b1d3f6a9c2e4b7d0f15",
    "data": {
      "type": "order",
      "reportNo": "1843",
      "gk": { "height": "40211873", "ordinal": 0 },
      "logTime": 1791210612351,
      "txId": "0x27ca64c092a959c7edc525ed45e845b1de6a7590d173fd2fad9133c8a779a1e3",
      "order": { "orderId": "perp:1:48213", "accountAddress": "0x8f3a6c1e2b9d4f7a0c5e8b1d3f6a9c2e4b7d0f15", "clOrdId": "0x5f1c9a7e3b2d4c6e8a0b1d3f5e7c9a2b", "txId": "0x27ca64c092a959c7edc525ed45e845b1de6a7590d173fd2fad9133c8a779a1e3", "marketId": 4294967297, "seq": 48213, "side": "buy", "type": "limit", "price": "70300", "size": "1", "status": "partially_filled", "filledSize": "0.4", "remainingSize": "0.6", "trimmedSize": "0", "avgFillPrice": "70220", "marginMode": "cross", "createdAt": 1791210612345, "updatedAt": 1791210612351, "signerRole": "agent" }
    }
  }
}

Orders and fills carry marketId, not a symbol: resolve the display symbol from atlas.getSymbols.

  • Orders: to tie an order report back to your write, match order.txId to the txId your atlas.sendRawTransaction result carried. A transaction carries one command, so its txId identifies it. The report frame's own txId names the transaction that produced that report, so a cancel's report carries the cancel's txId while order.txId stays the one that placed the order.
  • Fills: match a fill to your order by orderId. A fill's txId is the transaction that produced the trade: your own write on a taker fill, the other side's when your resting order is hit.

Orders and fills no client-signed transaction caused, such as a liquidation's fills or an order placed for a TP/SL or TWAP, carry no txId.

stream.account

Balance, position, payment, wallet-state and account reports for one account.

stream.account params

subscriptionIdSubscriptionIdrequired
seqSeqStringrequired
snapshotbooleanrequired
accountAddressAccountAddressrequired
dataobjectrequired

A balance or position report shows the state after the change and names the transaction that last changed it. Every report also carries the report fields; the examples below include them once.

stream.account reportsone of 5, by data.type
typestringrequired
balanceBalancerequired
›Show 8 child fields
placeenumrequired
symbolSymbol
assetstringrequired
assetIdintegerrequired
totalDecimalStringrequired
availableDecimalStringrequired
heldDecimalStringrequired
unstakeDueNsUint64String
{
  "jsonrpc": "2.0",
  "method": "stream.account",
  "params": {
    "subscriptionId": "sub_a002",
    "seq": "4",
    "snapshot": false,
    "accountAddress": "0x8f3a6c1e2b9d4f7a0c5e8b1d3f6a9c2e4b7d0f15",
    "data": {
      "type": "balance",
      "reportNo": "903",
      "gk": { "height": "40211873", "ordinal": 0 },
      "logTime": 1791210612351,
      "txId": "0x27ca64c092a959c7edc525ed45e845b1de6a7590d173fd2fad9133c8a779a1e3",
      "balance": { "place": "cross", "asset": "USDT", "assetId": 1, "total": "25000", "available": "24850", "held": "150" }
    }
  }
}

Values in these examples are illustrative.

When the server ends a stream

stream.closed

The server can end a subscription while keeping the connection open. It always sends stream.closed first, and that is the last message for that subscriptionId.

stream.closed params

subscriptionIdSubscriptionIdrequired
seqSeqStringrequired
snapshotbooleanrequired
reasonCodeErrorCode (integer)required
messagestringrequired
{
  "jsonrpc": "2.0",
  "method": "stream.closed",
  "params": { "subscriptionId": "sub_7f3a", "seq": "42", "snapshot": false, "reasonCode": -20006, "message": "Slow consumer" }
}

Mark the subscription closed. Resubscribe if you still want it. Treat unknown reasonCode values as normal, not as parse errors.

Slow consumers

If you read too slowly, ATLAS protects itself in two steps.

StepWhat happensSignal
1Expensive subscriptions are droppedstream.closed with reasonCode: -20006
2If you are still too slow, the connection is closedThe WebSocket closes, with or without stream.closed (-20007) for each subscription first

Don't rely on a close code or reason text. Treat the close itself as the signal: every subscription on that connection is gone. Reconnect with jittered exponential backoff, then subscribe again, resuming account streams from their last reportNo.

Heartbeats

Liveness uses standard WebSocket ping and pong frames. The server pings; most WebSocket libraries answer automatically. On /market/ws and /account/ws, a connection that stops answering pings is closed. Reconnect and subscribe again.