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,
36 }
else if (body.empty()) {
40 handler(std::string_view(body));
49template <
typename ForEach>
50void write_instruments(std::string& out, std::string_view type, ForEach&& for_each) {
51 out.assign(R
"({"type":)");
53 out += R"(,"instruments":{)";
54 const size_t first = out.size();
56 if (out.size() != first) {
73std::string dump_lossy(
const json& value) {
74 return value.dump(-1,
' ',
false, json::error_handler_t::replace);
78std::string_view status_line(
int 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";
89 assert(status == 500 &&
"a status with no reason phrase here");
90 return "500 Internal Server Error";
98 environment_ = environment;
99 sim_ = sim_control.
enabled() ? std::make_unique<SimControlLink>(sim_control) :
nullptr;
101 LOG_INFO(
"WebServer: slick-sim control at {}", sim_->address());
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;
111 if (config.contains(
"ladder_config")) {
112 ladder_config_ = config[
"ladder_config"];
113 LOG_INFO(
"WebServer: Loaded ladder config");
117 {
"default_qty", 0.01},
118 {
"per_instrument", json::object()}
120 LOG_INFO(
"WebServer: Using default ladder config");
123 workspaces_.load(config.value(
"web_server_workspaces_file", std::string(
"state/workspaces.json")));
132 listings_indexed_ = 0;
133 for (
const auto& strategy : strategy_manager_.get_all_strategies()) {
134 if (strategy.get() == strategy_manager_.manual()) {
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;
142 if (
streams_book(sub.type) && sub.broker_id == listing.broker) {
146 listing.trades =
true;
159 const auto config_queue_size = config.value(
"config_queue_size", 1u << 16 );
160 const auto config_control_size = config.value(
"config_control_size", 4096u);
162 uint32_t
producer_id =
static_cast<uint32_t
>(event_mux_.producer_count());
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) {
171 LOG_ERROR(
"WebServer: Could not register the config producer: {}", e.what());
174 LOG_INFO(
"WebServer: Initialized on {}:{}", config_.host, config_.port);
179 if (running_.load(std::memory_order_relaxed)) [[unlikely]] {
180 LOG_WARN(
"WebServer: Already running");
186 if (worker_thread_.joinable()) {
187 worker_thread_.join();
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);
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");
209 const bool was_running = running_.exchange(
false);
212 LOG_INFO(
"WebServer: Stopping");
225 std::lock_guard lock(loop_mutex_);
227 loop_->defer([
this]() { close_connections(); });
232 if (worker_thread_.joinable()) {
233 worker_thread_.join();
237 LOG_INFO(
"WebServer: Stopped");
241void WebServer::run() {
242 LOG_INFO(
"WebServer: Worker thread started");
249 ~AppRetire() { slot_ =
nullptr; }
253 app.listen(config_.port, [
this](
auto* socket) {
255 LOG_INFO(
"WebServer: Listening on port {}", config_.port);
258 uWS::Loop::get()->defer([this]() {
262 LOG_ERROR(
"WebServer: Failed to listen on port {}", config_.port);
263 running_.store(false, std::memory_order_release);
271 std::lock_guard lock(loop_mutex_);
272 loop_ = uWS::Loop::get();
274 if (!running_.load()) {
281 }
catch (
const std::exception& e) {
282 LOG_ERROR(
"WebServer: Exception in worker thread: {}", e.what());
292 std::lock_guard lock(loop_mutex_);
295 LOG_INFO(
"WebServer: Worker thread stopped");
298void WebServer::close_connections() {
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");
315void WebServer::setup_routes(uWS::App &app) {
317 app.get(
"/api/health", [
this](
auto* res,
auto* req) {
318 send_json_response(res, health_json_);
322 app.get(
"/api/sim", [
this](
auto* res,
auto* req) {
323 send_json_response(res, sim_json());
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); });
330 app.get(
"/api/brokers", [
this](
auto* res,
auto* req) {
331 handle_get_brokers(res, req);
335 app.get(
"/api/strategies", [
this](
auto* res,
auto* req) {
336 handle_get_strategies(res, req);
340 app.get(
"/api/positions", [
this](
auto* res,
auto* req) {
341 handle_get_positions(res, req);
345 app.get(
"/api/pnl", [
this](
auto* res,
auto* req) {
346 handle_get_pnl(res, req);
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);
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);
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); });
367 app.get(
"/api/orders", [
this](
auto* res,
auto* req) {
368 handle_get_orders(res, req);
372 app.get(
"/api/fills", [
this](
auto* res,
auto* req) {
373 handle_get_fills(res, req);
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);
381 res->onAborted([]() {});
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); });
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); });
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);
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);
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);
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);
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);
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);
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);
447 app.get(
"/api/ladder-config", [
this](
auto* res,
auto* req) {
448 handle_get_ladder_config(res, req);
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)); });
457 app.get(
"/api/workspaces", [
this](
auto* res,
auto* req) {
458 send_json_response(res, workspaces_.doc().dump());
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); });
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); });
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); });
471 app.ws<
void*>(
"/*", {
472 .maxBackpressure = WS_MAX_BACKPRESSURE,
473 .open = [
this](
auto* ws) {
476 .message = [
this](
auto* ws, std::string_view message, uWS::OpCode opCode) {
477 handle_ws_message(ws, message);
479 .close = [
this](
auto* ws,
int code, std::string_view message) {
485 app.get(
"/*", [
this](
auto* res,
auto* req) {
486 std::string url(req->getUrl());
491 if (url.starts_with(
"/app/")) {
492 res->writeStatus(
"302 Found");
493 res->writeHeader(
"Location",
"/?grouped");
499 if (url ==
"/" || url ==
"") {
504 std::filesystem::path file_path = std::filesystem::path(config_.static_files_path) / url.substr(1);
507 auto canonical_base = std::filesystem::weakly_canonical(config_.static_files_path);
508 auto canonical_path = std::filesystem::weakly_canonical(file_path);
510 if (canonical_path.string().find(canonical_base.string()) != 0) {
511 send_error_response(res,
"Invalid path", 403);
516 if (!std::filesystem::exists(file_path) || !std::filesystem::is_regular_file(file_path)) {
517 send_error_response(res,
"File not found", 404);
522 std::ifstream file(file_path, std::ios::binary);
524 send_error_response(res,
"Failed to read file", 500);
528 std::ostringstream content;
529 content << file.rdbuf();
530 std::string file_content = content.str();
533 std::string content_type =
"application/octet-stream";
534 std::string extension = file_path.extension().string();
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";
546 res->writeStatus(
"200 OK");
547 add_cors_headers(res);
548 res->writeHeader(
"Content-Type", content_type);
551 res->writeHeader(
"Cache-Control",
"no-cache");
552 res->end(file_content);
556void WebServer::handle_get_brokers(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
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;
568 {
"enabled", s.md_enabled.load(std::memory_order_acquire)},
569 {
"connected", s.md_connected.load(std::memory_order_acquire)}
572 {
"enabled", s.order_enabled.load(std::memory_order_acquire)},
573 {
"connected", s.order_connected.load(std::memory_order_acquire)}
577 send_json_response(res, json{{
"brokers", brokers}}.dump());
578 }
catch (
const std::exception& e) {
579 send_error_response(res, e.what(), 500);
583void WebServer::handle_get_strategies(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
585 json response = json::array();
587 const auto& strategies = strategy_manager_.get_all_strategies();
588 for (
const auto& strategy : strategies) {
589 const std::string sname = strategy->name();
591 std::string pause_reason;
592 if (risk_manager_.is_halted(sname)) {
594 pause_reason = risk_manager_.get_halt_reason(sname);
595 }
else if (strategy_manager_.is_auto_paused(sname)) {
597 pause_reason = strategy_manager_.get_auto_pause_reason(sname);
598 }
else if (
auto* base =
dynamic_cast<StrategyBase*
>(strategy.get()); base && base->is_running()) {
608 {
"halt_reason", pause_reason},
609 {
"type", strategy.get() == strategy_manager_.manual() ?
"builtin" :
"plugin"}
613 send_json_response(res, response.dump());
614 }
catch (
const std::exception& e) {
615 send_error_response(res, e.what(), 500);
619void WebServer::handle_get_positions(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
621 auto all_positions = position_tracker_.get_all_positions();
623 json response = json::object();
624 for (
const auto& [strategy_id, positions] : all_positions) {
625 json strategy_positions = json::array();
627 for (
const auto& [instrument, position] : positions) {
628 if (position.is_flat())
continue;
630 const price_t mark = pnl_calculator_.get_mark_price(instrument);
631 const double unrealized = position.get_unrealized_pnl(mark);
633 strategy_positions.push_back({
634 {
"instrument", position.instrument},
638 {
"unrealized_pnl", unrealized},
640 {
"last_update_time", position.last_update_time}
644 if (!strategy_positions.empty()) {
645 response[strategy_id] = strategy_positions;
649 send_json_response(res, response.dump());
650 }
catch (
const std::exception& e) {
651 send_error_response(res, e.what(), 500);
655void WebServer::handle_get_pnl(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
658 auto all_pnl = pnl_calculator_.calculate_all_pnl(now_ns);
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}
671 send_json_response(res, response.dump());
672 }
catch (
const std::exception& e) {
673 send_error_response(res, e.what(), 500);
677void WebServer::handle_get_strategy_positions(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
678 const std::string& strategy_id) {
680 auto positions = position_tracker_.get_all_positions(strategy_id);
682 json response = json::array();
683 for (
const auto& [instrument, position] : positions) {
684 if (position.is_flat())
continue;
687 {
"instrument", position.instrument},
691 {
"last_update_time", position.last_update_time}
695 send_json_response(res, response.dump());
696 }
catch (
const std::exception& e) {
697 send_error_response(res, e.what(), 500);
701void WebServer::handle_get_strategy_pnl(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
702 const std::string& strategy_id) {
705 auto pnl = pnl_calculator_.calculate_pnl(strategy_id, now_ns);
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}
716 send_json_response(res, response.dump());
717 }
catch (
const std::exception& e) {
718 send_error_response(res, e.what(), 500);
722void WebServer::handle_ws_open(uWS::WebSocket<false, true, void*>* ws) {
723 LOG_INFO(
"WebServer: WebSocket connection opened");
724 all_ws_clients_.insert(ws);
728 std::string welcome = R
"({"type":"welcome","message":"Connected to SlickTrader"})";
729 send_text(ws, welcome);
733 send_text(ws, sim_json(
"sim_status"));
737void WebServer::handle_ws_message(uWS::WebSocket<false, true, void*>* ws, std::string_view message) {
741 if (!lagging_.empty() && lagging_.contains(ws)) [[unlikely]] {
745 auto msg = json::parse(message);
746 std::string type = msg.value(
"type",
"");
748 if (type ==
"subscribe") {
749 std::string channel = msg.value(
"channel",
"");
750 std::string instrument = msg.value(
"instrument",
"");
752 if (channel ==
"instruments") {
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);
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);
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"}}
777 {
"type",
"subscribed"},
778 {
"channel", channel},
779 {
"instrument", instrument}
781 send_text(ws, response.dump());
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);
794 true, [&](
auto&& emit) {
796 book->for_each(emit);
799 send_text(ws, level2_message_);
801 if (
const LastTrade* trade = level2_streams_.last_trade(instrument); trade && !stale) {
803 send_text(ws, trade_message_);
806 LOG_WARN(
"WebServer: Invalid subscription request - channel: {}, instrument: {}", channel, instrument);
808 }
else if (type ==
"unsubscribe") {
809 std::string channel = msg.value(
"channel",
"");
810 std::string instrument = msg.value(
"instrument",
"");
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);
818 }
else if (type ==
"ping") {
819 send_text(ws, R
"({"type":"pong"})");
821 LOG_WARN(
"WebServer: Unknown WebSocket message type: {}", type);
823 }
catch (
const std::exception& e) {
824 LOG_ERROR(
"WebServer: Error handling WebSocket message: {}", e.what());
828void WebServer::handle_ws_close(uWS::WebSocket<false, true, void*>* ws) {
830 all_ws_clients_.erase(ws);
831 instrument_clients_.erase(ws);
832 level2_streams_.remove(ws, [
this](std::string_view instrument) { unwatched(instrument); });
835 LOG_INFO(
"WebServer: WebSocket connection closed and cleaned up");
838void WebServer::send_text(Socket* ws, std::string_view message) {
839 if (ws->send(message, uWS::OpCode::TEXT) == Socket::SendStatus::DROPPED) [[unlikely]] {
844void WebServer::close_lagging() {
846 if (lagging_.empty()) [[likely]] {
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);
858void WebServer::send_json_response(uWS::HttpResponse<false>* res,
const std::string& json,
int status) {
861 res->writeStatus(status_line(status));
862 add_cors_headers(res);
863 res->writeHeader(
"Content-Type",
"application/json");
867void WebServer::send_error_response(uWS::HttpResponse<false>* res,
const std::string& error,
int status) {
871 send_json_response(res, dump_lossy(response), status);
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");
882void WebServer::handle_post_order(uWS::HttpResponse<false>* res, uWS::HttpRequest* req, std::string_view body) {
884 auto order_data = json::parse(body);
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);
893 const std::string strategy_id = ManualStrategy::ID;
894 std::string instrument = order_data[
"instrument"];
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"];
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});
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);
916 send_error_response(res, std::format(
"No broker {} in this engine. It has: {}", broker_id_raw,
917 registered.empty() ?
"none" : registered), 400);
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);
927 if (tif_raw < 0 || tif_raw >
static_cast<int64_t
>(TimeInForce::DAY)) {
928 send_error_response(res,
"Invalid time_in_force: must be 0 (GTC), 1 (IOC), 2 (FOK), 3 (GTD) or 4 (DAY)", 400);
935 if (side_str ==
"buy" || side_str ==
"BUY") {
937 }
else if (side_str ==
"sell" || side_str ==
"SELL") {
940 send_error_response(res,
"Invalid side: must be 'buy' or 'sell'", 400);
946 if (order_type ==
"market") {
947 type = OrderType::MARKET;
948 }
else if (order_type ==
"limit") {
949 type = OrderType::LIMIT;
951 send_error_response(res,
"Limit orders require a valid price", 400);
955 send_error_response(res,
"Invalid order type: must be 'market' or 'limit'", 400);
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);
963 auto strategy = strategy_manager_.get_strategy(strategy_id);
965 LOG_ERROR(
"WebServer: strategy {} not found", strategy_id);
966 send_error_response(res,
"Strategy not found", 404);
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()) {
974 send_error_response(res,
"Order rejected: " + refusal, 422);
980 t.strategy_id = strategy_id;
981 t.client_order_id = client_order_id;
982 t.instrument = instrument;
984 t.type =
static_cast<int>(type);
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);
997 {
"message",
"Order submitted successfully"},
999 {
"strategy_id", strategy_id},
1000 {
"instrument", instrument},
1001 {
"broker_id", broker_id_raw},
1003 {
"quantity", quantity},
1004 {
"type", order_type},
1006 {
"time_in_force", tif_raw}
1010 send_json_response(res, response.dump(), 202);
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);
1018void WebServer::handle_post_strategy_control(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1019 const std::string& strategy_id, std::string_view body) {
1021 auto control_data = json::parse(body);
1023 if (!control_data.contains(
"action")) {
1024 send_error_response(res,
"Missing required field: action", 400);
1028 std::string action = control_data[
"action"];
1032 LOG_INFO(
"WebServer: Strategy control request - Strategy: {}, Action: {}", strategy_id, action);
1034 if (action ==
"start" || action ==
"resume") {
1035 bool ok = strategy_manager_.start_strategy(strategy_id);
1037 send_error_response(res,
"Strategy not found: " + strategy_id, 404);
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);
1044 send_error_response(res,
"Strategy not found: " + strategy_id, 404);
1047 send_json_response(res, json{{
"success",
true}, {
"strategy_id", strategy_id}, {
"action", action}}.dump());
1049 send_error_response(res,
"Invalid action: must be 'start', 'stop', 'pause', or 'resume'", 400);
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);
1059void WebServer::handle_get_risk_limits(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1060 const std::string& strategy_id) {
1062 auto limits = risk_manager_.get_limits(strategy_id);
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)}
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)}
1082 response[
"instrument_limits"] = inst_limits;
1085 send_json_response(res, response.dump());
1086 }
catch (
const std::exception& e) {
1087 send_error_response(res, e.what(), 500);
1091void WebServer::handle_put_risk_limits(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1092 const std::string& strategy_id, std::string_view body) {
1094 auto update_data = json::parse(body);
1097 auto limits = risk_manager_.get_limits(strategy_id);
1100 if (update_data.contains(
"max_position_size")) {
1101 limits.max_position_size =
to_qty_t(update_data[
"max_position_size"].get<double>());
1104 if (update_data.contains(
"max_order_value")) {
1105 limits.max_order_value =
to_price_t(update_data[
"max_order_value"].get<double>());
1108 if (update_data.contains(
"max_orders_per_second")) {
1109 limits.max_orders_per_second = update_data[
"max_orders_per_second"].get<uint32_t>();
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>());
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;
1121 if (inst_data.contains(
"max_position_size")) {
1122 inst_limits.max_position_size =
to_qty_t(inst_data[
"max_position_size"].get<double>());
1125 if (inst_data.contains(
"max_order_value")) {
1126 inst_limits.max_order_value =
to_price_t(inst_data[
"max_order_value"].get<double>());
1129 limits.instrument_limits[instrument] = inst_limits;
1134 risk_manager_.set_limits(strategy_id, limits);
1136 LOG_INFO(
"WebServer: Updated risk limits for strategy {}", strategy_id);
1140 {
"message",
"Risk limits updated successfully"},
1141 {
"strategy_id", strategy_id}
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);
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);
1156 send_error_response(res,
"Strategy not found: " + strategy_id, 404);
1159 auto* base =
dynamic_cast<StrategyBase*
>(strategy.get());
1161 send_error_response(res,
"Strategy does not support config", 400);
1164 send_json_response(res, base->get_config().dump(2));
1167void WebServer::handle_put_strategy_config(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1168 const std::string& strategy_id, std::string_view body) {
1170 auto params = json::parse(body);
1171 if (!params.is_object()) {
1172 send_error_response(res,
"Parameters must be a JSON object", 400);
1176 auto strategy = strategy_manager_.get_strategy(strategy_id);
1178 send_error_response(res,
"Strategy not found: " + strategy_id, 404);
1181 auto* base =
dynamic_cast<StrategyBase*
>(strategy.get());
1183 send_error_response(res,
"Strategy does not support config", 400);
1189 if (!publish_strategy_config(strategy_id, params)) {
1190 send_error_response(res,
"Could not publish the config update", 503);
1193 save_strategy_parameters(strategy_id, params);
1195 LOG_INFO(
"WebServer: Published config update for strategy {}", strategy_id);
1199 {
"message",
"Config updated successfully"},
1200 {
"strategy_id", strategy_id}
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);
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 {}",
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);
1223 if (strategy_id.size() >= MAX_STRATEGY_NAME_LENGTH) {
1224 LOG_ERROR(
"WebServer: strategy name '{}' is too long to publish", strategy_id);
1229 const uint32_t size = StrategyConfigEvent::size_for(text.size());
1230 return EventSerializer::publish<StrategyConfigEvent>(
1231 *config_producer_buffer_, size, [&](StrategyConfigEvent& event) {
1233 event.set_strategy(strategy_id);
1234 event.set_config(text);
1241bool WebServer::save_to_strategy_config_file(
const std::string& configs_folder,
1242 const std::string& strategy_id,
1243 const nlohmann::json& params) {
1245 if (configs_folder.empty() || !std::filesystem::exists(configs_folder, ec)) {
1249 for (
const auto& entry : std::filesystem::directory_iterator(configs_folder, ec)) {
1251 if (!entry.is_regular_file())
continue;
1252 if (!entry.path().filename().string().ends_with(
".config.json"))
continue;
1256 std::ifstream in(entry.path());
1257 if (!in.is_open())
continue;
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());
1266 if (strategy_json.value(
"name",
"") != strategy_id)
continue;
1269 strategy_json[
"parameters"] = params;
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);
1277 out << strategy_json.dump(4) <<
"\n";
1278 LOG_INFO(
"WebServer: Persisted config for strategy {} to {}", strategy_id, path);
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");
1290 std::ifstream in(config_path_);
1291 auto config = json::parse(in);
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",
1303 if (save_to_strategy_config_file(configs_folder, strategy_id, params)) {
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_);
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());
1331void WebServer::handle_post_halt_strategy(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1332 const std::string& strategy_id, std::string_view body) {
1334 auto halt_data = json::parse(body);
1335 std::string reason = halt_data.value(
"reason",
"Manual halt via API");
1337 risk_manager_.halt_strategy(strategy_id, reason);
1339 LOG_INFO(
"WebServer: Halted strategy {} - Reason: {}", strategy_id, reason);
1343 {
"message",
"Strategy halted successfully"},
1344 {
"strategy_id", strategy_id},
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);
1356void WebServer::handle_post_resume_strategy(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1357 const std::string& strategy_id) {
1359 risk_manager_.resume_strategy(strategy_id);
1361 LOG_INFO(
"WebServer: Resumed strategy {}", strategy_id);
1365 {
"message",
"Strategy resumed successfully"},
1366 {
"strategy_id", strategy_id}
1369 send_json_response(res, response.dump());
1370 }
catch (
const std::exception& e) {
1371 send_error_response(res, e.what(), 500);
1375void WebServer::handle_get_orders(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
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},
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}
1395 send_json_response(res, response.dump());
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) {
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);
1407 std::string client_order_id = data[
"client_order_id"];
1409 auto strategy = strategy_manager_.get_strategy(strategy_id);
1411 send_error_response(res,
"Strategy not found", 404);
1415 reinterpret_pointer_cast<StrategyBase>(strategy)->cancel_order(order_id, client_order_id);
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);
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) {
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);
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());
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);
1449 auto strategy = strategy_manager_.get_strategy(strategy_id);
1451 send_error_response(res,
"Strategy not found", 404);
1455 auto* base = reinterpret_pointer_cast<StrategyBase>(strategy).get();
1456 const Order* existing = base->get_order(client_order_id);
1458 send_error_response(res,
"Order not found", 404);
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);
1465 base->modify_order(client_order_id, final_price, final_qty);
1467 LOG_INFO(
"WebServer: Modify order {} for strategy {} price={} 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);
1477void WebServer::handle_delete_all_orders(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
1479 const auto& strategies = strategy_manager_.get_all_strategies();
1480 int strategy_count = 0;
1482 for (
const auto& strategy : strategies) {
1483 reinterpret_pointer_cast<StrategyBase>(strategy)->cancel_all_orders();
1489 LOG_INFO(
"WebServer: Cancel all orders across {} strategies", strategy_count);
1492 {
"message",
"Cancel all request submitted"},
1493 {
"strategies_affected", strategy_count}
1495 send_json_response(res, response.dump(), 202);
1496 }
catch (
const std::exception& e) {
1497 send_error_response(res, e.what(), 500);
1501void WebServer::process_events() {
1502 if (!running_.load(std::memory_order_acquire)) {
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_);
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);
1524 case EventType::TRADE:
1525 broadcast_trade(*
reinterpret_cast<const TradeEvent*
>(event));
1527 case EventType::TOB:
1530 pnl_changed_ =
true;
1532 case EventType::ORDER_ACK: {
1533 const auto* ack =
reinterpret_cast<const OrderAckEvent*
>(event);
1534 handle_order_ack(*ack);
1537 case EventType::ORDER_FILL: {
1538 const auto* fill =
reinterpret_cast<const OrderFillEvent*
>(event);
1541 if (!fill->replayed) {
1542 handle_order_fill(*fill);
1546 case EventType::ORDER_CANCEL: {
1547 const auto* cancel =
reinterpret_cast<const OrderCancelEvent*
>(event);
1548 handle_order_cancel(*cancel);
1551 case EventType::ORDER_REJECT: {
1552 const auto* reject =
reinterpret_cast<const OrderRejectEvent*
>(event);
1553 handle_order_reject(*reject);
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();
1574 if (!listings_added_.empty() || releasing_ != 0) {
1576 send_instruments_added(now_ns);
1577 release_holds(now_ns);
1580 check_and_broadcast_broker_status();
1581 if (sim_ && sim_->due(start_ns)) [[unlikely]] {
1582 service_sim(start_ns);
1586 uWS::Loop::get()->defer([
this]() { process_events(); });
1589void WebServer::check_and_broadcast_broker_status() {
1590 auto& reg = BrokerStatusRegistry::instance();
1591 const auto& all = reg.all();
1592 bool changed =
false;
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};
1609 if (!changed || all_ws_clients_.empty())
return;
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;
1619 {
"enabled", last_broker_status_[i].md_enabled},
1620 {
"connected", last_broker_status_[i].md_connected}
1623 {
"enabled", last_broker_status_[i].order_enabled},
1624 {
"connected", last_broker_status_[i].order_connected}
1629 const std::string msg =
json{{
"type",
"broker_status"}, {
"brokers", brokers}}.dump();
1630 for (
auto* ws : all_ws_clients_) {
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;
1640void WebServer::make_health_json() {
1641 health_json_ =
json{{
"status",
"ok"},
1642 {
"version", SLICK_TRADER_VERSION},
1643 {
"environment", environment()},
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();
1652 out[
"address"] = sim_->address();
1654 if (!type.empty()) {
1657 return dump_lossy(out);
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());
1669 const bool changed = control.take_changed();
1670 const auto answer = control.take_replay_answer();
1671 if (all_ws_clients_.empty()) {
1675 broadcast(sim_json(
"sim_status"));
1678 broadcast(dump_lossy(json{{
"type",
"sim_replay"}, {
"ok", answer->ok}, {
"message", answer->text}}));
1682void WebServer::handle_post_sim_replay(uWS::HttpResponse<false>* res) {
1684 send_error_response(res,
"Not a Sim environment", 404);
1687 auto& control = sim_->control();
1689 send_error_response(res, control.start_blocked(), control.connected() ? 409 : 503);
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);
1696void WebServer::broadcast_level2_update(
const Level2UpdateEvent& event) {
1697 const auto& clients = level2_streams_.apply(event);
1700 if (clients.empty()) {
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);
1709 for (
auto* ws : clients) {
1710 send_text(ws, level2_message_);
1714void WebServer::broadcast_trade(
const TradeEvent& event) {
1715 const auto& clients = level2_streams_.trade(event);
1716 if (clients.empty()) {
1720 LastTrade{event.price, event.quantity, event.side});
1721 for (
auto* ws : clients) {
1722 send_text(ws, trade_message_);
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);
1734 const auto& key = name->get_ref<
const std::string&>();
1735 WorkspaceStore::Result result;
1737 case WorkspaceChange::SAVE: {
1738 const auto windows = request.find(
"windows");
1739 result = workspaces_.save(key, windows == request.end() ?
json() : *windows);
1742 case WorkspaceChange::REMOVE: result = workspaces_.remove(key);
break;
1743 case WorkspaceChange::USE: result = workspaces_.use(key);
break;
1746 send_error_response(res, result.error, result.status);
1749 send_json_response(res, R
"({"status":"ok"})");
1752void WebServer::handle_get_ladder_config(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
1754 send_json_response(res, ladder_config_.dump());
1755 }
catch (
const std::exception& e) {
1756 send_error_response(res, e.what(), 500);
1760void WebServer::handle_put_ladder_config(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
1761 const std::string& body) {
1763 auto new_config = json::parse(body);
1766 if (!new_config.contains(
"default_qty")) {
1767 send_error_response(res,
"Invalid ladder config format: missing required fields", 400);
1772 ladder_config_ = new_config;
1774 LOG_INFO(
"WebServer: Updated ladder config - default_qty: {}",
1775 ladder_config_[
"default_qty"].get<double>());
1779 {
"message",
"Ladder config updated successfully"}
1781 send_json_response(res, response.dump());
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);
1790void WebServer::handle_order_ack(
const OrderAckEvent& ack) {
1791 std::string cid(ack.client_order_id);
1792 std::string oid(ack.order_id);
1797 const auto cid_it = oid_to_cid_.find(oid);
1798 if (cid_it == oid_to_cid_.end()) {
1801 cid = cid_it->second;
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;
1810 double remaining = qty;
1811 std::string strategy_id;
1812 auto it = open_orders_.find(cid);
1813 if (it != open_orders_.end()) {
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);
1820 oid_to_cid_[oid] = cid;
1823 t.last_update_time = ack.timestamp_ns;
1827 if (ack.quantity != 0) {
1829 t.remaining_qty = qty;
1836 remaining = t.remaining_qty;
1837 strategy_id = t.strategy_id;
1838 }
else if (!oid.empty()) {
1841 auto sep = cid.rfind(
'_');
1842 if (sep != std::string::npos) strategy_id = cid.substr(0, sep);
1845 t.strategy_id = strategy_id;
1846 t.client_order_id = cid;
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);
1853 t.remaining_qty = qty;
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;
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;
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());
1878void WebServer::handle_order_fill(
const OrderFillEvent& fill) {
1879 std::string oid(fill.order_id);
1881 if (fill.scope == FillScope::LEG) {
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";
1891 msg[
"fill_qty"] =
from_qty_t(fill.fill_quantity);
1892 msg[
"fill_id"] = std::string(fill.fill_id);
1894 msg[
"timestamp_ns"] = uint64_t{fill.timestamp_ns};
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;
1901 broadcast_fill(msg);
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;
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;
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;
1926 fill_status =
"FILLED";
1927 open_orders_.erase(it);
1928 oid_to_cid_.erase(cid_it);
1930 fill_status =
"PARTIALLY_FILLED";
1931 it->second.status = fill_status;
1937 msg[
"type"] =
"order_update";
1938 msg[
"event"] =
"fill";
1939 msg[
"order_id"] = oid;
1940 msg[
"instrument"] = instrument;
1942 msg[
"price"] = price;
1944 msg[
"status"] = fill_status;
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);
1950 msg[
"timestamp_ns"] = uint64_t{fill.timestamp_ns};
1951 msg[
"strategy_id"] = strategy_id;
1952 msg[
"client_order_id"] = client_order_id;
1953 broadcast_fill(msg);
1956void WebServer::handle_order_cancel(
const OrderCancelEvent& cancel) {
1957 std::string oid(cancel.order_id);
1960 std::string instrument, side;
1961 double price = 0.0, qty = 0.0;
1962 bool tracked =
false;
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);
1975 oid_to_cid_.erase(cid_it);
1979 LOG_DEBUG(
"WebServer: cancel of order {}, not open here - not sent on", oid);
1984 msg[
"type"] =
"order_update";
1985 msg[
"event"] =
"cancel";
1986 msg[
"order_id"] = oid;
1987 msg[
"instrument"] = instrument;
1989 msg[
"price"] = price;
1991 broadcast(msg.dump());
1994void WebServer::handle_order_reject(
const OrderRejectEvent& reject) {
1995 std::string cid(reject.client_order_id);
1998 std::string instrument, side, order_id;
1999 double price = 0.0, qty = 0.0;
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);
2015 msg[
"type"] =
"order_update";
2016 msg[
"event"] =
"reject";
2017 msg[
"order_id"] = order_id;
2018 msg[
"instrument"] = instrument;
2020 msg[
"price"] = price;
2022 msg[
"reason"] = std::string(reject.reason);
2023 broadcast(dump_lossy(msg));
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);
2033void WebServer::handle_get_fills(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
2035 fills_.write_json(body);
2036 send_json_response(res, body);
2039void WebServer::index_listings() {
2040 const auto* manual = strategy_manager_.manual();
2041 if (manual ==
nullptr || manual->listed_count() == listings_indexed_) {
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});
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))) {
2052 if (it->second.tick_size == 0) {
2053 it->second.tick_size = tick_size;
2055 if (it->second.min_qty == 0) {
2056 it->second.min_qty = min_qty;
2058 listings_added_.push_back(&it->first);
2063void WebServer::send_instruments(Socket* ws) {
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);
2070 send_text(ws, instruments_message_);
2073void WebServer::send_instruments_added(uint64_t now_ns) {
2076 if (listings_added_.empty()) {
2079 if (instrument_clients_.empty()) {
2080 listings_added_.clear();
2083 if (now_ns - last_instruments_sent_ns_ < INSTRUMENTS_ADDED_INTERVAL_NS) {
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);
2093 listings_added_.clear();
2094 for (
auto* ws : instrument_clients_) {
2095 send_text(ws, instruments_message_);
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;
2108 const auto listing = listings_.find(instrument);
2109 if (listing == listings_.end()) {
2113 const uint8_t feeds = (listing->second.book ? 0 :
LADDER_BOOK) | (listing->second.trades ? 0 : LADDER_TRADES);
2117 if (!publish_ladder_subscription(listing->second.broker, instrument,
true, feeds)) {
2120 ladder_holds_.try_emplace(std::string(instrument), LadderHold{listing->second.broker, 0});
2121 level2_streams_.renew(instrument);
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) {
2133void WebServer::release_holds(uint64_t now_ns) {
2134 if (releasing_ == 0) {
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) {
2144 if (!publish_ladder_subscription(hold.broker, it->first,
false)) {
2147 level2_streams_.release(it->first);
2148 it = ladder_holds_.erase(it);
2153bool WebServer::publish_ladder_subscription(BrokerId broker, std::string_view instrument,
bool subscribe,
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");
2160 return EventSerializer::publish<LadderSubscriptionEvent>(
2161 *config_producer_buffer_, [&](LadderSubscriptionEvent& event) {
2163 event.broker_id = broker;
2164 event.set_instrument(instrument);
2165 event.subscribe = subscribe;
2166 event.feeds = feeds;
2170void WebServer::broadcast(std::string_view message) {
2171 for (
auto* ws : all_ws_clients_) {
2172 send_text(ws, message);
2176void WebServer::broadcast_pnl_update() {
2177 if (all_ws_clients_.empty())
return;
2180 auto all_pnl = pnl_calculator_.calculate_all_pnl(now_ns);
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()}
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);
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)
price_t to_price_t(double value)
void write_trade_message(std::string &out, std::string_view instrument, const LastTrade &trade)
uint64_t get_timestamp_ns()
const char * to_string(BrokerId bid)
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
constexpr price_t NULL_PRICE
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
double from_qty_t(qty_t value)
static constexpr uint32_t producer_id
qty_t to_qty_t(double value)
void append_json_string(std::string &out, std::string_view text)
bool enabled() const noexcept