Market data¶
Market data takes two paths. Strategies state what they want through get_subscriptions(), and StrategyManager turns that into reference-counted requests for each broker's market data connector. The connectors publish trades, quotes and book updates onto the event bus. The worker thread builds the books strategies see. The web server builds a separate set of level 2 books for the dashboard from the same stream.
Subscription model¶
A subscription is a SubscriptionRequest: a broker, a SubscriptionType, a list of instruments, and a depth hint (default 10).
| Type | What it asks for | Events it produces |
|---|---|---|
TRADE |
Trade prints | TRADE |
QUOTE |
Best bid and ask from the venue's quote channel | QUOTE |
LEVEL2 |
Price levels | LEVEL2_UPDATE |
ORDER_BOOK |
Price levels, handled the same as LEVEL2 by the engine |
LEVEL2_UPDATE |
MBO |
Every resting order, for venues that publish it | MBO_UPDATE |
Neither in-tree broker has a market-by-order feed. Both log a warning and ignore an MBO subscription.
StrategyManager reads each strategy's get_subscriptions() once, in start(), before its worker thread exists. A strategy cannot add subscriptions later, and a parameter change does not re-subscribe. MANUAL is the exception: it subscribes while a dashboard ladder holds an instrument (see Ladder holds).
Holders are counted per (broker, type, instrument). Only the first holder triggers a SUBSCRIBE to the broker, and only the last one letting go triggers an UNSUBSCRIBE. Trades and the book of one instrument are separate keys. The same name at two brokers is two keys.
Coinbase serves LEVEL2 and ORDER_BOOK on one channel
The engine counts them separately, but Coinbase's connector subscribes both to its level2 channel and unsubscribes both from it. One holder letting go of an instrument's ORDER_BOOK while another holds its LEVEL2 drops the channel for both. Use one of the two types per instrument on Coinbase.
Instruments are matched by name. The L2 and MBO books, the web server's streams and PnLCalculator marks are all keyed by the instrument string alone. Two brokers that publish the same instrument name share one book.
Request queues, outbox and stalls¶
Each broker has its own request queue (md_request_queue_size, default 1 MiB), written only by StrategyManager and read only by that broker's market data connector. The queue is a lossy ring: a record written a ring's length past the connector's read position overwrites one it has not read. The manager prevents that itself.
- A request carries at most
(queue size / 4 - header) / 32instrument names (32 bytes each), and a queue too small for one gets requests of one. Larger lists are split into several records. - A record goes straight into the queue only if nothing waits ahead of it and the queue has room for twice its size ahead of where the connector reads. Otherwise it is appended to that broker's in-memory outbox, which has no size limit. The worker retries the outbox at most once per millisecond while any is non-empty, oldest first.
- After each request a connector handles (
process_md_request), it publishes its read position inBrokerStatusRegistry. Until it has read one, the manager treats it as having read nothing since the manager was made. - A broker whose market data connector is disabled is not waited on, since a disabled connector may drop what it reads. Hyperliquid's drops requests when disabled. A broker that was not built into this engine gets no request at all, with a warning.
- If a connector with a waiting outbox reads nothing for
md_request_stall_timeout_ms(default 5000, understrategies), the manager logs one warning with the count it holds, keeps waiting, and logs again when the connector reads again. One broker's stall never holds up another's requests. stop()waits for outboxes to empty. It gives up only on a connector already reported stalled, and drops its requests with a warning.
Hyperliquid's connector skips an instrument it does not know and logs skip subscription of an invalid coin.
Subscribe and unsubscribe are not symmetric at every connector
Hyperliquid's unsubscribe removes the instrument from the connector's own lists but does not cancel the WebSocket subscription, so the stream keeps arriving until the connection is rebuilt. Level2Streams handles that case: a book whose events kept coming after its release is treated as current.
Event types¶
| Event | Content | Handled by |
|---|---|---|
TradeEvent |
Price, quantity, aggressor side, is_buyer_maker, trade id |
dispatch_trade: sets the instrument's mark, then on_trade on every strategy |
QuoteEvent |
Best bid and ask with sizes | dispatch_quote: sets bid and ask marks when both are valid, then on_quote on every strategy |
Level2UpdateEvent |
A list of price levels (price, quantity, side), a sequence number, is_snapshot |
dispatch_level2_updates into the worker's L2 book, if a strategy subscribed one. The web server applies every one. |
MboUpdateEvent |
A list of order changes (order id, priority, price, quantity, side, ADD/MODIFY/REMOVE), is_snapshot, is_last |
dispatch_mbo_update into the worker's MBO book |
InstrumentDefinitionEvent |
Tick size, contract multiplier, min and max quantity, quantity step, currency | dispatch_instrument_definition |
InstrumentStatusEvent |
UNKNOWN, PRE_OPEN, OPEN, HALTED or CLOSED, cancel_allowed, a reason |
Logged, then on_instrument_status on every strategy. Nothing else reacts. |
A quantity of 0 in a level update removes the level. An adapter built on MdEventWriter splits a large snapshot into records of at most 1,024 levels (640 orders for MBO). Only the first record carries is_snapshot, and it clears the book. Such an adapter publishes an empty snapshot too, because that is what clears a subscriber.
Every strategy receives every trade, quote, book and status event the engine sees, not only those of its own subscriptions. Check event.instrument in the callback.
InstrumentDefinitionEvent is published by connectors when they start, ahead of their worker thread. For each one StrategyManager sets the instrument's contract multiplier in PositionTracker, which revalues held positions and applies to later fills. An invalid multiplier (not finite, or not positive) is refused and logged. It then calls on_instrument_definition on every strategy and remembers the tick and minimum quantity so MANUAL can list the instrument. Coinbase publishes a definition per tradable product with a multiplier of 1. In-tree connectors publish no InstrumentStatusEvent.
Books¶
Strategy books on the worker thread¶
StrategyManager keeps, per instrument, at most one OrderBookL2 (from the slick-orderbook library) for strategies that subscribed LEVEL2 or ORDER_BOOK, and at most one OrderBookL3 for MBO. They are built in start(), before the worker reads the bus, so each takes in its broker's snapshot. Only the worker thread touches them, so read a book only from a strategy callback.
For an L2 book the manager applies each level with the event's sequence number and event_time_ns. The library drops a level whose sequence number is below the highest the book has seen, and a snapshot's clear() does not reset that number.
Two callbacks come out of it:
on_order_book(instrument, book)runs for every price level the book reports changed. An event of ten levels calls it up to ten times, and each call sees the levels applied so far.- Top of book. When the top changes at the end of an update, the manager builds a
QuoteEventand callson_quoteon every strategy. A side with no quantity has its price set toNULL_PRICE, because the book reports an empty side as price 0, which is a real futures spread price. The same top is published on the bus as aTOBrecord for the web server.
An MBO update is applied order by order (ADD and MODIFY add or modify, REMOVE deletes) with no sequence check, since the broker already ordered the feed. Strategies are called only when is_last is set, which is the end of the exchange event, so they never see a half-built book. on_order_book_l3(instrument, book) runs for every strategy. If an MBO book exists for an instrument and no L2 book does, its top of book feeds quotes and TOB exactly as an L2 book would. Once an L2 book exists, it is the quote source and the MBO book stops publishing a top.
An MBO book is sized for a liquid futures book up front: 16,384 orders and 256 levels, with a 10-level top.
Book ids are 16 bits
Each book takes a 16-bit symbol id. Once all 65,536 are used, a new instrument gets no L2 book and an error is logged. An MBO book then labels itself with id 0 and still works.
Queue position¶
For brokers that publish MBO, queue_position(book, order_id) and StrategyBase::get_queue_position(book, client_order_id) return where a working order sits at its price:
| Field | Meaning |
|---|---|
orders_ahead, quantity_ahead |
Orders at the same price that trade first, and their displayed size |
quantity |
The order's own displayed size |
level_quantity, level_orders |
Everything displayed at the price, this order included |
level_index |
0 for the best price on its side |
price, side |
The order's |
It returns nothing when the book does not hold the order (not yet on the feed, filled, cancelled) or when the broker order id is not a number. Cost is one hop per order ahead. In this tree nothing publishes MBO, so only out-of-tree adapters can exercise it.
The web server's level 2 books¶
The dashboard gets books from a second, separate structure. Level2Streams applies every LEVEL2_UPDATE on the bus, whichever strategy or ladder asked for the instrument, to a Level2Book that keeps every level. A browser that subscribes late starts from that book as a snapshot. Streams that have received an event are kept for the life of the process, watched or not. One that was only asked for is dropped with its last watcher. A client can watch at most 1,024 instruments, and a name of 32 characters or more is refused.
A client that falls behind is closed and reconnects whole, rather than being sent a stream with a gap in it. If a book's broker has market data enabled but disconnected, a new subscriber gets an empty snapshot until the feed's next snapshot replaces the book.
Trades also reach Level2Streams, but only as the last trade of a stream that already exists, for the ladder's LTQ column. Trades never create a stream.
Ladder holds¶
A dashboard ladder needs an instrument's book and trades even when no strategy subscribed them. The web server and MANUAL handle that with a hold:
- The first browser to subscribe to
level2for an instrument thatMANUALlists askswatched(). It publishes aLadderSubscriptionEventon the bus (through its own producer) for each feed no strategy already streams. A feed counts as streamed when a strategy subscribed its book (LEVEL2orORDER_BOOK) or trades at that broker. - The worker receives it in
dispatch_ladder_subscription.ManualStrategy::hold()accepts it only if the instrument is listed at that broker (a broker defined it and theMANUALconfig takes it), or a strategy subscribes it there. Accepted feeds become ordinary subscriptions (LEVEL2for the book,TRADEfor the last trade), counted with every other holder, but with no strategy book kept. - When the last browser lets go, the hold is released after
web_server_ladder_release_ms(default 5000), so a reloaded page keeps its stream. The release goes out the same way and unsubscribes only whatMANUALheld. A strategy holding the same feed keeps it. Level2Streams::release()andrenew()track the book across the gap: if no event arrived while it was released, it is emptied on renew so a new subscriber starts from the broker's fresh snapshot.
An instrument that nobody lists is only watched, with no hold, so it shows data only if something else streams it. If the hold cannot be published, the browser gets a subscription_error. A release that cannot be published is kept and tried again on a later pass.
MANUAL lists what brokers define. Its instruments parameter narrows the list by name or PREFIX*. Without that parameter it lists everything, and with [] nothing. The list is capped at 65,536 instruments.
Marks and top of book¶
PnL needs a price per instrument, and PnLCalculator takes it from whichever event came last:
| Source | Bid mark | Ask mark |
|---|---|---|
TradeEvent price |
the price | the price |
| Order fill price | the price | the price |
QuoteEvent with both sides valid |
bid | ask |
| Top of an L2 or MBO book, both sides non-empty | best bid | best ask |
A trade or fill therefore overwrites both sides with one price until the next top of book that differs from the stored one. A one-sided top marks nothing. See Positions, PnL and risk for how a position uses them.
The web server pushes pnl_update when a TOB record arrives, at most every 250 ms. TOB is published only from books StrategyManager keeps, which are those strategies subscribed. An instrument held by a ladder alone has its trades for marks but never produces TOB.