Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
web_server.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <slick/queue.hpp>
4#include <uwebsockets/App.h>
14#include <slick/stream_buffer_multiplexer.hpp>
15#include <atomic>
16#include <array>
17#include <thread>
18#include <string>
19#include <string_view>
20#include <memory>
21#include <mutex>
22#include <unordered_map>
23#include <unordered_set>
24#include <nlohmann/json.hpp>
25
26namespace slick::trader {
27
28// Forward declarations
29class StrategyManager;
30class PositionTracker;
31class PnLCalculator;
32class RiskManager;
33struct OrderAckEvent;
34struct OrderFillEvent;
35struct OrderCancelEvent;
36struct OrderRejectEvent;
37
38using json = nlohmann::json;
39
40// Web server for monitoring and control
41// Provides REST API and WebSocket streaming
42// Runs on dedicated thread using uWebSockets
43class WebServer {
44public:
45 struct Config {
46 std::string host{"0.0.0.0"};
47 uint16_t port{8080};
48 std::string static_files_path{"./web/static"};
49 bool enable_cors{true};
50 // How long an instrument of MANUAL's stays held once no ladder shows it, so a page
51 // reloaded or switched back keeps its stream. web_server_ladder_release_ms.
52 uint64_t ladder_release_ns{5'000'000'000};
53 };
54
56 std::string_view config_path,
57 StrategyManager& strategy_manager,
58 PositionTracker& position_tracker,
59 PnLCalculator& pnl_calculator,
60 RiskManager& risk_manager,
61 slick::stream_buffer_multiplexer& mux)
62 : strategy_manager_(strategy_manager)
63 , position_tracker_(position_tracker)
64 , pnl_calculator_(pnl_calculator)
65 , risk_manager_(risk_manager)
66 , event_mux_(mux)
67 , event_cursor_(event_mux_.initial_reading_index())
68 , config_path_(config_path)
69 {}
70
72 stop();
73 }
74
75 // Initialize with configuration. `environment` is the config's top-level one, for /api/health,
76 // and `sim_control` where slick-sim's CLI port is, in Sim.
77 bool initialize(const json& config, std::string_view environment = PRODUCTION_ENVIRONMENT,
78 const SimControlConfig& sim_control = {});
79
80 // Start web server thread. start() and stop() are for one controlling thread.
81 void start();
82
83 // Stop web server and join its thread
84 void stop();
85
86 // Check if running
87 bool is_running() const {
88 return running_.load(std::memory_order_acquire);
89 }
90
91 // Get current port
92 uint16_t get_port() const { return config_.port; }
93
94private:
95 void run();
96 // Closes the listen socket and every connection so the event loop can exit.
97 // Event loop thread only. stop() defers it there.
98 void close_connections();
99
100 // REST API handlers
101 void setup_routes(uWS::App &app);
102 void handle_get_strategies(uWS::HttpResponse<false>* res, uWS::HttpRequest* req);
103 void handle_get_positions(uWS::HttpResponse<false>* res, uWS::HttpRequest* req);
104 void handle_get_pnl(uWS::HttpResponse<false>* res, uWS::HttpRequest* req);
105 void handle_get_strategy_positions(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
106 const std::string& strategy_id);
107 void handle_get_strategy_pnl(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
108 const std::string& strategy_id);
109 void handle_post_order(uWS::HttpResponse<false>* res, uWS::HttpRequest* req, std::string_view body);
110 void handle_post_strategy_control(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
111 const std::string& strategy_id, std::string_view body);
112 void handle_get_risk_limits(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
113 const std::string& strategy_id);
114 void handle_put_risk_limits(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
115 const std::string& strategy_id, std::string_view body);
116 void handle_get_strategy_config(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
117 const std::string& strategy_id);
118 void handle_put_strategy_config(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
119 const std::string& strategy_id, std::string_view body);
120 void handle_post_halt_strategy(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
121 const std::string& strategy_id, std::string_view body);
122 void handle_post_resume_strategy(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
123 const std::string& strategy_id);
124 void handle_get_brokers(uWS::HttpResponse<false>* res, uWS::HttpRequest* req);
125 void handle_get_ladder_config(uWS::HttpResponse<false>* res, uWS::HttpRequest* req);
126 void handle_put_ladder_config(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
127 const std::string& body);
128 void handle_get_orders(uWS::HttpResponse<false>* res, uWS::HttpRequest* req);
129 void handle_get_fills(uWS::HttpResponse<false>* res, uWS::HttpRequest* req);
130 void handle_delete_order(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
131 const std::string& strategy_id, const std::string& order_id,
132 std::string_view body);
133 void handle_put_order(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
134 const std::string& strategy_id, const std::string& order_id,
135 std::string_view body);
136 void handle_delete_all_orders(uWS::HttpResponse<false>* res, uWS::HttpRequest* req);
137 // PUT /api/workspaces {name, windows}, DELETE /api/workspaces {name}, PUT /api/workspaces/last {name}.
138 enum class WorkspaceChange { SAVE, REMOVE, USE };
139 void handle_workspace_change(uWS::HttpResponse<false>* res, std::string_view body, WorkspaceChange change);
140 void handle_post_sim_replay(uWS::HttpResponse<false>* res);
141
142 // Hand a parameter update to the StrategyManager worker over the event bus.
143 // Returns false when the update could not be published at all.
144 bool publish_strategy_config(const std::string& strategy_id, const nlohmann::json& params);
145
146 // Persist updated strategy parameters to whichever file the strategy loader reads
147 void save_strategy_parameters(const std::string& strategy_id, const nlohmann::json& params);
148
149 // Writes `parameters` into <configs_folder>/*.config.json for the file whose "name"
150 // is strategy_id. Returns false when no such file exists.
151 bool save_to_strategy_config_file(const std::string& configs_folder,
152 const std::string& strategy_id,
153 const nlohmann::json& params);
154
155 // WebSocket handlers
156 void handle_ws_open(uWS::WebSocket<false, true, void*>* ws);
157 void handle_ws_message(uWS::WebSocket<false, true, void*>* ws, std::string_view message);
158 void handle_ws_close(uWS::WebSocket<false, true, void*>* ws);
159
160 using Socket = uWS::WebSocket<false, true, void*>;
161 // Sends `message` as text. One uWS drops, its client too far behind, leaves that client's
162 // ladder or lists short of it for good: close_lagging() closes it, and it reconnects whole.
163 // Not uWS's closeOnBackpressureLimit: that only shuts the read side, so the close waits on
164 // the client sending again, and what is sent meanwhile reaches it past the gap.
165 void send_text(Socket* ws, std::string_view message);
166 void close_lagging();
167
168 // What uWS holds for a client before it drops a send. Over the largest message: the list a
169 // dashboard gets on connect runs to megabytes with MANUAL on "*", and the 64 KB default
170 // dropped the next message to any client still reading it, at every reconnect too.
171 static constexpr unsigned int WS_MAX_BACKPRESSURE = 16u << 20;
172
173 // Helper methods
174 void send_json_response(uWS::HttpResponse<false>* res, const std::string& json, int status = 200);
175 void send_error_response(uWS::HttpResponse<false>* res, const std::string& error, int status = 400);
176 void add_cors_headers(uWS::HttpResponse<false>* res);
177
178 // Market data streaming
179 void process_events();
180
181 void handle_order_ack(const OrderAckEvent& ack);
182 void handle_order_fill(const OrderFillEvent& fill);
183 void handle_order_cancel(const OrderCancelEvent& cancel);
184 void handle_order_reject(const OrderRejectEvent& reject);
185
186 void broadcast_level2_update(const Level2UpdateEvent& event);
187 // A trade to the ladders watching its instrument, for their LTQ column.
188 void broadcast_trade(const TradeEvent& event);
189 // To every client.
190 void broadcast(std::string_view message);
191 // Keeps a fill in fills_ and sends it to every client.
192 void broadcast_fill(json& message);
193
194 // The ladder's instruments. index_listings() takes what MANUAL listed since it last looked
195 // into listings_, and what is new into listings_added_; send_instruments() writes them all
196 // to a client that asked, send_instruments_added() what is new to every one that did.
197 void index_listings();
198 void send_instruments(Socket* ws);
199 void send_instruments_added(uint64_t now_ns);
200
201 // A ladder shows `instrument` and nobody else did (watched), or the last one let go
202 // (unwatched). One of MANUAL's is held at its broker while watched, and released
203 // ladder_release_ns after it is not, by release_holds(). False when a hold was needed and
204 // could not be asked for.
205 bool watched(std::string_view instrument);
206 void unwatched(std::string_view instrument);
207 void release_holds(uint64_t now_ns);
208 // A hold covers `feeds` (LadderFeed bits). A release frees whatever MANUAL held.
209 bool publish_ladder_subscription(BrokerId broker, std::string_view instrument, bool subscribe,
210 uint8_t feeds = LADDER_ALL);
211
212 // PnL broadcasting
213 void broadcast_pnl_update();
214
215 // Broker status broadcasting
216 void check_and_broadcast_broker_status();
217
218 // The link to slick-sim, in Sim: keeps it up, and sends what changed to every client.
219 void service_sim(uint64_t now_ns);
220 // The config's environment, or what slick-sim's feeds make a Sim.
221 std::string_view environment() const;
222 // /api/sim's body, with "type" when given one, as a WebSocket message has.
223 std::string sim_json(std::string_view type = {}) const;
224 void make_health_json();
225
226 StrategyManager& strategy_manager_;
227 PositionTracker& position_tracker_;
228 PnLCalculator& pnl_calculator_;
229 RiskManager& risk_manager_;
230
231 Config config_;
232 std::atomic_bool running_{false};
233 std::thread worker_thread_;
234 // The running app, for close_connections(). Touched only on the worker's event loop thread.
235 uWS::App* app_{nullptr};
236 // The worker's event loop, for stop() to hand the shutdown to. uWS may only be used from
237 // the thread running the loop. Loop::defer is the one call that is safe from another.
238 // The loop is thread local and is freed when the worker thread exits, so the pointer can
239 // only be used while loop_mutex_ is held. stop() holds the lock across defer(), and the
240 // worker takes it to clear loop_ before it exits, so the loop can't be freed in the middle
241 // of a defer().
242 std::mutex loop_mutex_;
243 uWS::Loop* loop_{nullptr};
244
245 slick::stream_buffer_multiplexer& event_mux_;
246 uint64_t event_cursor_{0};
247
248 // PnL goes to the dashboard when a top of book moved, at most this often. Touched only
249 // by the uWS event loop thread.
250 static constexpr uint64_t PNL_BROADCAST_INTERVAL_NS = 250'000'000;
251 bool pnl_changed_{false};
252 uint64_t last_pnl_broadcast_ns_{0};
253
254 // Every instrument a ladder can show: each strategy's, then each MANUAL lists, the first
255 // broker named winning, with its tick, 0 when unknown. listings_indexed_ is how many of
256 // MANUAL's are in. A dashboard asking gets them all, then what is new at most this often.
257 struct Listing {
258 BrokerId broker;
259 price_t tick_size;
260 // A strategy streams its book at `broker` (LEVEL2 or ORDER_BOOK), so it is never held for
261 // a ladder. One a strategy only quotes or trades streams no book: it is held.
262 bool book;
263 qty_t min_qty{0}; // smallest order, 0 when its broker did not say
264 bool trades{false}; // a strategy streams its trades at `broker`: a ladder's hold leaves them out
265 };
266 static constexpr uint64_t INSTRUMENTS_ADDED_INTERVAL_NS = 250'000'000;
267 StringMap<Listing> listings_;
268 uint32_t listings_indexed_{0};
269 // Keys of listings_, which a map keeps in place, new or given a tick since last sent.
270 std::vector<const std::string*> listings_added_;
271 uint64_t last_instruments_sent_ns_{0};
272 std::string instruments_message_; // one buffer, its capacity kept from one to the next
273 // The clients that asked for the list.
274 std::unordered_set<uWS::WebSocket<false, true, void*>*> instrument_clients_;
275
276 // MANUAL's instruments ladders hold: release_at_ns is 0 while one shows it, else when it
277 // goes. `releasing_` counts those with a deadline.
278 struct LadderHold {
279 BrokerId broker;
280 uint64_t release_at_ns;
281 };
282 StringMap<LadderHold> ladder_holds_;
283 size_t releasing_{0};
284
285 // How long one process_events() pass may read the bus before the loop gets its sockets back.
286 static constexpr uint64_t PROCESS_EVENTS_BUDGET_NS = 1'000'000;
287
288 // Each level2 message is written here: one buffer, its capacity kept from one to the next.
289 std::string level2_message_;
290 std::string trade_message_; // same for each trade message
291
292 // Producer side of the same bus: strategy parameter updates are published here from the
293 // uWS event loop thread and applied by the StrategyManager worker, so a strategy's
294 // on_config() runs on the thread that owns its state. Registered in initialize(), which
295 // is before any producer or consumer thread starts — add_producer() is setup-only.
296 std::shared_ptr<slick::stream_buffer_multiplexer::producer_buffer> config_producer_buffer_;
297
298 // // Market data queue (shared with StrategyManager)
299 // std::shared_ptr<slick::SlickQueue<uint8_t>> md_queue_;
300 // uint64_t ws_md_cursor_{0}; // Independent cursor for WebServer
301
302 // // Order event queue (shared with StrategyManager)
303 // std::shared_ptr<slick::SlickQueue<uint8_t>> order_event_queue_;
304 // uint64_t ws_order_cursor_{0}; // Independent cursor for WebServer
305
306 // // Top-of-book queue (written by StrategyManager)
307 // std::shared_ptr<slick::SlickQueue<uint8_t>> tob_queue_;
308 // uint64_t ws_tob_cursor_{0};
309
310 // All connected WebSocket clients (for broadcasting order updates)
311 std::unordered_set<uWS::WebSocket<false, true, void*>*> all_ws_clients_;
312
313 // Clients a send was dropped for, closed at the end of the process_events() pass.
314 std::unordered_set<Socket*> lagging_;
315
316 // The level 2 book of every instrument streamed, any strategy's or MANUAL's, and the
317 // browsers watching each.
318 Level2Streams<Socket> level2_streams_;
319
320 // Ladder configuration
321 nlohmann::json ladder_config_;
322
323 // /api/health's body: version and environment. Made in initialize(), and again when environment() changes.
324 std::string health_json_;
325 std::string environment_; // the config's
326
327 // The link to slick-sim's CLI port, in Sim alone. The event loop thread's once started.
328 std::unique_ptr<SimControlLink> sim_;
329
330 // The dashboard's saved window layouts, in web_server_workspaces_file.
331 WorkspaceStore workspaces_;
332
333 // Path to config.json — used to persist runtime strategy parameter changes
334 std::string config_path_;
335
336 // WebServer-side order tracking — accessed ONLY from the uWS event loop thread (no mutex needed)
337 struct TrackedOrder {
338 std::string strategy_id;
339 std::string client_order_id;
340 std::string order_id; // broker-assigned; may be empty until ACK
341 std::string instrument;
342 std::string side; // "buy" / "sell"
343 int type{0};
344 double price{0.0};
345 double qty{0.0};
346 double filled_qty{0.0};
347 double remaining_qty{0.0};
348 std::string status{"PENDING_NEW"};
349 uint64_t created_time{0};
350 uint64_t last_update_time{0};
351 };
352
353 // Keyed by client_order_id
354 std::unordered_map<std::string, TrackedOrder> open_orders_;
355 // The last fills sent, for /api/fills.
356 static constexpr size_t FILL_HISTORY_CAPACITY = 1000;
357 FillHistory fills_{FILL_HISTORY_CAPACITY};
358 // Reverse map: broker order_id → client_order_id
359 std::unordered_map<std::string, std::string> oid_to_cid_;
360
361 // Broker status snapshot for change detection (plain bools, no atomics)
362 struct BrokerSnapshot {
363 bool md_enabled{false};
364 bool md_connected{false};
365 bool order_enabled{false};
366 bool order_connected{false};
367 };
368 std::array<BrokerSnapshot, static_cast<size_t>(BrokerId::_BROKER_ID_COUNT_)> last_broker_status_{};
369};
370
371} // namespace slick::trader
uint16_t get_port() const
WebServer(std::string_view config_path, StrategyManager &strategy_manager, PositionTracker &position_tracker, PnLCalculator &pnl_calculator, RiskManager &risk_manager, slick::stream_buffer_multiplexer &mux)
bool initialize(const json &config, std::string_view environment=PRODUCTION_ENVIRONMENT, const SimControlConfig &sim_control={})
constexpr std::string_view PRODUCTION_ENVIRONMENT
std::unordered_map< std::string, V, StringHash, std::equal_to<> > StringMap
int64_t qty_t
Definition types.hpp:17
int64_t price_t
Definition types.hpp:16
nlohmann::json json