Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
web_server.cpp
Go to the documentation of this file.
14#include <cassert>
15#include <chrono>
16#include <fstream>
17#include <sstream>
18#include <filesystem>
19#include <format>
20#include <utility>
21#include <vector>
22
23namespace slick::trader {
24
25namespace {
26
27// Calls `handler(body)` with the request's body once all of it has come. uWS hands it over in
28// chunks as they arrive, and a handler given the last alone parsed the tail of a long one.
29template <typename Handler>
30void read_body(uWS::HttpResponse<false>* res, Handler&& handler) {
31 res->onAborted([]() {});
32 res->onData([handler = std::forward<Handler>(handler), body = std::string()](std::string_view data,
33 bool last) mutable {
34 if (!last) {
35 body.append(data);
36 } else if (body.empty()) {
37 handler(data); // all in one chunk, as most are: no copy
38 } else {
39 body.append(data);
40 handler(std::string_view(body));
41 }
42 });
43}
44
45// Writes {"type":<type>,"instruments":{<instrument>:[<broker id>,<tick>,<min qty>],...}} into `out`: what
46// the dashboard's ladders can show, all of it ("instruments") or what is new ("instruments_added").
47// `for_each(emit)` calls emit(instrument, listing) for each. With no JSON tree: the whole list
48// runs to megabytes.
49template <typename ForEach>
50void write_instruments(std::string& out, std::string_view type, ForEach&& for_each) {
51 out.assign(R"({"type":)");
52 append_json_string(out, type);
53 out += R"(,"instruments":{)";
54 const size_t first = out.size();
55 for_each([&](std::string_view instrument, BrokerId broker, price_t tick_size, qty_t min_qty) {
56 if (out.size() != first) {
57 out += ',';
58 }
59 append_json_string(out, instrument);
60 out += ":[";
61 append_json_number(out, static_cast<int>(broker));
62 out += ',';
63 append_json_number(out, from_price_t(tick_size));
64 out += ',';
65 append_json_number(out, from_qty_t(min_qty));
66 out += ']';
67 });
68 out += "}}";
69}
70
71// For JSON with text from elsewhere in it: dump() throws on what isn't UTF-8, as a broker's reason or
72// slick-sim's reply cut inside a character isn't, and nothing catches in a uWS callback.
73std::string dump_lossy(const json& value) {
74 return value.dump(-1, ' ', false, json::error_handler_t::replace);
75}
76
77// What uWS writes after "HTTP/1.1 ": the code and its reason phrase, which a status line needs.
78std::string_view status_line(int status) {
79 switch (status) {
80 case 200: return "200 OK";
81 case 202: return "202 Accepted";
82 case 400: return "400 Bad Request";
83 case 403: return "403 Forbidden";
84 case 404: return "404 Not Found";
85 case 409: return "409 Conflict";
86 case 422: return "422 Unprocessable Content";
87 case 503: return "503 Service Unavailable";
88 default:
89 assert(status == 500 && "a status with no reason phrase here");
90 return "500 Internal Server Error";
91 }
92}
93
94} // namespace
95
96bool WebServer::initialize(const json& config, std::string_view environment, const SimControlConfig& sim_control) {
97 // Set before start() makes the thread that reads them.
98 environment_ = environment;
99 sim_ = sim_control.enabled() ? std::make_unique<SimControlLink>(sim_control) : nullptr;
100 if (sim_) {
101 LOG_INFO("WebServer: slick-sim control at {}", sim_->address());
102 }
103 make_health_json();
104
105 config_.port = config.value("web_server_port", 8080);
106 config_.enable_cors = config.value("web_server_cors", true);
107 config_.static_files_path = config.value("web_server_static_path", "web/static");
108 config_.ladder_release_ns = config.value("web_server_ladder_release_ms", 5000ull) * 1'000'000;
109
110 // Load ladder config if present
111 if (config.contains("ladder_config")) {
112 ladder_config_ = config["ladder_config"];
113 LOG_INFO("WebServer: Loaded ladder config");
114 } else {
115 // Set defaults if not in config
116 ladder_config_ = {
117 {"default_qty", 0.01},
118 {"per_instrument", json::object()}
119 };
120 LOG_INFO("WebServer: Using default ladder config");
121 }
122
123 workspaces_.load(config.value("web_server_workspaces_file", std::string("state/workspaces.json")));
124 // Both off unless asked for: they change this user's Edge and Chrome settings, which keep them.
125 list_origin(config, "web_server_allow_popups", config_.port, POPUP_POLICY_KEYS);
126 list_origin(config, "web_server_secure_origin", config_.port, SECURE_POLICY_KEYS);
127
128 // What the strategies subscribe is fixed once they start, and nothing runs them yet: their
129 // get_subscriptions() read state their on_config() writes on the StrategyManager thread.
130 // MANUAL's list grows: index_listings() takes it in as it does.
131 listings_.clear();
132 listings_indexed_ = 0;
133 for (const auto& strategy : strategy_manager_.get_all_strategies()) {
134 if (strategy.get() == strategy_manager_.manual()) {
135 continue;
136 }
137 for (const auto& sub : strategy->get_subscriptions()) {
138 for (const auto& instrument : sub.instruments) {
139 Listing& listing = listings_.try_emplace(instrument, Listing{sub.broker_id, 0, false}).first->second;
140 // A hold of what streams already is redundant, and harmful at Coinbase: its LEVEL2
141 // and ORDER_BOOK share one channel, so the hold's release would drop the strategy's.
142 if (streams_book(sub.type) && sub.broker_id == listing.broker) {
143 listing.book = true;
144 }
145 if (sub.type == SubscriptionType::TRADE && sub.broker_id == listing.broker) {
146 listing.trades = true;
147 }
148 }
149 }
150 }
151
152 // Register our producer on the event bus. Strategy parameter updates go out this way so
153 // the StrategyManager worker applies them on its own thread. add_producer() is setup-only
154 // and no bus thread has started yet, so here is the place to do it.{
155
156 // The id follows the same convention StrategyManager uses for its top-of-book producer:
157 // one past whatever is already registered. A collision is only possible if a broker
158 // claimed a sparse id, so scan for a free one rather than letting the throw escape.
159 const auto config_queue_size = config.value("config_queue_size", 1u << 16 /* 64K */);
160 const auto config_control_size = config.value("config_control_size", 4096u);
161 try {
162 uint32_t producer_id = static_cast<uint32_t>(event_mux_.producer_count());
163 while (event_mux_.has_producer(producer_id)) {
164 ++producer_id;
165 }
166 config_producer_buffer_ = event_mux_.add_producer(producer_id, config_queue_size,
167 config_control_size);
168 LOG_INFO("WebServer: Publishing strategy config updates as producer {}", producer_id);
169 } catch (const std::exception& e) {
170 // Not fatal: everything except live parameter updates still works.
171 LOG_ERROR("WebServer: Could not register the config producer: {}", e.what());
172 }
173
174 LOG_INFO("WebServer: Initialized on {}:{}", config_.host, config_.port);
175 return true;
176}
177
179 if (running_.load(std::memory_order_relaxed)) [[unlikely]] {
180 LOG_WARN("WebServer: Already running");
181 return;
182 }
183
184 // A worker whose listen failed cleared running_ itself and left its thread unjoined.
185 // Assigning a new thread over a joinable one calls std::terminate.
186 if (worker_thread_.joinable()) {
187 worker_thread_.join();
188 }
189
190 LOG_INFO("WebServer: Starting on port {}", config_.port);
191 running_.store(true, std::memory_order_release);
192 worker_thread_ = std::thread(&WebServer::run, this);
193
194 LOG_INFO("");
195 LOG_INFO("Available endpoints:");
196 LOG_INFO(" GET /api/health - Health check");
197 LOG_INFO(" GET /api/positions - All positions");
198 LOG_INFO(" GET /api/positions/:id - Strategy positions");
199 LOG_INFO(" GET /api/pnl - All PnL snapshots");
200 LOG_INFO(" GET /api/pnl/:id - Strategy PnL");
201 LOG_INFO(" GET /api/strategies - Strategy list");
202 LOG_INFO(" GET /api/workspaces - Saved window layouts");
203}
204
206 // The worker clears running_ itself when the listen fails, so a false running_ doesn't
207 // mean there is no thread left. It still has to be joined, because ~std::thread calls
208 // std::terminate on a joinable thread.
209 const bool was_running = running_.exchange(false);
210
211 if (was_running) {
212 LOG_INFO("WebServer: Stopping");
213
214 // The loop runs while anything is open on it, so closing the listen socket isn't
215 // enough: an open dashboard WebSocket would keep app.run(), and the join below,
216 // waiting until the tab closed. Close everything on the loop thread, the only one
217 // uWS may be used from.
218 //
219 // The lock is held across defer(). The loop is freed when the worker thread exits,
220 // and the worker takes this lock to retire loop_ before it can get there, so the
221 // loop can't go away under defer(). Whichever side takes the lock second sees the
222 // other's write: either stop() finds the loop, or the worker's running_ check after
223 // it publishes the loop sees the false written above.
224 {
225 std::lock_guard lock(loop_mutex_);
226 if (loop_) {
227 loop_->defer([this]() { close_connections(); });
228 }
229 }
230 }
231
232 if (worker_thread_.joinable()) {
233 worker_thread_.join();
234 }
235
236 if (was_running) {
237 LOG_INFO("WebServer: Stopped");
238 }
239}
240
241void WebServer::run() {
242 LOG_INFO("WebServer: Worker thread started");
243
244 try {
245 uWS::App app;
246 // Clears app_ however this scope is left, and before app is destroyed.
247 struct AppRetire {
248 uWS::App*& slot_;
249 ~AppRetire() { slot_ = nullptr; }
250 } retire_app{app_};
251 setup_routes(app);
252
253 app.listen(config_.port, [this](auto* socket) {
254 if (socket) {
255 LOG_INFO("WebServer: Listening on port {}", config_.port);
256
257 // Start polling market data and order events after listen succeeds
258 uWS::Loop::get()->defer([this]() {
259 process_events();
260 });
261 } else {
262 LOG_ERROR("WebServer: Failed to listen on port {}", config_.port);
263 running_.store(false, std::memory_order_release);
264 }
265 });
266
267 // stop() can reach the loop from here on. If it ran earlier it found no loop to
268 // defer to and only cleared running_, so act on that here.
269 app_ = &app;
270 {
271 std::lock_guard lock(loop_mutex_);
272 loop_ = uWS::Loop::get();
273 }
274 if (!running_.load()) {
275 close_connections();
276 }
277
278 // Run event loop (blocking)
279 app.run();
280
281 } catch (const std::exception& e) {
282 LOG_ERROR("WebServer: Exception in worker thread: {}", e.what());
283 }
284
285 if (sim_) {
286 sim_->disconnect();
287 }
288
289 // Wait out a stop() that is inside defer() on this loop. The loop is freed when this
290 // thread exits, just after this, so no one may use the pointer past this point.
291 {
292 std::lock_guard lock(loop_mutex_);
293 loop_ = nullptr;
294 }
295 LOG_INFO("WebServer: Worker thread stopped");
296}
297
298void WebServer::close_connections() {
299 // end() sends the close frame and runs the close handler, which removes the socket from
300 // all_ws_clients_, so iterate over a copy.
301 const std::vector<uWS::WebSocket<false, true, void*>*> clients(all_ws_clients_.begin(),
302 all_ws_clients_.end());
303 for (auto* ws : clients) {
304 ws->end(1001, "server shutting down");
305 }
306
307 // Close whatever is left: the listen socket, idle keep-alive HTTP connections, and
308 // clients that ignore the close frame. Each would hold the loop, and the join in stop(),
309 // until its own timeout.
310 if (app_) {
311 app_->close();
312 }
313}
314
315void WebServer::setup_routes(uWS::App &app) {
316 // Health check
317 app.get("/api/health", [this](auto* res, auto* req) {
318 send_json_response(res, health_json_);
319 });
320
321 // slick-sim's feeds, in Sim, and starting the replay of its pcap ones
322 app.get("/api/sim", [this](auto* res, auto* req) {
323 send_json_response(res, sim_json());
324 });
325 app.post("/api/sim/replay", [this](auto* res, auto* req) {
326 read_body(res, [this, res](std::string_view) { handle_post_sim_replay(res); });
327 });
328
329 // Broker status
330 app.get("/api/brokers", [this](auto* res, auto* req) {
331 handle_get_brokers(res, req);
332 });
333
334 // Get all strategies
335 app.get("/api/strategies", [this](auto* res, auto* req) {
336 handle_get_strategies(res, req);
337 });
338
339 // Get all positions
340 app.get("/api/positions", [this](auto* res, auto* req) {
341 handle_get_positions(res, req);
342 });
343
344 // Get all PnL
345 app.get("/api/pnl", [this](auto* res, auto* req) {
346 handle_get_pnl(res, req);
347 });
348
349 // Get positions for specific strategy
350 app.get("/api/positions/:strategy_id", [this](auto* res, auto* req) {
351 std::string strategy_id(req->getParameter(0));
352 handle_get_strategy_positions(res, req, strategy_id);
353 });
354
355 // Get PnL for specific strategy
356 app.get("/api/pnl/:strategy_id", [this](auto* res, auto* req) {
357 std::string strategy_id(req->getParameter(0));
358 handle_get_strategy_pnl(res, req, strategy_id);
359 });
360
361 // POST: Submit manual order
362 app.post("/api/orders", [this](auto* res, auto* req) {
363 read_body(res, [this, res](std::string_view body) { handle_post_order(res, nullptr, body); });
364 });
365
366 // GET: All open orders across all strategies
367 app.get("/api/orders", [this](auto* res, auto* req) {
368 handle_get_orders(res, req);
369 });
370
371 // GET: The last fills, oldest first
372 app.get("/api/fills", [this](auto* res, auto* req) {
373 handle_get_fills(res, req);
374 });
375
376 // DELETE: Cancel all open orders (must be registered before the parameterized route)
377 app.del("/api/orders/cancel-all", [this](auto* res, auto* req) {
378 res->onData([this, res](std::string_view, bool last) {
379 if (last) handle_delete_all_orders(res, nullptr);
380 });
381 res->onAborted([]() {});
382 });
383
384 // PUT: Modify a specific order
385 app.put("/api/orders/:strategy_id/:order_id", [this](auto* res, auto* req) {
386 std::string sid(req->getParameter(0)), oid(req->getParameter(1));
387 read_body(res, [this, res, sid, oid](std::string_view body) { handle_put_order(res, nullptr, sid, oid, body); });
388 });
389
390 // DELETE: Cancel a specific order
391 app.del("/api/orders/:strategy_id/:order_id", [this](auto* res, auto* req) {
392 std::string sid(req->getParameter(0)), oid(req->getParameter(1));
393 read_body(res, [this, res, sid, oid](std::string_view body) { handle_delete_order(res, nullptr, sid, oid, body); });
394 });
395
396 // POST: Strategy control (start/stop)
397 app.post("/api/strategies/:strategy_id/control", [this](auto* res, auto* req) {
398 std::string strategy_id(req->getParameter(0));
399 read_body(res, [this, res, strategy_id](std::string_view body) {
400 handle_post_strategy_control(res, nullptr, strategy_id, body);
401 });
402 });
403
404 // GET: Risk limits for strategy
405 app.get("/api/strategies/:strategy_id/risk", [this](auto* res, auto* req) {
406 std::string strategy_id(req->getParameter(0));
407 handle_get_risk_limits(res, req, strategy_id);
408 });
409
410 // PUT: Update risk limits for strategy
411 app.put("/api/strategies/:strategy_id/risk", [this](auto* res, auto* req) {
412 std::string strategy_id(req->getParameter(0));
413 read_body(res, [this, res, strategy_id](std::string_view body) {
414 handle_put_risk_limits(res, nullptr, strategy_id, body);
415 });
416 });
417
418 // GET: Current strategy parameters
419 app.get("/api/strategies/:strategy_id/config", [this](auto* res, auto* req) {
420 std::string strategy_id(req->getParameter(0));
421 handle_get_strategy_config(res, req, strategy_id);
422 });
423
424 // PUT: Update strategy parameters at runtime and persist to config.json
425 app.put("/api/strategies/:strategy_id/config", [this](auto* res, auto* req) {
426 std::string strategy_id(req->getParameter(0));
427 read_body(res, [this, res, strategy_id](std::string_view body) {
428 handle_put_strategy_config(res, nullptr, strategy_id, body);
429 });
430 });
431
432 // POST: Halt strategy
433 app.post("/api/strategies/:strategy_id/halt", [this](auto* res, auto* req) {
434 std::string strategy_id(req->getParameter(0));
435 read_body(res, [this, res, strategy_id](std::string_view body) {
436 handle_post_halt_strategy(res, nullptr, strategy_id, body);
437 });
438 });
439
440 // POST: Resume strategy
441 app.post("/api/strategies/:strategy_id/resume", [this](auto* res, auto* req) {
442 std::string strategy_id(req->getParameter(0));
443 handle_post_resume_strategy(res, req, strategy_id);
444 });
445
446 // GET: Ladder configuration
447 app.get("/api/ladder-config", [this](auto* res, auto* req) {
448 handle_get_ladder_config(res, req);
449 });
450
451 // PUT: Update ladder configuration
452 app.put("/api/ladder-config", [this](auto* res, auto* req) {
453 read_body(res, [this, res](std::string_view body) { handle_put_ladder_config(res, nullptr, std::string(body)); });
454 });
455
456 // Workspaces: saved window layouts. The name goes in the body, so it needs no URL decoding.
457 app.get("/api/workspaces", [this](auto* res, auto* req) {
458 send_json_response(res, workspaces_.doc().dump());
459 });
460 app.put("/api/workspaces", [this](auto* res, auto* req) {
461 read_body(res, [this, res](std::string_view body) { handle_workspace_change(res, body, WorkspaceChange::SAVE); });
462 });
463 app.del("/api/workspaces", [this](auto* res, auto* req) {
464 read_body(res, [this, res](std::string_view body) { handle_workspace_change(res, body, WorkspaceChange::REMOVE); });
465 });
466 app.put("/api/workspaces/last", [this](auto* res, auto* req) {
467 read_body(res, [this, res](std::string_view body) { handle_workspace_change(res, body, WorkspaceChange::USE); });
468 });
469
470 // WebSocket endpoint
471 app.ws<void*>("/*", {
472 .maxBackpressure = WS_MAX_BACKPRESSURE,
473 .open = [this](auto* ws) {
474 handle_ws_open(ws);
475 },
476 .message = [this](auto* ws, std::string_view message, uWS::OpCode opCode) {
477 handle_ws_message(ws, message);
478 },
479 .close = [this](auto* ws, int code, std::string_view message) {
480 handle_ws_close(ws);
481 }
482 });
483
484 // Static file serving
485 app.get("/*", [this](auto* res, auto* req) {
486 std::string url(req->getUrl());
487
488 // The app slick-trader-web.bat adds opens each dashboard at /app/<token>/. Edge and Chrome
489 // name the windows of an app after the path it opened at, so each dashboard's windows can
490 // be told from another's. The page itself is the root's, told it is grouped.
491 if (url.starts_with("/app/")) {
492 res->writeStatus("302 Found");
493 res->writeHeader("Location", "/?grouped");
494 res->end();
495 return;
496 }
497
498 // Default to index.html for root path
499 if (url == "/" || url == "") {
500 url = "/index.html";
501 }
502
503 // Construct file path
504 std::filesystem::path file_path = std::filesystem::path(config_.static_files_path) / url.substr(1);
505
506 // Security check: prevent directory traversal
507 auto canonical_base = std::filesystem::weakly_canonical(config_.static_files_path);
508 auto canonical_path = std::filesystem::weakly_canonical(file_path);
509
510 if (canonical_path.string().find(canonical_base.string()) != 0) {
511 send_error_response(res, "Invalid path", 403);
512 return;
513 }
514
515 // Check if file exists
516 if (!std::filesystem::exists(file_path) || !std::filesystem::is_regular_file(file_path)) {
517 send_error_response(res, "File not found", 404);
518 return;
519 }
520
521 // Read file
522 std::ifstream file(file_path, std::ios::binary);
523 if (!file) {
524 send_error_response(res, "Failed to read file", 500);
525 return;
526 }
527
528 std::ostringstream content;
529 content << file.rdbuf();
530 std::string file_content = content.str();
531
532 // Determine content type
533 std::string content_type = "application/octet-stream";
534 std::string extension = file_path.extension().string();
535
536 if (extension == ".html") content_type = "text/html";
537 else if (extension == ".css") content_type = "text/css";
538 else if (extension == ".js") content_type = "application/javascript";
539 else if (extension == ".json") content_type = "application/json";
540 else if (extension == ".png") content_type = "image/png";
541 else if (extension == ".jpg" || extension == ".jpeg") content_type = "image/jpeg";
542 else if (extension == ".svg") content_type = "image/svg+xml";
543 else if (extension == ".ico") content_type = "image/x-icon";
544
545 // Send response
546 res->writeStatus("200 OK");
547 add_cors_headers(res);
548 res->writeHeader("Content-Type", content_type);
549 // The dashboard ships with the engine: a page reloaded after a restart must run the
550 // scripts that engine came with, not ones the browser kept from the last.
551 res->writeHeader("Cache-Control", "no-cache");
552 res->end(file_content);
553 });
554}
555
556void WebServer::handle_get_brokers(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
557 try {
558 auto& reg = BrokerStatusRegistry::instance();
559 json brokers = json::array();
560 const auto& all = reg.all();
561 for (size_t i = 1; i < all.size(); ++i) {
562 const auto& s = all[i];
563 if (!reg.is_registered(static_cast<BrokerId>(i))) continue;
564 brokers.push_back({
565 {"id", i},
566 {"name", s.name},
567 {"md", {
568 {"enabled", s.md_enabled.load(std::memory_order_acquire)},
569 {"connected", s.md_connected.load(std::memory_order_acquire)}
570 }},
571 {"order", {
572 {"enabled", s.order_enabled.load(std::memory_order_acquire)},
573 {"connected", s.order_connected.load(std::memory_order_acquire)}
574 }}
575 });
576 }
577 send_json_response(res, json{{"brokers", brokers}}.dump());
578 } catch (const std::exception& e) {
579 send_error_response(res, e.what(), 500);
580 }
581}
582
583void WebServer::handle_get_strategies(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
584 try {
585 json response = json::array();
586
587 const auto& strategies = strategy_manager_.get_all_strategies();
588 for (const auto& strategy : strategies) {
589 const std::string sname = strategy->name();
590 std::string status;
591 std::string pause_reason;
592 if (risk_manager_.is_halted(sname)) {
593 status = "halted";
594 pause_reason = risk_manager_.get_halt_reason(sname);
595 } else if (strategy_manager_.is_auto_paused(sname)) {
596 status = "paused";
597 pause_reason = strategy_manager_.get_auto_pause_reason(sname);
598 } else if (auto* base = dynamic_cast<StrategyBase*>(strategy.get()); base && base->is_running()) {
599 status = "running";
600 } else {
601 status = "stopped";
602 }
603
604 response.push_back({
605 {"name", sname},
606 {"id", sname},
607 {"status", status},
608 {"halt_reason", pause_reason},
609 {"type", strategy.get() == strategy_manager_.manual() ? "builtin" : "plugin"}
610 });
611 }
612
613 send_json_response(res, response.dump());
614 } catch (const std::exception& e) {
615 send_error_response(res, e.what(), 500);
616 }
617}
618
619void WebServer::handle_get_positions(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
620 try {
621 auto all_positions = position_tracker_.get_all_positions();
622
623 json response = json::object();
624 for (const auto& [strategy_id, positions] : all_positions) {
625 json strategy_positions = json::array();
626
627 for (const auto& [instrument, position] : positions) {
628 if (position.is_flat()) continue; // Skip flat positions
629
630 const price_t mark = pnl_calculator_.get_mark_price(instrument);
631 const double unrealized = position.get_unrealized_pnl(mark);
632
633 strategy_positions.push_back({
634 {"instrument", position.instrument},
635 {"quantity", from_qty_t(position.quantity)},
636 {"avg_price", from_price_t(position.avg_price)},
637 {"realized_pnl", from_price_t(position.realized_pnl)},
638 {"unrealized_pnl", unrealized},
639 {"mark_price", from_price_t(mark)},
640 {"last_update_time", position.last_update_time}
641 });
642 }
643
644 if (!strategy_positions.empty()) {
645 response[strategy_id] = strategy_positions;
646 }
647 }
648
649 send_json_response(res, response.dump());
650 } catch (const std::exception& e) {
651 send_error_response(res, e.what(), 500);
652 }
653}
654
655void WebServer::handle_get_pnl(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
656 try {
657 const uint64_t now_ns = get_timestamp_ns();
658 auto all_pnl = pnl_calculator_.calculate_all_pnl(now_ns);
659
660 json response = json::object();
661 for (const auto& [strategy_id, pnl] : all_pnl) {
662 response[strategy_id] = {
663 {"realized_pnl", pnl.get_realized()},
664 {"unrealized_pnl", pnl.get_unrealized()},
665 {"total_fees", pnl.get_fees()},
666 {"total_pnl", pnl.get_total()},
667 {"timestamp_ns", pnl.timestamp_ns}
668 };
669 }
670
671 send_json_response(res, response.dump());
672 } catch (const std::exception& e) {
673 send_error_response(res, e.what(), 500);
674 }
675}
676
677void WebServer::handle_get_strategy_positions(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
678 const std::string& strategy_id) {
679 try {
680 auto positions = position_tracker_.get_all_positions(strategy_id);
681
682 json response = json::array();
683 for (const auto& [instrument, position] : positions) {
684 if (position.is_flat()) continue; // Skip flat positions
685
686 response.push_back({
687 {"instrument", position.instrument},
688 {"quantity", from_qty_t(position.quantity)},
689 {"avg_price", from_price_t(position.avg_price)},
690 {"realized_pnl", from_price_t(position.realized_pnl)},
691 {"last_update_time", position.last_update_time}
692 });
693 }
694
695 send_json_response(res, response.dump());
696 } catch (const std::exception& e) {
697 send_error_response(res, e.what(), 500);
698 }
699}
700
701void WebServer::handle_get_strategy_pnl(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
702 const std::string& strategy_id) {
703 try {
704 const uint64_t now_ns = get_timestamp_ns();
705 auto pnl = pnl_calculator_.calculate_pnl(strategy_id, now_ns);
706
707 json response = {
708 {"strategy_id", pnl.strategy_id},
709 {"realized_pnl", pnl.get_realized()},
710 {"unrealized_pnl", pnl.get_unrealized()},
711 {"total_fees", pnl.get_fees()},
712 {"total_pnl", pnl.get_total()},
713 {"timestamp_ns", pnl.timestamp_ns}
714 };
715
716 send_json_response(res, response.dump());
717 } catch (const std::exception& e) {
718 send_error_response(res, e.what(), 500);
719 }
720}
721
722void WebServer::handle_ws_open(uWS::WebSocket<false, true, void*>* ws) {
723 LOG_INFO("WebServer: WebSocket connection opened");
724 all_ws_clients_.insert(ws);
725
726 // Send welcome message. The instruments ladders can show go only to a client that asks: the
727 // list runs to megabytes, and a window with no ladder has no use for it.
728 std::string welcome = R"({"type":"welcome","message":"Connected to SlickTrader"})";
729 send_text(ws, welcome);
730
731 // On the socket, not over REST: an answer there could come after a later change here.
732 if (sim_) {
733 send_text(ws, sim_json("sim_status"));
734 }
735}
736
737void WebServer::handle_ws_message(uWS::WebSocket<false, true, void*>* ws, std::string_view message) {
738 // A client uWS dropped a send for is closed at the end of this loop pass. Until then its asks
739 // are only dropped too, and uWS may hand over thousands at once, each snapshot costing the
740 // book's depth: answering them held its close back for seconds.
741 if (!lagging_.empty() && lagging_.contains(ws)) [[unlikely]] {
742 return;
743 }
744 try {
745 auto msg = json::parse(message);
746 std::string type = msg.value("type", "");
747
748 if (type == "subscribe") {
749 std::string channel = msg.value("channel", "");
750 std::string instrument = msg.value("instrument", "");
751
752 if (channel == "instruments") {
753 // All of them now, then what is new from process_events().
754 instrument_clients_.insert(ws);
755 send_instruments(ws);
756 } else if (channel == "level2" && !instrument.empty()) {
757 const Level2Book* book = level2_streams_.subscribe(ws, instrument);
758 if (!book) {
759 // Debug: a page sending these in a loop would flood the log.
760 LOG_DEBUG("WebServer: level2 subscription to '{}' refused: no instrument has a name that "
761 "long, or the client watches {} already",
762 instrument, decltype(level2_streams_)::MAX_STREAMS_PER_CLIENT);
763 return;
764 }
765
766 // The first ladder on one of MANUAL's has it held at its broker, its book emptied
767 // if it went stale since it was last let go.
768 if (level2_streams_.watchers(instrument) == 1 && !watched(instrument)) {
769 send_text(ws, json{{"type", "subscription_error"},
770 {"channel", channel},
771 {"instrument", instrument},
772 {"message", "could not ask for its market data"}}
773 .dump());
774 }
775
776 json response = {
777 {"type", "subscribed"},
778 {"channel", channel},
779 {"instrument", instrument}
780 };
781 send_text(ws, response.dump());
782
783 // The broker's own snapshot may have streamed before this browser asked, so it
784 // starts from the book as it stands. Again on a repeat: a page that built its
785 // ladder anew asks again, and has nothing to start from otherwise. Empty while its
786 // broker's feed is down: the book is as the feed left it, and the snapshot that
787 // follows the reconnect replaces it.
788 LOG_INFO("WebServer: Client subscribed to level2 for {}", instrument);
789 const auto& brokers = BrokerStatusRegistry::instance();
790 const BrokerId broker = book->broker();
791 const bool stale = broker != BrokerId::UNKNOWN && brokers.is_md_enabled(broker) &&
792 !brokers.is_md_connected(broker);
793 write_level2_message(level2_message_, instrument, book->event_time_ns(), book->sequence_num(),
794 true, [&](auto&& emit) {
795 if (!stale) {
796 book->for_each(emit);
797 }
798 });
799 send_text(ws, level2_message_);
800 // Its LTQ, from the trade before this browser asked.
801 if (const LastTrade* trade = level2_streams_.last_trade(instrument); trade && !stale) {
802 write_trade_message(trade_message_, instrument, *trade);
803 send_text(ws, trade_message_);
804 }
805 } else {
806 LOG_WARN("WebServer: Invalid subscription request - channel: {}, instrument: {}", channel, instrument);
807 }
808 } else if (type == "unsubscribe") {
809 std::string channel = msg.value("channel", "");
810 std::string instrument = msg.value("instrument", "");
811
812 if (channel == "level2" && level2_streams_.unsubscribe(ws, instrument)) {
813 LOG_INFO("WebServer: Client unsubscribed from level2 for {}", instrument);
814 if (level2_streams_.watchers(instrument) == 0) {
815 unwatched(instrument);
816 }
817 }
818 } else if (type == "ping") {
819 send_text(ws, R"({"type":"pong"})");
820 } else {
821 LOG_WARN("WebServer: Unknown WebSocket message type: {}", type);
822 }
823 } catch (const std::exception& e) {
824 LOG_ERROR("WebServer: Error handling WebSocket message: {}", e.what());
825 }
826}
827
828void WebServer::handle_ws_close(uWS::WebSocket<false, true, void*>* ws) {
829 // Remove from all connected clients and from the books it watched
830 all_ws_clients_.erase(ws);
831 instrument_clients_.erase(ws);
832 level2_streams_.remove(ws, [this](std::string_view instrument) { unwatched(instrument); });
833 lagging_.erase(ws);
834
835 LOG_INFO("WebServer: WebSocket connection closed and cleaned up");
836}
837
838void WebServer::send_text(Socket* ws, std::string_view message) {
839 if (ws->send(message, uWS::OpCode::TEXT) == Socket::SendStatus::DROPPED) [[unlikely]] {
840 lagging_.insert(ws);
841 }
842}
843
844void WebServer::close_lagging() {
845 // Every pass: the exchange below builds a set, which allocates on MSVC.
846 if (lagging_.empty()) [[likely]] {
847 return;
848 }
849 // close() runs the close handler now, so not from send_text(): a broadcast may be walking
850 // the clients it would remove this one from.
851 for (auto* ws : std::exchange(lagging_, {})) {
852 LOG_WARN("WebServer: closing a WebSocket client {} KB behind, so it reconnects in step",
853 ws->getBufferedAmount() / 1024);
854 ws->close();
855 }
856}
857
858void WebServer::send_json_response(uWS::HttpResponse<false>* res, const std::string& json, int status) {
859 // Status first: uWS sends 200 OK with the first header written ahead of one, and ignores
860 // the status written after, so every error went out as a success.
861 res->writeStatus(status_line(status));
862 add_cors_headers(res);
863 res->writeHeader("Content-Type", "application/json");
864 res->end(json);
865}
866
867void WebServer::send_error_response(uWS::HttpResponse<false>* res, const std::string& error, int status) {
868 json response = {
869 {"error", error}
870 };
871 send_json_response(res, dump_lossy(response), status);
872}
873
874void WebServer::add_cors_headers(uWS::HttpResponse<false>* res) {
875 if (config_.enable_cors) {
876 res->writeHeader("Access-Control-Allow-Origin", "*");
877 res->writeHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
878 res->writeHeader("Access-Control-Allow-Headers", "Content-Type");
879 }
880}
881
882void WebServer::handle_post_order(uWS::HttpResponse<false>* res, uWS::HttpRequest* req, std::string_view body) {
883 try {
884 auto order_data = json::parse(body);
885
886 // Validate required fields
887 if (!order_data.contains("instrument") ||
888 !order_data.contains("side") || !order_data.contains("quantity") || !order_data.contains("broker_id")) {
889 send_error_response(res, "Missing required fields: instrument, broker_id, side, quantity", 400);
890 return;
891 }
892
893 const std::string strategy_id = ManualStrategy::ID;
894 std::string instrument = order_data["instrument"];
895 // Wide, and range checked before they narrow: read as a byte, 258 was broker 2.
896 const int64_t broker_id_raw = order_data["broker_id"].get<int64_t>();
897 std::string side_str = order_data["side"];
898 double quantity = order_data["quantity"];
899
900 // Optional fields
901 std::string order_type = order_data.value("type", "market");
902 double price = order_data.value("price", std::numeric_limits<double>::quiet_NaN());
903 const int64_t tif_raw = order_data.value("time_in_force", int64_t{0}); // Default to GTC
904
905 // Only a broker this engine built, and one that can take the order now: the strategy
906 // would turn it down anyway, and the caller would hear nothing of why.
907 const auto& brokers = BrokerStatusRegistry::instance();
908 if (broker_id_raw <= 0 || broker_id_raw >= static_cast<int64_t>(BrokerId::_BROKER_ID_COUNT_) ||
909 !brokers.is_registered(static_cast<BrokerId>(broker_id_raw))) {
910 std::string registered;
911 for (size_t i = 1; i < static_cast<size_t>(BrokerId::_BROKER_ID_COUNT_); ++i) {
912 if (brokers.is_registered(static_cast<BrokerId>(i))) {
913 registered += std::format("{}{} ({})", registered.empty() ? "" : ", ", brokers.all()[i].name, i);
914 }
915 }
916 send_error_response(res, std::format("No broker {} in this engine. It has: {}", broker_id_raw,
917 registered.empty() ? "none" : registered), 400);
918 return;
919 }
920 const BrokerId broker_id = static_cast<BrokerId>(broker_id_raw);
921 if (const char* reason = brokers.order_unavailable_reason(broker_id)) {
922 send_error_response(res, std::format("{}: {}", brokers.get(broker_id).name, reason), 503);
923 return;
924 }
925
926 // Validate time_in_force
927 if (tif_raw < 0 || tif_raw > static_cast<int64_t>(TimeInForce::DAY)) { // Valid range is 0-4
928 send_error_response(res, "Invalid time_in_force: must be 0 (GTC), 1 (IOC), 2 (FOK), 3 (GTD) or 4 (DAY)", 400);
929 return;
930 }
931 const TimeInForce tif = static_cast<TimeInForce>(tif_raw);
932
933 // Validate side
934 Side side;
935 if (side_str == "buy" || side_str == "BUY") {
936 side = Side::BUY;
937 } else if (side_str == "sell" || side_str == "SELL") {
938 side = Side::SELL;
939 } else {
940 send_error_response(res, "Invalid side: must be 'buy' or 'sell'", 400);
941 return;
942 }
943
944 // Validate order type
945 OrderType type;
946 if (order_type == "market") {
947 type = OrderType::MARKET;
948 } else if (order_type == "limit") {
949 type = OrderType::LIMIT;
950 if (price <= 0.0) {
951 send_error_response(res, "Limit orders require a valid price", 400);
952 return;
953 }
954 } else {
955 send_error_response(res, "Invalid order type: must be 'market' or 'limit'", 400);
956 return;
957 }
958
959 // Submit the order through the strategy
960 LOG_INFO("WebServer: Manual order request - Strategy: {}, Instrument: {}, Broker: {}, Side: {}, {}@{}, Type: {}, TIF: {}",
961 strategy_id, instrument, static_cast<int>(broker_id), side_str, quantity, price, order_type, tif_raw);
962
963 auto strategy = strategy_manager_.get_strategy(strategy_id);
964 if (!strategy) {
965 LOG_ERROR("WebServer: strategy {} not found", strategy_id);
966 send_error_response(res, "Strategy not found", 404);
967 return;
968 }
969 std::string refusal;
970 std::string client_order_id = reinterpret_pointer_cast<StrategyBase>(strategy)->submit_order(
971 instrument, broker_id, side, to_qty_t(quantity), type, to_price_t(price), tif, true, &refusal);
972 if (client_order_id.empty()) {
973 // Turned down before it left the engine: by risk, or by a broker gone since the check above.
974 send_error_response(res, "Order rejected: " + refusal, 422);
975 return;
976 }
977
978 // Seed WebServer-side tracking so handle_get_orders() can return it immediately
979 TrackedOrder t;
980 t.strategy_id = strategy_id;
981 t.client_order_id = client_order_id;
982 t.instrument = instrument;
983 t.side = side_str;
984 t.type = static_cast<int>(type);
985 t.price = price;
986 t.qty = quantity;
987 t.remaining_qty = quantity;
988 t.status = "PENDING_NEW";
989 t.created_time = static_cast<uint64_t>(
990 std::chrono::duration_cast<std::chrono::nanoseconds>(
991 std::chrono::system_clock::now().time_since_epoch()).count());
992 t.last_update_time = t.created_time;
993 open_orders_[client_order_id] = std::move(t);
994
995 json response = {
996 {"success", true},
997 {"message", "Order submitted successfully"},
998 {"order", {
999 {"strategy_id", strategy_id},
1000 {"instrument", instrument},
1001 {"broker_id", broker_id_raw},
1002 {"side", side_str},
1003 {"quantity", quantity},
1004 {"type", order_type},
1005 {"price", price},
1006 {"time_in_force", tif_raw}
1007 }}
1008 };
1009
1010 send_json_response(res, response.dump(), 202); // 202 Accepted
1011 } catch (const json::exception& e) {
1012 send_error_response(res, std::string("Invalid JSON: ") + e.what(), 400);
1013 } catch (const std::exception& e) {
1014 send_error_response(res, e.what(), 500);
1015 }
1016}
1017
1018void WebServer::handle_post_strategy_control(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1019 const std::string& strategy_id, std::string_view body) {
1020 try {
1021 auto control_data = json::parse(body);
1022
1023 if (!control_data.contains("action")) {
1024 send_error_response(res, "Missing required field: action", 400);
1025 return;
1026 }
1027
1028 std::string action = control_data["action"];
1029
1030 // TODO: Implement actual strategy control
1031 // For now, just log and return
1032 LOG_INFO("WebServer: Strategy control request - Strategy: {}, Action: {}", strategy_id, action);
1033
1034 if (action == "start" || action == "resume") {
1035 bool ok = strategy_manager_.start_strategy(strategy_id);
1036 if (!ok) {
1037 send_error_response(res, "Strategy not found: " + strategy_id, 404);
1038 return;
1039 }
1040 send_json_response(res, json{{"success", true}, {"strategy_id", strategy_id}, {"action", action}}.dump());
1041 } else if (action == "stop" || action == "pause") {
1042 bool ok = strategy_manager_.stop_strategy(strategy_id);
1043 if (!ok) {
1044 send_error_response(res, "Strategy not found: " + strategy_id, 404);
1045 return;
1046 }
1047 send_json_response(res, json{{"success", true}, {"strategy_id", strategy_id}, {"action", action}}.dump());
1048 } else {
1049 send_error_response(res, "Invalid action: must be 'start', 'stop', 'pause', or 'resume'", 400);
1050 }
1051
1052 } catch (const json::exception& e) {
1053 send_error_response(res, std::string("Invalid JSON: ") + e.what(), 400);
1054 } catch (const std::exception& e) {
1055 send_error_response(res, e.what(), 500);
1056 }
1057}
1058
1059void WebServer::handle_get_risk_limits(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1060 const std::string& strategy_id) {
1061 try {
1062 auto limits = risk_manager_.get_limits(strategy_id);
1063
1064 json response = {
1065 {"strategy_id", strategy_id},
1066 {"max_position_size", from_qty_t(limits.max_position_size)},
1067 {"max_order_value", from_price_t(limits.max_order_value)},
1068 {"max_orders_per_second", limits.max_orders_per_second},
1069 {"max_loss_per_strategy", from_price_t(limits.max_loss_per_strategy)},
1070 {"halted", risk_manager_.is_halted(strategy_id)}
1071 };
1072
1073 // Add per-instrument limits if any
1074 if (!limits.instrument_limits.empty()) {
1075 json inst_limits = json::object();
1076 for (const auto& [instrument, inst_limit] : limits.instrument_limits) {
1077 inst_limits[instrument] = {
1078 {"max_position_size", from_qty_t(inst_limit.max_position_size)},
1079 {"max_order_value", from_price_t(inst_limit.max_order_value)}
1080 };
1081 }
1082 response["instrument_limits"] = inst_limits;
1083 }
1084
1085 send_json_response(res, response.dump());
1086 } catch (const std::exception& e) {
1087 send_error_response(res, e.what(), 500);
1088 }
1089}
1090
1091void WebServer::handle_put_risk_limits(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1092 const std::string& strategy_id, std::string_view body) {
1093 try {
1094 auto update_data = json::parse(body);
1095
1096 // Get current limits
1097 auto limits = risk_manager_.get_limits(strategy_id);
1098
1099 // Update provided fields
1100 if (update_data.contains("max_position_size")) {
1101 limits.max_position_size = to_qty_t(update_data["max_position_size"].get<double>());
1102 }
1103
1104 if (update_data.contains("max_order_value")) {
1105 limits.max_order_value = to_price_t(update_data["max_order_value"].get<double>());
1106 }
1107
1108 if (update_data.contains("max_orders_per_second")) {
1109 limits.max_orders_per_second = update_data["max_orders_per_second"].get<uint32_t>();
1110 }
1111
1112 if (update_data.contains("max_loss_per_strategy")) {
1113 limits.max_loss_per_strategy = to_price_t(update_data["max_loss_per_strategy"].get<double>());
1114 }
1115
1116 // Update per-instrument limits
1117 if (update_data.contains("instrument_limits") && update_data["instrument_limits"].is_object()) {
1118 for (const auto& [instrument, inst_data] : update_data["instrument_limits"].items()) {
1119 InstrumentRiskLimits inst_limits;
1120
1121 if (inst_data.contains("max_position_size")) {
1122 inst_limits.max_position_size = to_qty_t(inst_data["max_position_size"].get<double>());
1123 }
1124
1125 if (inst_data.contains("max_order_value")) {
1126 inst_limits.max_order_value = to_price_t(inst_data["max_order_value"].get<double>());
1127 }
1128
1129 limits.instrument_limits[instrument] = inst_limits;
1130 }
1131 }
1132
1133 // Apply updated limits
1134 risk_manager_.set_limits(strategy_id, limits);
1135
1136 LOG_INFO("WebServer: Updated risk limits for strategy {}", strategy_id);
1137
1138 json response = {
1139 {"success", true},
1140 {"message", "Risk limits updated successfully"},
1141 {"strategy_id", strategy_id}
1142 };
1143
1144 send_json_response(res, response.dump());
1145 } catch (const json::exception& e) {
1146 send_error_response(res, std::string("Invalid JSON: ") + e.what(), 400);
1147 } catch (const std::exception& e) {
1148 send_error_response(res, e.what(), 500);
1149 }
1150}
1151
1152void WebServer::handle_get_strategy_config(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1153 const std::string& strategy_id) {
1154 auto strategy = strategy_manager_.get_strategy(strategy_id);
1155 if (!strategy) {
1156 send_error_response(res, "Strategy not found: " + strategy_id, 404);
1157 return;
1158 }
1159 auto* base = dynamic_cast<StrategyBase*>(strategy.get());
1160 if (!base) {
1161 send_error_response(res, "Strategy does not support config", 400);
1162 return;
1163 }
1164 send_json_response(res, base->get_config().dump(2));
1165}
1166
1167void WebServer::handle_put_strategy_config(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1168 const std::string& strategy_id, std::string_view body) {
1169 try {
1170 auto params = json::parse(body);
1171 if (!params.is_object()) {
1172 send_error_response(res, "Parameters must be a JSON object", 400);
1173 return;
1174 }
1175
1176 auto strategy = strategy_manager_.get_strategy(strategy_id);
1177 if (!strategy) {
1178 send_error_response(res, "Strategy not found: " + strategy_id, 404);
1179 return;
1180 }
1181 auto* base = dynamic_cast<StrategyBase*>(strategy.get());
1182 if (!base) {
1183 send_error_response(res, "Strategy does not support config", 400);
1184 return;
1185 }
1186
1187 // Hand the update to the worker thread rather than calling set_config() from here:
1188 // a strategy's on_config() may touch state that only its own thread owns.
1189 if (!publish_strategy_config(strategy_id, params)) {
1190 send_error_response(res, "Could not publish the config update", 503);
1191 return;
1192 }
1193 save_strategy_parameters(strategy_id, params);
1194
1195 LOG_INFO("WebServer: Published config update for strategy {}", strategy_id);
1196
1197 json response = {
1198 {"success", true},
1199 {"message", "Config updated successfully"},
1200 {"strategy_id", strategy_id}
1201 };
1202 send_json_response(res, response.dump());
1203 } catch (const json::exception& e) {
1204 send_error_response(res, std::string("Invalid JSON: ") + e.what(), 400);
1205 } catch (const std::exception& e) {
1206 send_error_response(res, e.what(), 500);
1207 }
1208}
1209
1210bool WebServer::publish_strategy_config(const std::string& strategy_id, const nlohmann::json& params) {
1211 if (!config_producer_buffer_) {
1212 LOG_ERROR("WebServer: no config producer registered — cannot publish an update for {}",
1213 strategy_id);
1214 return false;
1215 }
1216
1217 const std::string text = params.dump();
1218 if (text.size() > MAX_STRATEGY_CONFIG_LENGTH) {
1219 LOG_ERROR("WebServer: config for {} is {} bytes, over the {} byte limit",
1220 strategy_id, text.size(), MAX_STRATEGY_CONFIG_LENGTH);
1221 return false;
1222 }
1223 if (strategy_id.size() >= MAX_STRATEGY_NAME_LENGTH) {
1224 LOG_ERROR("WebServer: strategy name '{}' is too long to publish", strategy_id);
1225 return false;
1226 }
1227
1228 // Trailing flexible array, so the published size covers the header plus the JSON text.
1229 const uint32_t size = StrategyConfigEvent::size_for(text.size());
1230 return EventSerializer::publish<StrategyConfigEvent>(
1231 *config_producer_buffer_, size, [&](StrategyConfigEvent& event) {
1232 event.timestamp_ns = get_timestamp_ns();
1233 event.set_strategy(strategy_id);
1234 event.set_config(text);
1235 });
1236}
1237
1238// Mirrors StrategyManager::load_strategies(): the per-strategy files live in
1239// strategy_configs_folder as *.config.json and are keyed by the "name" INSIDE the
1240// file, not by the filename, so that is what we match on here.
1241bool WebServer::save_to_strategy_config_file(const std::string& configs_folder,
1242 const std::string& strategy_id,
1243 const nlohmann::json& params) {
1244 std::error_code ec;
1245 if (configs_folder.empty() || !std::filesystem::exists(configs_folder, ec)) {
1246 return false;
1247 }
1248
1249 for (const auto& entry : std::filesystem::directory_iterator(configs_folder, ec)) {
1250 if (ec) break;
1251 if (!entry.is_regular_file()) continue;
1252 if (!entry.path().filename().string().ends_with(".config.json")) continue;
1253
1254 json strategy_json;
1255 {
1256 std::ifstream in(entry.path());
1257 if (!in.is_open()) continue;
1258 try {
1259 strategy_json = json::parse(in);
1260 } catch (const json::exception& e) {
1261 LOG_WARN("WebServer: skipping unparsable strategy config {}: {}",
1262 entry.path().filename().string(), e.what());
1263 continue;
1264 }
1265 }
1266 if (strategy_json.value("name", "") != strategy_id) continue;
1267
1268 // Only the parameters block is ours; enabled and risk_limits stay as written.
1269 strategy_json["parameters"] = params;
1270
1271 const auto path = entry.path().string();
1272 std::ofstream out(path, std::ios::trunc);
1273 if (!out.is_open()) {
1274 LOG_ERROR("WebServer: cannot open {} for writing", path);
1275 return false;
1276 }
1277 out << strategy_json.dump(4) << "\n";
1278 LOG_INFO("WebServer: Persisted config for strategy {} to {}", strategy_id, path);
1279 return true;
1280 }
1281 return false;
1282}
1283
1284void WebServer::save_strategy_parameters(const std::string& strategy_id, const nlohmann::json& params) {
1285 if (config_path_.empty()) {
1286 LOG_WARN("WebServer: config_path not set — cannot persist strategy config");
1287 return;
1288 }
1289 try {
1290 std::ifstream in(config_path_);
1291 auto config = json::parse(in);
1292 in.close();
1293
1294 // Preferred layout: one <name>.config.json per strategy in the configs folder.
1295 // Resolve the folder exactly as StrategyManager::load_strategies() does, so we
1296 // write the file that will actually be read back at startup.
1297 if (config.contains("strategies") && config["strategies"].is_object()) {
1298 const auto& strategies = config["strategies"];
1299 const auto plugins_folder = strategies.value("strategy_plugins_folder",
1300 std::string("strategies"));
1301 const auto configs_folder = strategies.value("strategy_configs_folder",
1302 plugins_folder);
1303 if (save_to_strategy_config_file(configs_folder, strategy_id, params)) {
1304 return;
1305 }
1306 }
1307
1308 // Legacy layout: the parameters live inline in a "strategies" array in the
1309 // main config. Only rewrite the file when the strategy is actually in it —
1310 // an unconditional rewrite reports success while persisting nothing.
1311 if (config.contains("strategies") && config["strategies"].is_array()) {
1312 for (auto& s : config["strategies"]) {
1313 if (s.value("name", "") == strategy_id) {
1314 s["parameters"] = params;
1315 std::ofstream out(config_path_);
1316 out << config.dump(2);
1317 LOG_INFO("WebServer: Persisted config for strategy {} to {}",
1318 strategy_id, config_path_);
1319 return;
1320 }
1321 }
1322 }
1323
1324 LOG_WARN("WebServer: no config file found for strategy {} — the running strategy "
1325 "has the new parameters, but they will not survive a restart", strategy_id);
1326 } catch (const std::exception& e) {
1327 LOG_ERROR("WebServer: Failed to save config for strategy {}: {}", strategy_id, e.what());
1328 }
1329}
1330
1331void WebServer::handle_post_halt_strategy(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1332 const std::string& strategy_id, std::string_view body) {
1333 try {
1334 auto halt_data = json::parse(body);
1335 std::string reason = halt_data.value("reason", "Manual halt via API");
1336
1337 risk_manager_.halt_strategy(strategy_id, reason);
1338
1339 LOG_INFO("WebServer: Halted strategy {} - Reason: {}", strategy_id, reason);
1340
1341 json response = {
1342 {"success", true},
1343 {"message", "Strategy halted successfully"},
1344 {"strategy_id", strategy_id},
1345 {"reason", reason}
1346 };
1347
1348 send_json_response(res, response.dump());
1349 } catch (const json::exception& e) {
1350 send_error_response(res, std::string("Invalid JSON: ") + e.what(), 400);
1351 } catch (const std::exception& e) {
1352 send_error_response(res, e.what(), 500);
1353 }
1354}
1355
1356void WebServer::handle_post_resume_strategy(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1357 const std::string& strategy_id) {
1358 try {
1359 risk_manager_.resume_strategy(strategy_id);
1360
1361 LOG_INFO("WebServer: Resumed strategy {}", strategy_id);
1362
1363 json response = {
1364 {"success", true},
1365 {"message", "Strategy resumed successfully"},
1366 {"strategy_id", strategy_id}
1367 };
1368
1369 send_json_response(res, response.dump());
1370 } catch (const std::exception& e) {
1371 send_error_response(res, e.what(), 500);
1372 }
1373}
1374
1375void WebServer::handle_get_orders(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
1376 // Use WebServer-side open_orders_ (accessed only from uWS thread — no data race)
1377 json response = json::array();
1378 for (const auto& [cid, t] : open_orders_) {
1379 response.push_back({
1380 {"strategy_id", t.strategy_id},
1381 {"order_id", t.order_id},
1382 {"client_order_id", t.client_order_id},
1383 {"instrument", t.instrument},
1384 {"side", t.side},
1385 {"type", t.type},
1386 {"price", t.price},
1387 {"qty", t.qty},
1388 {"filled_qty", t.filled_qty},
1389 {"remaining_qty", t.remaining_qty},
1390 {"status", t.status},
1391 {"created_time", t.created_time},
1392 {"last_update_time", t.last_update_time}
1393 });
1394 }
1395 send_json_response(res, response.dump());
1396}
1397
1398void WebServer::handle_delete_order(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1399 const std::string& strategy_id, const std::string& order_id,
1400 std::string_view body) {
1401 try {
1402 auto data = json::parse(body);
1403 if (!data.contains("client_order_id")) {
1404 send_error_response(res, "Missing required field: client_order_id", 400);
1405 return;
1406 }
1407 std::string client_order_id = data["client_order_id"];
1408
1409 auto strategy = strategy_manager_.get_strategy(strategy_id);
1410 if (!strategy) {
1411 send_error_response(res, "Strategy not found", 404);
1412 return;
1413 }
1414
1415 reinterpret_pointer_cast<StrategyBase>(strategy)->cancel_order(order_id, client_order_id);
1416
1417 // The order stays tracked until the broker's ORDER_CANCEL says it's gone: a cancel can be
1418 // refused, or fail on the way, and leave it live. That event tells the UI, with the
1419 // order's details, which went missing when it came after the order was dropped here.
1420
1421 LOG_INFO("WebServer: Cancel order {} for strategy {}", order_id, strategy_id);
1422 send_json_response(res, R"({"success":true,"message":"Cancel request submitted"})", 202);
1423 } catch (const json::exception& e) {
1424 send_error_response(res, std::string("Invalid JSON: ") + e.what(), 400);
1425 } catch (const std::exception& e) {
1426 send_error_response(res, e.what(), 500);
1427 }
1428}
1429
1430void WebServer::handle_put_order(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1431 const std::string& strategy_id, const std::string& order_id,
1432 std::string_view body) {
1433 try {
1434 auto data = json::parse(body);
1435 if (!data.contains("client_order_id")) {
1436 send_error_response(res, "Missing required field: client_order_id", 400);
1437 return;
1438 }
1439
1440 std::string client_order_id = data["client_order_id"];
1441 double new_price = data.value("new_price", std::numeric_limits<double>::quiet_NaN());
1442 double new_quantity = data.value("new_quantity", std::numeric_limits<double>::quiet_NaN());
1443
1444 if (std::isnan(new_price) && std::isnan(new_quantity)) {
1445 send_error_response(res, "At least one of new_price or new_quantity is required", 400);
1446 return;
1447 }
1448
1449 auto strategy = strategy_manager_.get_strategy(strategy_id);
1450 if (!strategy) {
1451 send_error_response(res, "Strategy not found", 404);
1452 return;
1453 }
1454
1455 auto* base = reinterpret_pointer_cast<StrategyBase>(strategy).get();
1456 const Order* existing = base->get_order(client_order_id);
1457 if (!existing) {
1458 send_error_response(res, "Order not found", 404);
1459 return;
1460 }
1461
1462 price_t final_price = std::isnan(new_price) ? existing->price : to_price_t(new_price);
1463 qty_t final_qty = std::isnan(new_quantity) ? existing->qty : to_qty_t(new_quantity);
1464
1465 base->modify_order(client_order_id, final_price, final_qty);
1466
1467 LOG_INFO("WebServer: Modify order {} for strategy {} price={} qty={}",
1468 order_id, strategy_id, from_price_t(final_price), from_qty_t(final_qty));
1469 send_json_response(res, R"({"success":true,"message":"Modify request submitted"})", 202);
1470 } catch (const json::exception& e) {
1471 send_error_response(res, std::string("Invalid JSON: ") + e.what(), 400);
1472 } catch (const std::exception& e) {
1473 send_error_response(res, e.what(), 500);
1474 }
1475}
1476
1477void WebServer::handle_delete_all_orders(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
1478 try {
1479 const auto& strategies = strategy_manager_.get_all_strategies();
1480 int strategy_count = 0;
1481
1482 for (const auto& strategy : strategies) {
1483 reinterpret_pointer_cast<StrategyBase>(strategy)->cancel_all_orders();
1484 ++strategy_count;
1485 }
1486
1487 // Each order stays tracked until its ORDER_CANCEL, as for one cancel.
1488
1489 LOG_INFO("WebServer: Cancel all orders across {} strategies", strategy_count);
1490 json response = {
1491 {"success", true},
1492 {"message", "Cancel all request submitted"},
1493 {"strategies_affected", strategy_count}
1494 };
1495 send_json_response(res, response.dump(), 202);
1496 } catch (const std::exception& e) {
1497 send_error_response(res, e.what(), 500);
1498 }
1499}
1500
1501void WebServer::process_events() {
1502 if (!running_.load(std::memory_order_acquire)) {
1503 return; // Stop polling if server is shutting down
1504 }
1505
1506 // The bus until it is empty, or PROCESS_EVENTS_BUDGET_NS is spent, so ladders keep up with a
1507 // busy feed and the loop still gets back to its sockets. The clock is read every 64 events.
1508 const uint64_t start_ns = get_timestamp_ns();
1509 const uint64_t deadline = start_ns + PROCESS_EVENTS_BUDGET_NS;
1510 for (uint32_t n = 1;; ++n) {
1511 auto record = event_mux_.read(event_cursor_);
1512 if (!record) {
1513 // no event available
1514 break;
1515 }
1516
1517 const Event* event = reinterpret_cast<const Event*>(record.data);
1518 switch(event->type) {
1519 case EventType::LEVEL2_UPDATE: {
1520 const auto* level2_event = reinterpret_cast<const Level2UpdateEvent*>(event);
1521 broadcast_level2_update(*level2_event);
1522 break;
1523 }
1524 case EventType::TRADE:
1525 broadcast_trade(*reinterpret_cast<const TradeEvent*>(event));
1526 break;
1527 case EventType::TOB:
1528 // A mark moved. Many arrive per pass on a busy book and a browser needs
1529 // none of them individually, so they only raise a flag.
1530 pnl_changed_ = true;
1531 break;
1532 case EventType::ORDER_ACK: {
1533 const auto* ack = reinterpret_cast<const OrderAckEvent*>(event);
1534 handle_order_ack(*ack);
1535 break;
1536 }
1537 case EventType::ORDER_FILL: {
1538 const auto* fill = reinterpret_cast<const OrderFillEvent*>(event);
1539 // A broker's replay of its journal at startup is the run before's: the
1540 // positions it may still book reach the dashboard with the PnL.
1541 if (!fill->replayed) {
1542 handle_order_fill(*fill);
1543 }
1544 break;
1545 }
1546 case EventType::ORDER_CANCEL: {
1547 const auto* cancel = reinterpret_cast<const OrderCancelEvent*>(event);
1548 handle_order_cancel(*cancel);
1549 break;
1550 }
1551 case EventType::ORDER_REJECT: {
1552 const auto* reject = reinterpret_cast<const OrderRejectEvent*>(event);
1553 handle_order_reject(*reject);
1554 break;
1555 }
1556 default:
1557 break; // the dashboard shows no other event
1558 }
1559 if (n % 64 == 0 && get_timestamp_ns() >= deadline) {
1560 break;
1561 }
1562 }
1563
1564 if (pnl_changed_) {
1565 const uint64_t now_ns = get_timestamp_ns();
1566 if (now_ns - last_pnl_broadcast_ns_ >= PNL_BROADCAST_INTERVAL_NS) {
1567 pnl_changed_ = false;
1568 last_pnl_broadcast_ns_ = now_ns;
1569 broadcast_pnl_update();
1570 }
1571 }
1572
1573 index_listings();
1574 if (!listings_added_.empty() || releasing_ != 0) {
1575 const uint64_t now_ns = get_timestamp_ns();
1576 send_instruments_added(now_ns);
1577 release_holds(now_ns);
1578 }
1579
1580 check_and_broadcast_broker_status();
1581 if (sim_ && sim_->due(start_ns)) [[unlikely]] {
1582 service_sim(start_ns);
1583 }
1584 close_lagging();
1585
1586 uWS::Loop::get()->defer([this]() { process_events(); });
1587}
1588
1589void WebServer::check_and_broadcast_broker_status() {
1590 auto& reg = BrokerStatusRegistry::instance();
1591 const auto& all = reg.all();
1592 bool changed = false;
1593
1594 for (size_t i = 1; i < all.size(); ++i) {
1595 const auto& s = all[i];
1596 if (!reg.is_registered(static_cast<BrokerId>(i))) continue;
1597 auto& snap = last_broker_status_[i];
1598 bool me = s.md_enabled.load(std::memory_order_acquire);
1599 bool mc = s.md_connected.load(std::memory_order_acquire);
1600 bool oe = s.order_enabled.load(std::memory_order_acquire);
1601 bool oc = s.order_connected.load(std::memory_order_acquire);
1602 if (me != snap.md_enabled || mc != snap.md_connected ||
1603 oe != snap.order_enabled || oc != snap.order_connected) {
1604 snap = {me, mc, oe, oc};
1605 changed = true;
1606 }
1607 }
1608
1609 if (!changed || all_ws_clients_.empty()) return;
1610
1611 json brokers = json::array();
1612 for (size_t i = 1; i < all.size(); ++i) {
1613 const auto& s = all[i];
1614 if (!reg.is_registered(static_cast<BrokerId>(i))) continue;
1615 brokers.push_back({
1616 {"id", i},
1617 {"name", s.name},
1618 {"md", {
1619 {"enabled", last_broker_status_[i].md_enabled},
1620 {"connected", last_broker_status_[i].md_connected}
1621 }},
1622 {"order", {
1623 {"enabled", last_broker_status_[i].order_enabled},
1624 {"connected", last_broker_status_[i].order_connected}
1625 }}
1626 });
1627 }
1628
1629 const std::string msg = json{{"type", "broker_status"}, {"brokers", brokers}}.dump();
1630 for (auto* ws : all_ws_clients_) {
1631 send_text(ws, msg);
1632 }
1633}
1634
1635std::string_view WebServer::environment() const {
1636 const std::string_view sim = sim_ ? sim_->control().environment() : std::string_view();
1637 return sim.empty() ? std::string_view(environment_) : sim;
1638}
1639
1640void WebServer::make_health_json() {
1641 health_json_ = json{{"status", "ok"},
1642 {"version", SLICK_TRADER_VERSION},
1643 {"environment", environment()},
1644 {"production", is_production_environment(environment())}}.dump();
1645}
1646
1647std::string WebServer::sim_json(std::string_view type) const {
1648 json out = sim_ ? sim_->control().to_json() : json::object();
1649 out["enabled"] = sim_ != nullptr;
1650 out["environment"] = environment();
1651 if (sim_) {
1652 out["address"] = sim_->address();
1653 }
1654 if (!type.empty()) {
1655 out["type"] = type;
1656 }
1657 return dump_lossy(out);
1658}
1659
1660void WebServer::service_sim(uint64_t now_ns) {
1661 auto& control = sim_->control();
1662 const std::string_view was = environment();
1663 sim_->service(now_ns);
1664 if (environment() != was) {
1665 LOG_WARN("Environment: {} (not production)", environment());
1666 make_health_json();
1667 }
1668
1669 const bool changed = control.take_changed();
1670 const auto answer = control.take_replay_answer();
1671 if (all_ws_clients_.empty()) {
1672 return;
1673 }
1674 if (changed) {
1675 broadcast(sim_json("sim_status"));
1676 }
1677 if (answer) {
1678 broadcast(dump_lossy(json{{"type", "sim_replay"}, {"ok", answer->ok}, {"message", answer->text}}));
1679 }
1680}
1681
1682void WebServer::handle_post_sim_replay(uWS::HttpResponse<false>* res) {
1683 if (!sim_) {
1684 send_error_response(res, "Not a Sim environment", 404);
1685 return;
1686 }
1687 auto& control = sim_->control();
1688 if (!control.start_replay(get_timestamp_ns())) {
1689 send_error_response(res, control.start_blocked(), control.connected() ? 409 : 503);
1690 return;
1691 }
1692 LOG_INFO("WebServer: Replay start sent to slick-sim at {}", sim_->address());
1693 send_json_response(res, R"({"success":true,"message":"Replay start sent"})", 202);
1694}
1695
1696void WebServer::broadcast_level2_update(const Level2UpdateEvent& event) {
1697 const auto& clients = level2_streams_.apply(event);
1698
1699 // Most books have no watcher, as a page watches its ladder's alone. Skip the JSON for them.
1700 if (clients.empty()) {
1701 return;
1702 }
1703 write_level2_message(level2_message_, std::string_view(event.instrument), event.event_time_ns,
1704 event.sequence_num, event.is_snapshot, [&](auto&& emit) {
1705 for (uint16_t i = 0; i < event.num_levels; ++i) {
1706 emit(event.levels[i].price, event.levels[i].quantity, event.levels[i].side);
1707 }
1708 });
1709 for (auto* ws : clients) {
1710 send_text(ws, level2_message_);
1711 }
1712}
1713
1714void WebServer::broadcast_trade(const TradeEvent& event) {
1715 const auto& clients = level2_streams_.trade(event);
1716 if (clients.empty()) {
1717 return;
1718 }
1719 write_trade_message(trade_message_, std::string_view(event.instrument),
1720 LastTrade{event.price, event.quantity, event.side});
1721 for (auto* ws : clients) {
1722 send_text(ws, trade_message_);
1723 }
1724}
1725
1726void WebServer::handle_workspace_change(uWS::HttpResponse<false>* res, std::string_view body,
1727 WorkspaceChange change) {
1728 const json request = json::parse(body, nullptr, false);
1729 const auto name = request.is_object() ? request.find("name") : request.end();
1730 if (!request.is_object() || name == request.end() || !name->is_string()) {
1731 send_error_response(res, "expected {\"name\":<workspace>}", 400);
1732 return;
1733 }
1734 const auto& key = name->get_ref<const std::string&>();
1735 WorkspaceStore::Result result;
1736 switch (change) {
1737 case WorkspaceChange::SAVE: {
1738 const auto windows = request.find("windows");
1739 result = workspaces_.save(key, windows == request.end() ? json() : *windows);
1740 break;
1741 }
1742 case WorkspaceChange::REMOVE: result = workspaces_.remove(key); break;
1743 case WorkspaceChange::USE: result = workspaces_.use(key); break;
1744 }
1745 if (!result.ok()) {
1746 send_error_response(res, result.error, result.status);
1747 return;
1748 }
1749 send_json_response(res, R"({"status":"ok"})");
1750}
1751
1752void WebServer::handle_get_ladder_config(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
1753 try {
1754 send_json_response(res, ladder_config_.dump());
1755 } catch (const std::exception& e) {
1756 send_error_response(res, e.what(), 500);
1757 }
1758}
1759
1760void WebServer::handle_put_ladder_config(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1761 const std::string& body) {
1762 try {
1763 auto new_config = json::parse(body);
1764
1765 // Validate config structure
1766 if (!new_config.contains("default_qty")) {
1767 send_error_response(res, "Invalid ladder config format: missing required fields", 400);
1768 return;
1769 }
1770
1771 // Update in-memory config
1772 ladder_config_ = new_config;
1773
1774 LOG_INFO("WebServer: Updated ladder config - default_qty: {}",
1775 ladder_config_["default_qty"].get<double>());
1776
1777 json response = {
1778 {"status", "ok"},
1779 {"message", "Ladder config updated successfully"}
1780 };
1781 send_json_response(res, response.dump());
1782
1783 } catch (const json::exception& e) {
1784 send_error_response(res, std::string("Invalid JSON: ") + e.what(), 400);
1785 } catch (const std::exception& e) {
1786 send_error_response(res, e.what(), 500);
1787 }
1788}
1789
1790void WebServer::handle_order_ack(const OrderAckEvent& ack) {
1791 std::string cid(ack.client_order_id);
1792 std::string oid(ack.order_id);
1793
1794 // An ack can come without its client_order_id, as Coinbase's OPEN can: its order_id names the
1795 // order. One that names no order here is kept off the map and the UI.
1796 if (cid.empty()) {
1797 const auto cid_it = oid_to_cid_.find(oid);
1798 if (cid_it == oid_to_cid_.end()) {
1799 return;
1800 }
1801 cid = cid_it->second;
1802 }
1803
1804 // A price or qty of 0 (or NULL_PRICE) is one the ack didn't know: the tracked one stands, and
1805 // goes out. An ack that changes nothing tracked, a broker repeating itself, goes out not at all.
1806 const bool has_price = ack.price != NULL_PRICE && ack.price != 0;
1807 const std::string status(to_string(ack.status));
1808 double price = has_price ? from_price_t(ack.price) : 0.0;
1809 double qty = from_qty_t(ack.quantity);
1810 double remaining = qty;
1811 std::string strategy_id;
1812 auto it = open_orders_.find(cid);
1813 if (it != open_orders_.end()) {
1814 // Update existing entry — covers both initial new-order ACK and modify-ack
1815 auto& t = it->second;
1816 const bool changed = (!oid.empty() && t.order_id != oid) || t.status != status ||
1817 (has_price && t.price != price) || (ack.quantity != 0 && t.qty != qty);
1818 if (!oid.empty()) {
1819 t.order_id = oid;
1820 oid_to_cid_[oid] = cid;
1821 }
1822 t.status = status;
1823 t.last_update_time = ack.timestamp_ns;
1824 if (has_price) {
1825 t.price = price;
1826 }
1827 if (ack.quantity != 0) {
1828 t.qty = qty;
1829 t.remaining_qty = qty;
1830 }
1831 if (!changed) {
1832 return;
1833 }
1834 price = t.price;
1835 qty = t.qty;
1836 remaining = t.remaining_qty;
1837 strategy_id = t.strategy_id;
1838 } else if (!oid.empty()) {
1839 // Algo-submitted order: not yet in open_orders_ — create entry now.
1840 // We can derive strategy from client_order_id prefix (name_<timestamp>)
1841 auto sep = cid.rfind('_');
1842 if (sep != std::string::npos) strategy_id = cid.substr(0, sep);
1843
1844 TrackedOrder t;
1845 t.strategy_id = strategy_id;
1846 t.client_order_id = cid;
1847 t.order_id = oid;
1848 t.instrument = std::string(ack.instrument);
1849 t.side = (ack.side == Side::BUY) ? "buy" : "sell";
1850 t.type = static_cast<int>(ack.order_type);
1851 t.price = price;
1852 t.qty = qty;
1853 t.remaining_qty = qty;
1854 t.status = status;
1855 t.created_time = ack.timestamp_ns;
1856 t.last_update_time = ack.timestamp_ns;
1857 open_orders_[cid] = std::move(t);
1858 oid_to_cid_[oid] = cid;
1859 }
1860
1861 // A cancel needs strategy_id and client_order_id, and a ladder's Work column cancels MANUAL's
1862 // orders from what the ack says.
1863 json msg;
1864 msg["type"] = "order_update";
1865 msg["event"] = "ack";
1866 msg["order_id"] = oid;
1867 msg["instrument"] = std::string(ack.instrument);
1868 msg["side"] = (ack.side == Side::BUY) ? "buy" : "sell";
1869 msg["price"] = price;
1870 msg["qty"] = qty;
1871 msg["remaining_qty"] = remaining;
1872 msg["status"] = status;
1873 msg["strategy_id"] = strategy_id;
1874 msg["client_order_id"] = cid;
1875 broadcast(msg.dump());
1876}
1877
1878void WebServer::handle_order_fill(const OrderFillEvent& fill) {
1879 std::string oid(fill.order_id);
1880
1881 if (fill.scope == FillScope::LEG) {
1882 // One leg of a multi-leg order's fill: a position in the leg, and nothing new about
1883 // the order, which its own fill already brought up to date.
1884 json msg;
1885 msg["type"] = "order_update";
1886 msg["event"] = "leg_fill";
1887 msg["order_id"] = oid;
1888 msg["instrument"] = std::string(fill.instrument);
1889 msg["side"] = (fill.side == Side::BUY) ? "buy" : "sell";
1890 msg["fill_price"] = from_price_t(fill.fill_price);
1891 msg["fill_qty"] = from_qty_t(fill.fill_quantity);
1892 msg["fill_id"] = std::string(fill.fill_id);
1893 msg["fee"] = from_price_t(fill.fee_amount);
1894 msg["timestamp_ns"] = uint64_t{fill.timestamp_ns}; // a copy: json binds a reference, and fill is packed
1895 if (const auto cid_it = oid_to_cid_.find(oid); cid_it != oid_to_cid_.end()) {
1896 msg["client_order_id"] = cid_it->second;
1897 if (const auto it = open_orders_.find(cid_it->second); it != open_orders_.end()) {
1898 msg["strategy_id"] = it->second.strategy_id;
1899 }
1900 }
1901 broadcast_fill(msg);
1902 return;
1903 }
1904
1905 // Capture tracked order fields before potential erasure. One not tracked is named by the fill.
1906 std::string instrument(fill.instrument), side(fill.side == Side::BUY ? "buy" : "sell"), fill_status;
1907 std::string strategy_id, client_order_id;
1908 double price = 0.0, qty = 0.0;
1909
1910 auto cid_it = oid_to_cid_.find(oid);
1911 if (cid_it != oid_to_cid_.end()) {
1912 auto it = open_orders_.find(cid_it->second);
1913 if (it != open_orders_.end()) {
1914 instrument = it->second.instrument;
1915 side = it->second.side;
1916 price = it->second.price;
1917 qty = it->second.qty;
1918 strategy_id = it->second.strategy_id;
1919 client_order_id = it->second.client_order_id;
1920
1921 double rem = from_qty_t(fill.remaining_quantity);
1922 it->second.remaining_qty = rem;
1923 it->second.filled_qty = it->second.qty - rem;
1924 it->second.last_update_time = fill.timestamp_ns;
1925 if (rem <= 0.0) {
1926 fill_status = "FILLED";
1927 open_orders_.erase(it);
1928 oid_to_cid_.erase(cid_it);
1929 } else {
1930 fill_status = "PARTIALLY_FILLED";
1931 it->second.status = fill_status;
1932 }
1933 }
1934 }
1935
1936 json msg;
1937 msg["type"] = "order_update";
1938 msg["event"] = "fill";
1939 msg["order_id"] = oid;
1940 msg["instrument"] = instrument;
1941 msg["side"] = side;
1942 msg["price"] = price;
1943 msg["qty"] = qty;
1944 msg["status"] = fill_status;
1945 msg["fill_price"] = from_price_t(fill.fill_price);
1946 msg["fill_qty"] = from_qty_t(fill.fill_quantity);
1947 msg["remaining_qty"] = from_qty_t(fill.remaining_quantity);
1948 msg["fill_id"] = std::string(fill.fill_id);
1949 msg["fee"] = from_price_t(fill.fee_amount);
1950 msg["timestamp_ns"] = uint64_t{fill.timestamp_ns}; // a copy, as above
1951 msg["strategy_id"] = strategy_id;
1952 msg["client_order_id"] = client_order_id;
1953 broadcast_fill(msg);
1954}
1955
1956void WebServer::handle_order_cancel(const OrderCancelEvent& cancel) {
1957 std::string oid(cancel.order_id);
1958
1959 // Capture tracked order fields before erasure
1960 std::string instrument, side;
1961 double price = 0.0, qty = 0.0;
1962 bool tracked = false;
1963
1964 auto cid_it = oid_to_cid_.find(oid);
1965 if (cid_it != oid_to_cid_.end()) {
1966 auto it = open_orders_.find(cid_it->second);
1967 if (it != open_orders_.end()) {
1968 instrument = it->second.instrument;
1969 side = it->second.side;
1970 price = it->second.price;
1971 qty = it->second.qty;
1972 open_orders_.erase(it);
1973 tracked = true;
1974 }
1975 oid_to_cid_.erase(cid_it);
1976 }
1977 // One gone already, as a broker repeating the cancel says: nothing on any window to take off.
1978 if (!tracked) {
1979 LOG_DEBUG("WebServer: cancel of order {}, not open here - not sent on", oid);
1980 return;
1981 }
1982
1983 json msg;
1984 msg["type"] = "order_update";
1985 msg["event"] = "cancel";
1986 msg["order_id"] = oid;
1987 msg["instrument"] = instrument;
1988 msg["side"] = side;
1989 msg["price"] = price;
1990 msg["qty"] = qty;
1991 broadcast(msg.dump());
1992}
1993
1994void WebServer::handle_order_reject(const OrderRejectEvent& reject) {
1995 std::string cid(reject.client_order_id);
1996
1997 // Capture tracked order fields before erasure
1998 std::string instrument, side, order_id;
1999 double price = 0.0, qty = 0.0;
2000
2001 if (!cid.empty()) {
2002 auto it = open_orders_.find(cid);
2003 if (it != open_orders_.end()) {
2004 instrument = it->second.instrument;
2005 side = it->second.side;
2006 price = it->second.price;
2007 qty = it->second.qty;
2008 order_id = it->second.order_id;
2009 if (!order_id.empty()) oid_to_cid_.erase(order_id);
2010 open_orders_.erase(it);
2011 }
2012 }
2013
2014 json msg;
2015 msg["type"] = "order_update";
2016 msg["event"] = "reject";
2017 msg["order_id"] = order_id;
2018 msg["instrument"] = instrument;
2019 msg["side"] = side;
2020 msg["price"] = price;
2021 msg["qty"] = qty;
2022 msg["reason"] = std::string(reject.reason);
2023 broadcast(dump_lossy(msg)); // the broker's text, cut to fit
2024}
2025
2026void WebServer::broadcast_fill(json& message) {
2027 const std::string& text = fills_.push(message);
2028 for (auto* ws : all_ws_clients_) {
2029 send_text(ws, text);
2030 }
2031}
2032
2033void WebServer::handle_get_fills(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
2034 std::string body;
2035 fills_.write_json(body);
2036 send_json_response(res, body);
2037}
2038
2039void WebServer::index_listings() {
2040 const auto* manual = strategy_manager_.manual();
2041 if (manual == nullptr || manual->listed_count() == listings_indexed_) {
2042 return;
2043 }
2044 listings_indexed_ = manual->for_each_listed(listings_indexed_, [&](BrokerId broker, std::string_view instrument,
2045 price_t tick_size, qty_t min_qty) {
2046 auto [it, added] = listings_.try_emplace(std::string(instrument), Listing{broker, tick_size, false, min_qty});
2047 if (added) {
2048 listings_added_.push_back(&it->first);
2049 } else if (it->second.broker == broker && ((it->second.tick_size == 0 && tick_size != 0) ||
2050 (it->second.min_qty == 0 && min_qty != 0))) {
2051 // a strategy's, defined: the ladder takes its tick and its smallest order
2052 if (it->second.tick_size == 0) {
2053 it->second.tick_size = tick_size;
2054 }
2055 if (it->second.min_qty == 0) {
2056 it->second.min_qty = min_qty;
2057 }
2058 listings_added_.push_back(&it->first);
2059 }
2060 });
2061}
2062
2063void WebServer::send_instruments(Socket* ws) {
2064 index_listings();
2065 write_instruments(instruments_message_, "instruments", [&](auto&& emit) {
2066 for (const auto& [instrument, listing] : listings_) {
2067 emit(instrument, listing.broker, listing.tick_size, listing.min_qty);
2068 }
2069 });
2070 send_text(ws, instruments_message_);
2071}
2072
2073void WebServer::send_instruments_added(uint64_t now_ns) {
2074 // At most once per interval: a channel's definitions arrive by the thousand. With no client
2075 // asking, nothing waits: one that asks gets the whole list.
2076 if (listings_added_.empty()) {
2077 return;
2078 }
2079 if (instrument_clients_.empty()) {
2080 listings_added_.clear();
2081 return;
2082 }
2083 if (now_ns - last_instruments_sent_ns_ < INSTRUMENTS_ADDED_INTERVAL_NS) {
2084 return;
2085 }
2086 last_instruments_sent_ns_ = now_ns;
2087 write_instruments(instruments_message_, "instruments_added", [&](auto&& emit) {
2088 for (const std::string* instrument : listings_added_) {
2089 const Listing& listing = listings_.find(*instrument)->second;
2090 emit(*instrument, listing.broker, listing.tick_size, listing.min_qty);
2091 }
2092 });
2093 listings_added_.clear();
2094 for (auto* ws : instrument_clients_) {
2095 send_text(ws, instruments_message_);
2096 }
2097}
2098
2099bool WebServer::watched(std::string_view instrument) {
2100 if (const auto it = ladder_holds_.find(instrument); it != ladder_holds_.end()) {
2101 if (it->second.release_at_ns != 0) {
2102 it->second.release_at_ns = 0; // back within the grace: the stream never stopped
2103 --releasing_;
2104 }
2105 return true;
2106 }
2107 index_listings();
2108 const auto listing = listings_.find(instrument);
2109 if (listing == listings_.end()) {
2110 return true; // a name nobody lists is only watched
2111 }
2112 // Skip what a strategy already streams. It reaches the ladder anyway.
2113 const uint8_t feeds = (listing->second.book ? 0 : LADDER_BOOK) | (listing->second.trades ? 0 : LADDER_TRADES);
2114 if (feeds == 0) {
2115 return true;
2116 }
2117 if (!publish_ladder_subscription(listing->second.broker, instrument, true, feeds)) {
2118 return false;
2119 }
2120 ladder_holds_.try_emplace(std::string(instrument), LadderHold{listing->second.broker, 0});
2121 level2_streams_.renew(instrument);
2122 return true;
2123}
2124
2125void WebServer::unwatched(std::string_view instrument) {
2126 const auto it = ladder_holds_.find(instrument);
2127 if (it != ladder_holds_.end() && it->second.release_at_ns == 0) {
2128 it->second.release_at_ns = get_timestamp_ns() + config_.ladder_release_ns;
2129 ++releasing_;
2130 }
2131}
2132
2133void WebServer::release_holds(uint64_t now_ns) {
2134 if (releasing_ == 0) {
2135 return;
2136 }
2137 for (auto it = ladder_holds_.begin(); it != ladder_holds_.end();) {
2138 const LadderHold hold = it->second;
2139 if (hold.release_at_ns == 0 || now_ns < hold.release_at_ns) {
2140 ++it;
2141 continue;
2142 }
2143 // Kept for another pass if the bus has no room for it now: a release must not be lost.
2144 if (!publish_ladder_subscription(hold.broker, it->first, false)) {
2145 return;
2146 }
2147 level2_streams_.release(it->first);
2148 it = ladder_holds_.erase(it);
2149 --releasing_;
2150 }
2151}
2152
2153bool WebServer::publish_ladder_subscription(BrokerId broker, std::string_view instrument, bool subscribe,
2154 uint8_t feeds) {
2155 if (!config_producer_buffer_) {
2156 LOG_ERROR("WebServer: no bus producer registered, so {} on {} is not {}", instrument, to_string(broker),
2157 subscribe ? "held" : "released");
2158 return false;
2159 }
2160 return EventSerializer::publish<LadderSubscriptionEvent>(
2161 *config_producer_buffer_, [&](LadderSubscriptionEvent& event) {
2162 event.timestamp_ns = get_timestamp_ns();
2163 event.broker_id = broker;
2164 event.set_instrument(instrument);
2165 event.subscribe = subscribe;
2166 event.feeds = feeds;
2167 });
2168}
2169
2170void WebServer::broadcast(std::string_view message) {
2171 for (auto* ws : all_ws_clients_) {
2172 send_text(ws, message);
2173 }
2174}
2175
2176void WebServer::broadcast_pnl_update() {
2177 if (all_ws_clients_.empty()) return;
2178
2179 const uint64_t now_ns = get_timestamp_ns();
2180 auto all_pnl = pnl_calculator_.calculate_all_pnl(now_ns);
2181
2182 json pnl_obj = json::object();
2183 for (const auto& [strategy_id, pnl] : all_pnl) {
2184 pnl_obj[strategy_id] = {
2185 {"realized_pnl", pnl.get_realized()},
2186 {"unrealized_pnl", pnl.get_unrealized()},
2187 {"total_fees", pnl.get_fees()},
2188 {"total_pnl", pnl.get_total()}
2189 };
2190 }
2191
2192 const std::string message = json{{"type", "pnl_update"}, {"pnl", pnl_obj}}.dump();
2193 for (auto* ws : all_ws_clients_) {
2194 send_text(ws, message);
2195 }
2196}
2197
2198} // namespace slick::trader
bool initialize(const json &config, std::string_view environment=PRODUCTION_ENVIRONMENT, const SimControlConfig &sim_control={})
constexpr std::array< std::string_view, 2 > SECURE_POLICY_KEYS
void write_level2_message(std::string &out, std::string_view instrument, uint64_t event_time_ns, uint64_t sequence_num, bool is_snapshot, ForEachLevel &&for_each_level)
double from_price_t(price_t value)
Definition types.hpp:36
price_t to_price_t(double value)
Definition types.hpp:24
void write_trade_message(std::string &out, std::string_view instrument, const LastTrade &trade)
uint64_t get_timestamp_ns()
Definition time.hpp:7
const char * to_string(BrokerId bid)
Definition event.hpp:78
constexpr std::array< std::string_view, 2 > POPUP_POLICY_KEYS
void append_json_number(std::string &out, T value)
constexpr bool streams_book(SubscriptionType type) noexcept
Definition types.hpp:54
constexpr price_t NULL_PRICE
Definition types.hpp:19
int64_t qty_t
Definition types.hpp:17
int64_t price_t
Definition types.hpp:16
void list_origin(const nlohmann::json &config, std::string_view setting, int64_t default_port, std::span< const std::string_view > keys)
bool is_production_environment(std::string_view env) noexcept
nlohmann::json json
double from_qty_t(qty_t value)
Definition types.hpp:40
static constexpr uint32_t producer_id
qty_t to_qty_t(double value)
Definition types.hpp:32
void append_json_string(std::string &out, std::string_view text)
bool enabled() const noexcept