WebSocket¶
The dashboard's live data comes over one WebSocket per window, served by the same
WebServer thread as the
REST API. The server polls the event bus itself and pushes what it reads: order events,
P&L, broker status and, for the instruments a client asked about, level 2 books and trades. Clients
send only subscriptions and pings. Orders go in over REST, never here.
Connect to ws://<host>:<port>/. The route is /*, so any path upgrades, and there is no
sub-protocol, token or Origin check. Messages are JSON text frames in both directions. Prices and
quantities are plain numbers, not the engine's 1e-8 fixed point.
Anyone who can reach the port can listen
There is no authentication on the socket, and it sees every order, fill and P&L update of every strategy. See the note under REST API.
Connecting¶
On open the server sends welcome. In the Sim environment (with the control link on) it follows
with a sim_status, so a window knows slick-sim's state without a REST round trip that could land
after a later change. Nothing else is sent until the client subscribes, apart from the broadcasts
below.
Client to server¶
| Message | Effect |
|---|---|
{"type":"subscribe","channel":"instruments"} |
Sends the whole instrument list now, then additions as they come |
{"type":"subscribe","channel":"level2","instrument":"ZNZ6"} |
Streams that instrument's book and trades, answered with subscribed and a snapshot |
{"type":"unsubscribe","channel":"level2","instrument":"ZNZ6"} |
Stops them. No reply |
{"type":"ping"} |
Answered with {"type":"pong"} |
Everything else is logged and dropped with no reply: an unknown type, an unknown channel, JSON
that does not parse, and a level2 subscribe with an empty or over-long instrument. There is no
unsubscribe for instruments, a client keeps that channel until it closes. A repeated level2
subscribe is not an error. It answers with a fresh snapshot, which is how a page that rebuilt its
ladder gets the book again.
Server to client¶
Broadcasts go to every connected client. Per-subscription messages go only to the clients that asked.
type |
Goes to | When |
|---|---|---|
welcome, pong |
the one client | Connect, ping |
subscribed, subscription_error |
the one client | A level2 subscribe |
instruments, instruments_added |
clients on instruments |
Subscribe, then at most every 250 ms |
level2, trade |
clients watching that instrument | Subscribe, then each update |
order_update |
all | Each order or fill event |
pnl_update |
all | A top of book moved, at most every 250 ms |
broker_status |
all | Any broker connection flag changed |
sim_status, sim_replay |
all | In Sim, see Simulator |
instruments and instruments_added¶
Each value is [broker id, tick size, smallest order]. The tick and the smallest order are 0 when the
broker has not said. instruments is the whole list and replaces what the client had.
instruments_added has the same shape and carries what is new, or what just got a tick or a minimum
quantity, so the client merges it in. A name can come again in a later instruments_added.
The list is every instrument MANUAL lists plus what the loaded strategies subscribe, the first broker
named winning. With MANUAL on "*" it runs to megabytes, which is why it goes only to a client that
asks. The asked-for flag is per connection, so a reconnecting client asks again.
subscribed and subscription_error¶
{"type":"subscribed","channel":"level2","instrument":"ZNZ6"}
{"type":"subscription_error","channel":"level2","instrument":"ZNZ6","message":"could not ask for its market data"}
subscription_error means the first ladder on an instrument MANUAL lists could not have its feed held
because the event bus had no room. The subscribed and the snapshot still follow, so the book may stay
empty. Subscribing again retries the hold while that client is the only watcher.
level2¶
{"type":"level2","instrument":"ZNZ6","timestamp":1764547200123,"seq_num":42,
"is_snapshot":true,"levels":[[110.0,1000,0],[110.0625,1001,0],[110.5,1000,1]]}
timestamp is the event time in milliseconds. Each level is [price, quantity, side] with side 0 for
a bid and 1 for an ask. A quantity of 0 removes the level. When is_snapshot is true the client
replaces its book, and otherwise it applies the levels one by one. A broker splits a deep snapshot
into several events and only the first carries is_snapshot.
The answer to a subscribe is always a snapshot, built from the server's copy of the book (bids from the best, then asks from the best). The server keeps every book it has seen, watched or not, so a late subscriber still starts from the current state. The snapshot is empty when:
- the instrument has not streamed yet, or
- its broker's market data connector is enabled but disconnected. The copy is as the feed left it, so it is held back until the reconnect brings a fresh snapshot.
trade¶
side is the aggressor: 0 buy, 1 sell, 2 unknown. Trades go to the clients watching the instrument's
level 2, and the last one is sent again straight after a snapshot so a ladder opened late has its LTQ.
A trade of an instrument with no stream on the server is dropped, and one nobody watches is only
remembered.
order_update¶
One message type with an event field. Every order event reaches every client, so a window filters by
strategy_id or client_order_id itself. Each carries type, event, order_id (the broker's) and
instrument.
ack is sent once per change. A repeated ack that changes nothing the server tracks is dropped,
and an ack that names no known order and has no client id is dropped.
{"type":"order_update","event":"ack","order_id":"0a1b","instrument":"BTC-USD","side":"buy",
"price":50000.0,"qty":0.01,"remaining_qty":0.01,"status":"ACKNOWLEDGED",
"strategy_id":"MANUAL","client_order_id":"MANUAL_83412000000000"}
An ack that does not know its price or quantity (0) goes out with the ones the server already tracked.
status is an OrderStatus name (PENDING_NEW, ACKNOWLEDGED, PARTIALLY_FILLED and the rest).
fill
{"type":"order_update","event":"fill","order_id":"0a1b","instrument":"BTC-USD","side":"buy",
"price":50000.0,"qty":0.01,"status":"FILLED","fill_price":50000.0,"fill_qty":0.01,
"remaining_qty":0.0,"fill_id":"F1","fee":0.0,"timestamp_ns":83412200000000,
"strategy_id":"MANUAL","client_order_id":"MANUAL_83412000000000","seq":17}
price and qty are the order's, fill_price and fill_qty this fill's. status is FILLED or
PARTIALLY_FILLED, and empty with price and qty 0 for a fill of an order the server does not
track. Fills a broker replays from its journal at startup are not sent.
leg_fill is one leg of a multi-leg order. It names the leg's own instrument, side,
fill_price, fill_qty, fill_id, fee and timestamp_ns, adds client_order_id and strategy_id
when the order is known, and moves a position without touching the order.
Both fill events carry a seq, which grows by one for every fill and leg fill the server sends. The
same messages fill GET /api/fills, so a client that loaded that list and kept listening drops what it
has by seq.
cancel and reject
{"type":"order_update","event":"cancel","order_id":"0a1b","instrument":"BTC-USD","side":"buy","price":50000.0,"qty":0.01}
{"type":"order_update","event":"reject","order_id":"","instrument":"BTC-USD","side":"buy","price":50000.0,"qty":0.01,"reason":"..."}
A cancel for an order the server no longer tracks (a broker repeating it) is not sent. A reject is
always sent, with empty fields when the order was not tracked. reason is the broker's text, cut to
fit, with bytes that are not UTF-8 replaced.
An order stays in /api/orders until its cancel or fill event arrives, so a cancel request alone
produces no message.
pnl_update¶
{"type":"pnl_update","pnl":{"MM":{"realized_pnl":11.8,"unrealized_pnl":4.1,"total_fees":0.5,"total_pnl":15.9}}}
The server raises a flag on each top of book event and sends the update at most every 250 ms while the
flag is set. A fill alone does not trigger one, so with no top of book moving the numbers can lag until
a client polls /api/pnl. The bundled windows poll as well.
broker_status¶
{"type":"broker_status","brokers":[{"id":1,"name":"Coinbase","md":{"enabled":true,"connected":true},
"order":{"enabled":true,"connected":true}}]}
The same list as /api/brokers, sent when any flag of any broker changes. It is not sent on connect, so
a client reads /api/brokers first.
Limits¶
| Limit | Value | Notes |
|---|---|---|
level2 subscriptions per client |
1,024 | The 1,025th is dropped. A dashboard watches one |
| Instrument name | 1 to 31 bytes | Longer is refused |
| Pending bytes per client | 16 MiB | See below. uWS defaults to 64 KB, which dropped the connect-time instrument list |
| Inbound message | 16 KB | The uWebSockets default, the code sets none. Larger closes the socket |
| Idle timeout | 120 s | Also a uWebSockets default, with automatic pings. The bundled client pings every 30 s |
Backpressure and lagging clients¶
The server never queues without bound. Each socket may hold 16 MiB of unsent data. When a send would go past that, uWS drops the message and says so, and the server marks the client as lagging. That client has lost a message for good, so its ladder or instrument list would stay short of it forever. The server therefore closes it:
- From then on the server ignores that client's messages. uWS can hand over thousands at once, and answering each with a snapshot held the close back for seconds.
- At the end of the current event loop pass the server closes the socket. The log line reads
closing a WebSocket client N KB behind, so it reconnects in step. - The close is forced, without a close frame, so a browser reports an abnormal close. The bundled client reconnects and re-asks for everything, getting whole books and the whole instrument list again.
uWS's own closeOnBackpressureLimit is not used, because it shuts only the read side and what was
sent in the meantime would reach the client past the gap.
On engine shutdown every client gets a close frame with code 1001 and server shutting down.
Ladder holds¶
A ladder shows an instrument by subscribing to its level2 channel. The server then makes sure
something streams that instrument's book and trades. Instruments a strategy already streams cost
nothing extra. For the others, the instruments MANUAL lists, the web server asks MANUAL to hold them
at their broker, and lets go after the last ladder is gone. The strategy side is MANUAL's
hold() and release(), driven by LADDER_SUBSCRIPTION events from the web server. See
Market data.
sequenceDiagram
autonumber
participant B as Browser
participant W as WebServer<br/>(uWS thread)
participant S as StrategyManager<br/>(worker thread)
participant M as Broker MD worker
B->>W: subscribe level2 ZNZ6
Note over W: first watcher, nothing held yet
W->>S: LADDER_SUBSCRIPTION subscribe, feeds
S->>M: subscribe book and trades
W-->>B: subscribed, then snapshot (and last trade)
M->>W: LEVEL2_UPDATE, TRADE via the bus
W-->>B: level2, trade
B->>W: unsubscribe, or the socket closes
Note over W: last watcher gone, release in 5 s
W->>S: LADDER_SUBSCRIPTION release
S->>M: unsubscribe
The rules:
- The hold is by instrument, not by client. The first watcher asks for it. Later ones, and the first one leaving, ask for nothing.
- Which feeds are held depends on what strategies already stream at that broker.
LEVEL2orORDER_BOOKmakes the ladder skip the book,TRADEmakes it skip the trades, and nothing is held when both are covered. A strategy that only subscribesQUOTEcovers neither. The hold's release therefore never drops a strategy's feed. - An instrument MANUAL does not list, and one no strategy subscribed, is only watched: the client reads whatever happens to stream, and nothing is held.
- When the last watcher goes, the release waits
web_server_ladder_release_ms(default 5000). A ladder that reloads or switches back inside that window finds the stream running, and nothing is asked of the broker. The release is retried on the next pass if the bus has no room. - On the next hold after a release the book is emptied if no event arrived since the release, so a subscriber starts from the snapshot the broker sends and not from the stale book. A connector that streamed on regardless keeps its current book.
The bundled client¶
websocket.js
and connection.js
make one socket per window, ws:// or wss:// to match the page.
- Reconnect. It retries forever. The delay is
min(1000 * 1.5^n, 30000)ms for attemptn, counted from 1: 1.5 s, 2.25 s, 3.4 s, 5.1 s, 7.6 s, 11.4 s, 17.1 s, 25.6 s, then 30 s. A successful open resetsn. - Ping.
{"type":"ping"}every 30 s while open. Nothing checks for thepong. - After every connect. The window re-sends its
instrumentssubscription, a ladder re-subscribes itslevel2, and each view reloads its REST snapshot (orders, fills, positions, brokers, health). Windows that depend on pushes stay correct across a gap because of this.welcomealso clears the cached Sim state, since the engine that answered may not be in Sim. - Events. The client emits each message by its
type, plusconnected,disconnected,reconnectinganderrorfor the socket.
Worked example¶
With websocat, type each line as you go:
{"type":"welcome","message":"Connected to SlickTrader"}
{"type":"subscribe","channel":"level2","instrument":"BTC-USD"}
{"type":"subscribed","channel":"level2","instrument":"BTC-USD"}
{"type":"level2","instrument":"BTC-USD","timestamp":1764547200123,"seq_num":1,"is_snapshot":true,"levels":[[64000.0,1.2,0],[64000.5,0.8,1]]}
{"type":"trade","instrument":"BTC-USD","price":64000.5,"qty":0.1,"side":0}
In the page, or Node 22 and later, a small client that keeps a book, with the same backoff idea:
const book = { bids: new Map(), asks: new Map() };
let ws;
let pinger;
function connect() {
ws = new WebSocket('ws://localhost:3000/');
ws.onopen = () => {
ws.send(JSON.stringify({ type: 'subscribe', channel: 'level2', instrument: 'BTC-USD' }));
pinger = setInterval(() => ws.send('{"type":"ping"}'), 30000);
};
ws.onmessage = ({ data }) => {
const m = JSON.parse(data);
if (m.type === 'level2') {
if (m.is_snapshot) { book.bids.clear(); book.asks.clear(); }
for (const [price, qty, side] of m.levels) {
const half = side === 0 ? book.bids : book.asks;
qty === 0 ? half.delete(price) : half.set(price, qty);
}
} else if (m.type === 'order_update' && m.event === 'fill') {
console.log('fill', m.strategy_id, m.instrument, m.fill_qty, '@', m.fill_price, 'seq', m.seq);
}
};
ws.onclose = () => {
clearInterval(pinger);
setTimeout(connect, 2000); // the server closes a lagging client, so come back whole
};
}
connect();
Place the order over REST and watch it here:
curl -X POST http://localhost:3000/api/orders -H "Content-Type: application/json" \
-d '{"instrument":"BTC-USD","broker_id":1,"side":"buy","type":"limit","price":50000,"quantity":0.001}'
The socket then shows an ack with PENDING_NEW, another with ACKNOWLEDGED, and, if it trades, a
fill.
Related¶
- REST API for placing, cancelling and reading state.
- Web dashboard for what each window does with these messages.
- Simulator for
sim_statusandsim_replay.