Skip to Content
API ReferenceWebSocket API

WebSocket

Live market data and your account. URL: wss://api.loafmarkets.com/ws.

Market channels are keyed by ticker: orderbook:TERA, orderbook:TERA-PERP. Frames name the same ticker.

Connect

{ "type": "subscribe", "channels": ["orderbook:TERA", "trades:TERA"], "timestamp": 1764000000 }

The server answers subscription_confirmed with the channels this socket holds. Unsubscribe with { "type": "unsubscribe", "channels": ["orderbook:TERA"] }.

An unknown channel, or another user’s portfolio, is an error frame.

code
UNKNOWN_CHANNEL
UNAUTHORIZED
SUBSCRIPTION_LIMIT
TOO_MANY_CHANNELS
INVALID_CHANNELS
RATE_LIMITED
UNSUPPORTED_MESSAGE_TYPE
INVALID_MESSAGE

INVALID_MESSAGE answers a frame that is not JSON, or is a bare JSON value such as a string or null. Its message is Invalid message format.

Send { "type": "ping" } on a timer. The server answers { "type": "echo", "data": … }. A browser cannot see protocol ping frames, so use the echo to check that the socket is still open.

timestamp on a server frame is when the server sent it, in unix seconds. orderbook_update also carries engineMs (the engine’s clock, unix ms). Engine-sourced portfolio frames carry engineMs and batchSeq (the sequence number of the engine batch that made the change, not the explorer’s batchNumber). trades_batch, candle_update, and the other public frames carry neither. timestamp * 1000 - engineMs is how old the change was when the frame was sent, to within a second.

Auth

Private channels need an auth frame. The token is a login token or a Privy JWT. The socket does not read ?token= on the URL.

{ "type": "auth", "token": "loaf_lt_…" }

The server answers auth_result: { "type": "auth_result", "success": true, "userId": 4 }. On success you may subscribe to portfolio (your own user) or portfolio:{userId}. A login token does not need a separate profile call. GET /api/auth/profile takes only a Privy JWT. A login token is refused there.

Another auth frame on the same socket replaces the credential. Send a fresh login token before the current one expires. Auth frames are rate limited per connection. Past the limit the socket is closed.

A failed auth leaves the socket anonymous: the portfolio channel drops, public channels stay. A second failed auth on that connection closes it. Reconnect with a valid token.

A login-token session ends with close code 4001 and reason expired at the token’s expiry. A Privy JWT session ends the same way, shortly after the JWT’s exp.

The server can also close a socket that holds portfolio or a trades:{ticker} channel, with code 1012 and reason resync. Frames on those channels may have been lost. The server does not send them again. Reconnect, send auth again for portfolio, and subscribe again. Then seed again from REST.

A new socket can be closed as it opens, with code 1013 and reason too many connections. Hold fewer sockets, and reconnect with backoff.

Channels

ChannelAuthFrames
orderbook:{ticker}Publicorderbook_update. The book when it changes, throttled, and resent periodically even when it did not change. A frame carries the best levels on each side. A very deep book is cut off. engineMs is the engine time of the book’s last change. A quiet market keeps sending, with the old engineMs.
trades:{ticker}Publictrades_batch. Trades since the last batch. A new subscriber first gets the most recent trades. A liquidation take is a row with isLiquidation: true and no txHash.
chart:{ticker}Publiccandle_update
markprice:{ticker}Publicmark_price when the mark moves, throttled. A new subscriber gets the current mark immediately. price is an exact decimal string. On a perp it is the same value as live.markPrice.
volume:{ticker}Publicvolume_update with volume24h
market:{ticker}Publicmarket_halt with isHalted
perps:marketsPublicperps_markets_live periodically, and the current list immediately to a new subscriber. market_terms_update when a perp’s l2 terms change.
ipo:{ipoId}Publicipo_allocation_update
competitionPublicround_update
leaderboardPublicleaderboard_update when the board changes, including a halt
portfolio or portfolio:{userId}Login token or Privy JWTAccount frames below

Seed the book, candles, and account from REST, then listen. orderbook, trades, markprice, and perps:markets also send the current values to a new subscriber. chart, volume, market, ipo, leaderboard, and portfolio do not replace a REST seed. A new leaderboard subscriber gets nothing until the board changes. Seed the board from GET /api/leaderboard. See Ask once, then listen.

Frames

orderbook_update:

FieldMeaning
tickerMarket ticker
bidsLevels { price, quantity }
asksLevels { price, quantity }
engineMsEngine time of the book’s last change

trades_batch. A liquidation take has isLiquidation: true and no txHash.

FieldMeaning
tickerMarket ticker
tradesThe rows below
FieldMeaning
tradeIdTrade id
txHashAbsent on a liquidation take
aggressorSideBUY or SELL
pricePrice
quantityQuantity
timestampUnix seconds
isLiquidationSet on a liquidation take

candle_update:

FieldMeaning
tickerMarket ticker
candleThe bar below
FieldMeaning
timeUnix seconds
openOpen
highHigh
lowLow
closeClose
volumeVolume

mark_price, volume_update, and market_halt:

FrameFields
mark_priceticker, price. price is an exact decimal string. On a perp it is the same value as live.markPrice
volume_updateticker, volume24h
market_haltticker, isHalted

perps_markets_live is { markets }, each a perp’s market.live from Trade.

market_terms_update:

FieldMeaning
marketIndexPerp market index
tickerMarket ticker
l2The perp’s l2 object

ipo_allocation_update:

FieldMeaning
ipoIdOffering id
subscribersSubscriber count
unitsAllocatedUnits allocated
ordersAllocatedOrders allocated
recentOrdersRecent orders

round_update:

FieldMeaning
roundNumberRound number
statusRound status
startsAtStart, unix seconds
endsAtEnd, unix seconds
arenaTickerArena ticker

leaderboard_update is { leaderboard } in the leaderboard shape.

Portfolio frames

Subscribe to portfolio after auth. Seed with GET /api/portfolio/summary and GET /api/portfolio/component, then apply frames.

typePayload
balances_updatebalances, the full list, same rows as the summary
holding_updateholding and details
perps_account_updateThe row below. snapshot: true is a full account, flat pools included, sent periodically on a login-token socket
order_updateorder, a history row, including conditionals
order_statusThe row below
order_queueLogin-token sockets only. A non-empty list is resent periodically, even when unchanged. The row is below
trade_newtrade, a history fill without proof. Read proof from GET /api/history/trades
funding_paymentfunding, a funding row
transfer_updatetransfer
fees_updateapplicableFees
lifetime_volume_updatelifetimeVolume
offering_order_updateorder
l2_keys_updateapiKeyIndices that changed
relay_update{ txHash, calls }, the same object as GET /api/relay/:txHash
perps_leverage_update{ ticker, leverage }

perps_account_update:

FieldMeaning
perpsl2AccountIndex and pools
accountModeOptional
withdrawableOptional

order_status:

FieldMeaning
orderIdOrder id
statusOrder status
quantityLeftUnfilled remainder
cancelReasonOptional
l2OrderIndexOptional
orderTagOptional

order_queue is { marketIndex, orders }. Each order:

FieldMeaning
orderIdOrder id
sideBUY or SELL
pricePrice
quantityQuantity
quantityAheadQuantity ahead of this order
ordersAheadOrder count ahead of this order

Engine-sourced frames carry engineMs and batchSeq. One engine batch’s frames share batchSeq. For a deposit or withdrawal, balances_update and holding_update carry the batchSeq of the latest engine batch, not one of its own. transfer_update carries neither engineMs nor batchSeq.

Last updated on