Architecture¶
slick-trader is one process. Broker connectors publish market data and order events onto a shared lock-free bus. One worker thread reads that bus, keeps the order books and calls the strategies. A uWebSockets thread serves the REST API and the dashboard and reads the same bus on its own cursor. Orders and subscription requests travel the other way on queues of their own.
Component map¶
flowchart LR
subgraph brokers["Broker adapters (one per configured broker)"]
MD["Market data connector<br/>MD worker thread"]
OC["Order connector<br/>order worker thread"]
end
BUS[("event_mux_<br/>stream_buffer_multiplexer")]
MDQ[("md_request_queues_<br/>one per broker")]
OQ[("order_request_queue_<br/>shared, filtered per connector")]
CTL[("control_queue_<br/>startup only")]
subgraph sm["StrategyManager worker thread"]
DISP["dispatch<br/>L2 and MBO books"]
STRATS["strategies<br/>plugins and MANUAL"]
PT["PositionTracker<br/>PnLCalculator"]
end
RM["RiskManager"]
WEB["WebServer<br/>uWS thread"]
REG["BrokerStatusRegistry<br/>atomic flags"]
MD --> BUS
OC --> BUS
MD -.->|register| CTL
OC -.->|register| CTL
BUS --> DISP
BUS --> WEB
DISP -->|TOB records| BUS
WEB -->|config and ladder events| BUS
DISP --> STRATS
STRATS --> PT
STRATS --> RM
STRATS --> OQ
WEB -->|MANUAL orders| OQ
OQ --> OC
DISP -->|subscribe and unsubscribe| MDQ
MDQ --> MD
MD --> REG
OC --> REG
STRATS -.->|order check| REG
WEB -.->|reads| PT
| Component | What it does | Source |
|---|---|---|
TradingEngine |
Singleton that builds everything from the config, starts and stops it in a fixed order. | trading_engine.cpp |
BrokerRegistry |
Maps a config broker name (case-insensitive) to a factory. Adapters register themselves at static-init time with SLICK_TRADER_REGISTER_BROKER. An enabled broker with no adapter stops startup. |
broker_registry.hpp |
| Brokers and connectors | IBroker owns one market data connector and one order connector. Only coinbase and hyperliquid are built in. Others join through SLICK_TRADER_EXTERNAL_BROKERS at build time. |
brokers/ |
BrokerStatusRegistry |
Process-wide table of atomic flags per broker (MD and order, enabled and connected) plus the cursor each MD connector has read to. Strategies and the web server read it without locks. | broker_status.hpp |
StrategyManager |
Worker thread. Reads the bus, builds L2 and MBO books, dispatches to strategies, sends subscriptions, runs the 1 s loss-limit and broker-status checks. | strategy_manager.cpp |
StrategyBase, ManualStrategy |
The strategy interface and its base class. MANUAL is always registered and owns dashboard orders. |
strategy_base.hpp |
RiskManager |
Per-strategy limits and halt state. Pre-trade checks run inside submit_order. See Positions, PnL and risk. |
risk_manager.cpp |
PositionTracker, PnLCalculator |
FIFO positions per strategy and instrument, and marks and PnL over them. | position_tracker.cpp, pnl_calculator.cpp |
PositionStore |
Optional memory-mapped file that keeps positions across restarts. | position_store.cpp |
WebServer |
REST, WebSocket and static files on the uWS thread. | web_server.cpp |
Strategies are shared libraries loaded once at startup from strategy_plugins_folder. A plugin links the core statically, so it carries private copies of the logger and of BrokerStatusRegistry. StrategyLoader injects the host's instances before create_strategy() runs, and refuses a plugin whose STRATEGY_API_VERSION (currently 2) differs from the host's. There is no runtime reload of binaries. Parameters can change live through PUT /api/strategies/:id/config (see REST API).
Threading model¶
flowchart TB
subgraph T1["main thread"]
M["init, start, sleep 100 ms,<br/>shutdown on SIGINT or SIGTERM"]
end
subgraph T2["StrategyManager worker"]
S["event dispatch<br/>L2 and MBO books<br/>strategy callbacks<br/>positions and marks<br/>MD request outbox<br/>1 s loss and broker checks"]
end
subgraph T3["WebServer uWS thread"]
W["HTTP and WebSocket<br/>polls the bus itself<br/>Level2Streams<br/>tracked orders<br/>MANUAL order calls"]
end
subgraph T4["per broker: MD worker"]
D["reads its MD request queue<br/>publishes market data"]
end
subgraph T5["per broker: order worker"]
O["reads the shared order queue<br/>REST and WebSocket calls<br/>publishes acks and fills"]
end
T4 -->|event_mux_| T2
T5 -->|event_mux_| T2
T4 -->|event_mux_| T3
T5 -->|event_mux_| T3
T2 -->|md_request_queues_| T4
T2 -->|order_request_queue_| T5
T3 -->|order_request_queue_| T5
T3 -->|"event_mux_ (config, ladder holds)"| T2
| Thread | Callbacks and state it owns |
|---|---|
| main | Config parsing, plugin loading, and the start() and stop() order. Runs each strategy's on_initialize, first on_config, and its on_start at startup and on_stop at shutdown. (on_start and on_stop also run on the uWS thread for the control endpoint and on the worker for auto-pause and loss halts.) After engine.start() it only sleeps in 100 ms steps until a signal clears the run flag. |
| StrategyManager worker | Every market data and order callback (on_trade, on_quote, on_order_book, on_order_book_l3, on_order_ack, on_order_fill, on_order_reject, on_order_cancel, on_instrument_definition, on_instrument_status) and every on_config after startup. Owns the L2 and MBO books, the symbol ids, the subscription reference counts, the request outbox and the auto-pause sets. Books OrderFillEvents into PositionTracker and writes marks into PnLCalculator. |
| WebServer (uWS loop) | All HTTP and WebSocket handling. It re-defers process_events() onto its own loop, so it polls the bus itself. Owns Level2Streams, the tracked-order map, the fill history and the ladder holds. Registers one producer on the bus for strategy config updates and ladder subscription events. |
| MD worker, one per broker | Reads that broker's MD request queue and subscribes upstream. Writes market data and instrument definitions into the connector's producer buffer. |
| Order worker, one per broker | Reads the shared order queue, acts on requests addressed to its broker, and writes acks, fills, rejects and cancels into its producer buffer. |
A producer buffer is meant to have one writer thread. The bus fans several producers into one ordered stream. Consumers, which are the StrategyManager worker and the web server, each keep their own cursor and see every record.
Shared state is not locked
PositionTracker, PnLCalculator, RiskManager and a strategy's own order maps are plain unordered_maps with no mutex. The worker thread writes them. The uWS thread reads positions, PnL and risk limits for REST and WebSocket output. It also calls StrategyBase::submit_order, cancel_order and modify_order on MANUAL, calls start_strategy and stop_strategy for POST /api/strategies/:id/control, and calls halt_strategy, resume_strategy and set_limits for the risk endpoints. A strategy author should treat those calls as arriving from a second thread. The one structure built for cross-thread reads is ManualStrategy's instrument list, which is append-only behind an atomic count.
Queues¶
All of them are slick-queue or slick-stream-buffer rings. They are lossy: a writer never waits, and a reader that falls a full ring behind skips to newer data without an error. Backpressure exists only where the code adds it (the market data request path).
| Queue | Created by | Writers | Readers | If a reader falls behind |
|---|---|---|---|---|
event_mux_ |
TradingEngine |
Each connector's producer buffer (one writer thread each). StrategyManager's TOB producer. WebServer's config producer. | StrategyManager worker and WebServer thread, each with its own cursor. | Lossy. The reader skips lapped records. Nothing is reported to the strategies. |
control_queue_ |
TradingEngine |
Connectors in register_broker() (REGISTER), the engine (REGISTER_END). |
wait_for_brokers_ready() on the main thread. |
Startup only, nothing laps it. |
md_request_queues_ (per broker) |
TradingEngine, one queue per broker |
StrategyManager only: main thread in start() and stop(), worker in between. |
That broker's MD connector. | Lossy ring, but the writer holds requests back in an in-memory outbox until the connector's reported cursor leaves room. See Market data. |
order_request_queue_ |
TradingEngine |
Any thread that calls a strategy's submit_order, modify_order or cancel_order: the worker, the main thread during stop(), the uWS thread for MANUAL. The queue accepts many writers. |
Every order connector, each with its own cursor, each skipping requests addressed to other brokers. | Lossy, no backpressure. A connector lapped by a full ring loses requests silently, and the strategy's order stays PENDING_NEW with no timeout. |
Sizes come from the top-level config. event_queue_size is a count of 16-byte records and defaults to 16,777,216. control_queue_size, md_request_queue_size (per broker), and order_request_queue_size are byte counts and default to 1 MiB, 1 MiB and 16 MiB. Each connector sizes its own producer buffer from queue_size and control_size in its config block, TOB_queue_size and TOB_control_size size the top-of-book producer, and config_queue_size and config_control_size size the web server's. Every queue accepts an optional shared-memory name. See Configuration for the full key list.
Events and wire types¶
Every record on the bus starts with a 50-byte packed Event header: type, timestamp_ns, event_time_ns, broker_id and a 32-byte instrument. Events are trivially copyable structs. Variable-length ones (Level2UpdateEvent, MboUpdateEvent, MDSubscription, StrategyConfigEvent) end in a flexible array and are published with their real size.
| Record | Travels on | Producer | Consumer |
|---|---|---|---|
TRADE, QUOTE, LEVEL2_UPDATE, MBO_UPDATE, INSTRUMENT_DEFINITION, INSTRUMENT_STATUS |
event_mux_ |
MD connectors | StrategyManager, WebServer (trades, L2 and TOB only) |
ORDER_ACK, ORDER_FILL, ORDER_REJECT, ORDER_CANCEL |
event_mux_ |
Order connectors | StrategyManager, WebServer |
TOB |
event_mux_ |
StrategyManager | WebServer. StrategyManager ignores its own. |
STRATEGY_CONFIG, LADDER_SUBSCRIPTION |
event_mux_ |
WebServer | StrategyManager |
NEW_ORDER, MODIFY_ORDER, CANCEL_ORDER |
order_request_queue_ |
Strategies | Order connectors |
SUBSCRIBE, UNSUBSCRIBE |
md_request_queues_ |
StrategyManager | MD connectors |
REGISTER, REGISTER_END |
control_queue_ |
Connectors, engine | Engine |
CANDLE, POSITION_UPDATE, PNL_UPDATE and STATUS exist in the enum and nothing publishes them. ORDER_BOOK is handled by StrategyManager, but no in-tree connector publishes it (Coinbase's publish_order_book is never called).
Prices and quantities are fixed point: price_t and qty_t are int64_t scaled by 1e8. NULL_PRICE is INT64_MAX. to_price_t(NaN) and any value outside about plus or minus 9.2e10 return NULL_PRICE, and from_price_t(NULL_PRICE) returns NaN. Prices can be zero or negative (calendar spreads trade through zero). Position and PnL arithmetic converts to double, multiplies, and converts back, so results are rounded to 1e-8.
timestamp_ns is std::chrono::steady_clock nanoseconds, a monotonic clock with an arbitrary epoch. It is not wall time. event_time_ns is the venue's time where the connector has one. Position last_update_time is also steady-clock time, so it is meaningless across a machine reboot.
Instrument names are cut at 31 characters
Event::instrument holds 31 characters plus a NUL. set_instrument truncates silently, the 32-byte slot in an MDSubscription does the same, and Level2Streams refuses a longer name for a WebSocket subscription. Two instruments that share their first 31 characters become one.
Other fixed-size fields, as characters without the NUL: client_order_id and order_id 63, reject and cancel reason 127, instrument status reason 31, currency 7, strategy name in a config event 63, strategy config text 64 KiB. PositionStore keys (strategy id and instrument) are 63. StrategyBase::generate_order_id() produces <name>_<steady-clock ns>, so a strategy name much past 40 characters gets a cut-off id.
Startup order¶
TradingEngine::initialize() runs on the main thread:
- Open the config, set up the logger, read
environment. InSimit also requiressim_control_addrandsim_control_port. - Open the
PositionStoreifposition_storeis configured, and restore positions from it. A store that cannot be opened stops startup. - Create
event_mux_,control_queue_,md_request_queues_andorder_request_queue_. - For each enabled broker in
brokers: look up the adapter, make its MD request queue, construct it (each connector adds its producer to the bus here), callregister_broker(). Then publishREGISTER_END. - Construct
StrategyManager(adds the TOB producer), thenload_strategies()ifstrategies.enabledis not false. That loads plugins, callsinitialize()on each, sets risk limits, and registersMANUAL. - Construct and
initialize()theWebServerifweb_serviceis present and enabled (adds the config producer). wait_for_brokers_ready(), bounded bywaiting_time_out(default 30 s).
Then start(), still on the main thread: brokers start (connectors connect and their workers begin), then StrategyManager::start() (each strategy's on_start, its initial subscriptions, the worker thread), then the web server thread. main() installs its SIGINT and SIGTERM handlers after start() returns and then sleeps.
A config with no strategies section cannot have a web server
web_service is constructed with a reference to the StrategyManager, which is created only when strategies is present. Without it, *strategy_manager_ dereferences a null pointer. Without strategies.enabled, the manager exists but MANUAL is never registered, so POST /api/orders answers 404 "Strategy not found".
The wait for brokers returns after one record
The loop in wait_for_brokers_ready() ends with while (!(timed_out = now < end)). The assignment is true while time remains, so the condition is false on the first pass and the body runs once. It handles whatever record is first on control_queue_, attaches an out-of-process producer only if that record names one, and returns. In-process brokers need no attach. waiting_time_out has no effect. With no brokers key the queue is empty and the first read is a null dereference.
Shutdown order¶
TradingEngine::shutdown() runs only if start() completed. main() calls it after the signal handler clears the run flag.
begin_stop()on every broker. The in-tree brokers do nothing here.StrategyManager::stop(): clear the run flag, join the worker, then for each strategy unsubscribe its subscriptions and call itsstop()(which usually cancels its orders).MANUALreleases its ladder holds. Pending MD requests are drained. A connector that has read nothing formd_request_stall_timeout_msis given up on and its requests dropped with a warning.stop()on every broker: MD and order connectors disconnect and join their workers.WebServer::stop(): closes the listen socket and every WebSocket on the uWS loop, then joins.
The dashboard therefore stays up until the end, but with no worker thread nothing updates it.
Stop does not guarantee cancels, and on_shutdown never runs
Cancels a strategy sends from on_stop() go onto order_request_queue_, and step 3 stops the order connectors right after. The in-tree connectors have no wait-for-confirm step, so whether a cancel is read before the worker exits is a race. The kill-switch helper in brokers/common/kill_switch.hpp exists for out-of-tree adapters. Also, StrategyManager::shutdown(), the only caller of each strategy's on_shutdown(), is never called by the engine.
State on disk¶
| Path | Written by | What | Config |
|---|---|---|---|
logs/slick_trader.log |
Logger | Log file. A console sink exists only in debug builds. | log_file_path, log_level |
state/positions.dat |
PositionStore |
Positions and open lots. See Positions, PnL and risk. Absent unless configured. | position_store.path |
state/workspaces.json |
WorkspaceStore |
The dashboard's saved window layouts. | web_server_workspaces_file |
<name>.config.json |
WebServer |
Rewritten on PUT /api/strategies/:id/config: only the parameters block, found by the name inside the file. Falls back to an inline strategies array in the main config. |
strategy_configs_folder |
| Fill journals and slot stores | Broker helpers in brokers/common/ |
Used by out-of-tree adapters that journal fills. Neither in-tree broker uses them. | per broker |
Order state is not on disk. After a restart, strategies start with empty order maps. A fill or ack that arrives for an order the strategy does not track is adopted when its client_order_id carries the strategy's prefix. See Order lifecycle.
Operating environments¶
The top-level environment string labels the session. Empty, Production or Prod in any case is production. Anything else, a misspelling included, makes the dashboard show its non-production bar. Sim means the venues are slick-sim's: the engine keeps a control link to slick-sim's CLI port, retried every 5 s, and the dashboard shows Live Sim or Historical Sim from the feeds slick-sim reports. Nothing else in the engine branches on the environment. The broker blocks in the config decide where orders go.