Repository navigation
Expand file tree
/
Copy pathweb_server.cpp
More file actions
1708 lines (1480 loc) · 64.9 KB
/
Copy pathweb_server.cpp
File metadata and controls
1708 lines (1480 loc) · 64.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <slick-trader/web/web_server.hpp>
#include <slick-trader/core/position_tracker.hpp>
#include <slick-trader/core/pnl_calculator.hpp>
#include <slick-trader/core/risk_manager.hpp>
#include <slick-trader/core/strategy_manager.hpp>
#include <slick-trader/strategy/strategy_base.hpp>
#include <slick-trader/strategy/manual_strategy.hpp>
#include <slick-trader/events/order_event.hpp>
#include <slick-trader/events/quote_event.hpp>
#include <slick-trader/events/strategy_config_event.hpp>
#include <slick-trader/events/event_serializer.hpp>
#include <chrono>
#include <fstream>
#include <sstream>
#include <filesystem>
#include <set>
namespace slick::trader {
bool WebServer::initialize(const json& config) {
config_.port = config.value("web_server_port", 8080);
config_.enable_cors = config.value("web_server_cors", true);
config_.static_files_path = config.value("web_server_static_path", "web/static");
// Load ladder config if present
if (config.contains("ladder_config")) {
ladder_config_ = config["ladder_config"];
LOG_INFO("WebServer: Loaded ladder config");
} else {
// Set defaults if not in config
ladder_config_ = {
{"default_qty", 0.01},
{"per_instrument", json::object()}
};
LOG_INFO("WebServer: Using default ladder config");
}
// Register our producer on the event bus. Strategy parameter updates go out this way so
// the StrategyManager worker applies them on its own thread. add_producer() is setup-only
// and no bus thread has started yet, so here is the place to do it.{
// The id follows the same convention StrategyManager uses for its top-of-book producer:
// one past whatever is already registered. A collision is only possible if a broker
// claimed a sparse id, so scan for a free one rather than letting the throw escape.
const auto config_queue_size = config.value("config_queue_size", 1u << 16 /* 64K */);
const auto config_control_size = config.value("config_control_size", 4096u);
try {
uint32_t producer_id = static_cast<uint32_t>(event_mux_.producer_count());
while (event_mux_.has_producer(producer_id)) {
++producer_id;
}
config_producer_buffer_ = event_mux_.add_producer(producer_id, config_queue_size,
config_control_size);
LOG_INFO("WebServer: Publishing strategy config updates as producer {}", producer_id);
} catch (const std::exception& e) {
// Not fatal: everything except live parameter updates still works.
LOG_ERROR("WebServer: Could not register the config producer: {}", e.what());
}
LOG_INFO("WebServer: Initialized on {}:{}", config_.host, config_.port);
return true;
}
void WebServer::start() {
if (running_.load(std::memory_order_relaxed)) [[unlikely]] {
LOG_WARN("WebServer: Already running");
return;
}
LOG_INFO("WebServer: Starting on port {}", config_.port);
running_.store(true, std::memory_order_release);
worker_thread_ = std::thread(&WebServer::run, this);
LOG_INFO("");
LOG_INFO("Available endpoints:");
LOG_INFO(" GET /api/health - Health check");
LOG_INFO(" GET /api/positions - All positions");
LOG_INFO(" GET /api/positions/:id - Strategy positions");
LOG_INFO(" GET /api/pnl - All PnL snapshots");
LOG_INFO(" GET /api/pnl/:id - Strategy PnL");
LOG_INFO(" GET /api/strategies - Strategy list");
}
void WebServer::stop() {
if (!running_.load(std::memory_order_acquire)) {
return;
}
LOG_INFO("WebServer: Stopping");
running_.store(false, std::memory_order_release);
// Close listen socket to unblock uWS loop
if (listen_socket_) {
us_listen_socket_close(0, listen_socket_);
}
if (worker_thread_.joinable()) {
worker_thread_.join();
}
LOG_INFO("WebServer: Stopped");
}
void WebServer::run() {
LOG_INFO("WebServer: Worker thread started");
try {
uWS::App app;
setup_routes(app);
app.listen(config_.port, [this](auto* socket) {
if (socket) {
listen_socket_ = socket;
LOG_INFO("WebServer: Listening on port {}", config_.port);
// Start polling market data and order events after listen succeeds
uWS::Loop::get()->defer([this]() {
process_events();
});
} else {
LOG_ERROR("WebServer: Failed to listen on port {}", config_.port);
running_.store(false, std::memory_order_release);
}
});
// Run event loop (blocking)
app.run();
} catch (const std::exception& e) {
LOG_ERROR("WebServer: Exception in worker thread: {}", e.what());
}
LOG_INFO("WebServer: Worker thread stopped");
}
void WebServer::setup_routes(uWS::App &app) {
// Health check
app.get("/api/health", [this](auto* res, auto* req) {
send_json_response(res, R"({"status":"ok"})");
});
// Broker status
app.get("/api/brokers", [this](auto* res, auto* req) {
handle_get_brokers(res, req);
});
// Get all strategies
app.get("/api/strategies", [this](auto* res, auto* req) {
handle_get_strategies(res, req);
});
// Get all positions
app.get("/api/positions", [this](auto* res, auto* req) {
handle_get_positions(res, req);
});
// Get all PnL
app.get("/api/pnl", [this](auto* res, auto* req) {
handle_get_pnl(res, req);
});
// Get positions for specific strategy
app.get("/api/positions/:strategy_id", [this](auto* res, auto* req) {
std::string strategy_id(req->getParameter(0));
handle_get_strategy_positions(res, req, strategy_id);
});
// Get PnL for specific strategy
app.get("/api/pnl/:strategy_id", [this](auto* res, auto* req) {
std::string strategy_id(req->getParameter(0));
handle_get_strategy_pnl(res, req, strategy_id);
});
// POST: Submit manual order
app.post("/api/orders", [this](auto* res, auto* req) {
res->onData([this, res](std::string_view data, bool last) {
if (last) {
handle_post_order(res, nullptr, data);
}
});
res->onAborted([]() {});
});
// GET: All open orders across all strategies
app.get("/api/orders", [this](auto* res, auto* req) {
handle_get_orders(res, req);
});
// DELETE: Cancel all open orders (must be registered before the parameterized route)
app.del("/api/orders/cancel-all", [this](auto* res, auto* req) {
res->onData([this, res](std::string_view, bool last) {
if (last) handle_delete_all_orders(res, nullptr);
});
res->onAborted([]() {});
});
// PUT: Modify a specific order
app.put("/api/orders/:strategy_id/:order_id", [this](auto* res, auto* req) {
std::string sid(req->getParameter(0)), oid(req->getParameter(1));
res->onData([this, res, sid, oid](std::string_view data, bool last) {
if (last) handle_put_order(res, nullptr, sid, oid, data);
});
res->onAborted([]() {});
});
// DELETE: Cancel a specific order
app.del("/api/orders/:strategy_id/:order_id", [this](auto* res, auto* req) {
std::string sid(req->getParameter(0)), oid(req->getParameter(1));
res->onData([this, res, sid, oid](std::string_view data, bool last) {
if (last) handle_delete_order(res, nullptr, sid, oid, data);
});
res->onAborted([]() {});
});
// POST: Strategy control (start/stop)
app.post("/api/strategies/:strategy_id/control", [this](auto* res, auto* req) {
std::string strategy_id(req->getParameter(0));
res->onData([this, res, strategy_id](std::string_view data, bool last) {
if (last) {
handle_post_strategy_control(res, nullptr, strategy_id, data);
}
});
res->onAborted([]() {});
});
// GET: Risk limits for strategy
app.get("/api/strategies/:strategy_id/risk", [this](auto* res, auto* req) {
std::string strategy_id(req->getParameter(0));
handle_get_risk_limits(res, req, strategy_id);
});
// PUT: Update risk limits for strategy
app.put("/api/strategies/:strategy_id/risk", [this](auto* res, auto* req) {
std::string strategy_id(req->getParameter(0));
res->onData([this, res, strategy_id](std::string_view data, bool last) {
if (last) {
handle_put_risk_limits(res, nullptr, strategy_id, data);
}
});
res->onAborted([]() {});
});
// GET: Current strategy parameters
app.get("/api/strategies/:strategy_id/config", [this](auto* res, auto* req) {
std::string strategy_id(req->getParameter(0));
handle_get_strategy_config(res, req, strategy_id);
});
// PUT: Update strategy parameters at runtime and persist to config.json
app.put("/api/strategies/:strategy_id/config", [this](auto* res, auto* req) {
std::string strategy_id(req->getParameter(0));
res->onData([this, res, strategy_id](std::string_view data, bool last) {
if (last) {
handle_put_strategy_config(res, nullptr, strategy_id, data);
}
});
res->onAborted([]() {});
});
// POST: Halt strategy
app.post("/api/strategies/:strategy_id/halt", [this](auto* res, auto* req) {
std::string strategy_id(req->getParameter(0));
res->onData([this, res, strategy_id](std::string_view data, bool last) {
if (last) {
handle_post_halt_strategy(res, nullptr, strategy_id, data);
}
});
res->onAborted([]() {});
});
// POST: Resume strategy
app.post("/api/strategies/:strategy_id/resume", [this](auto* res, auto* req) {
std::string strategy_id(req->getParameter(0));
handle_post_resume_strategy(res, req, strategy_id);
});
// GET: Ladder configuration
app.get("/api/ladder-config", [this](auto* res, auto* req) {
handle_get_ladder_config(res, req);
});
// PUT: Update ladder configuration
app.put("/api/ladder-config", [this](auto* res, auto* req) {
auto body_ptr = std::make_shared<std::string>();
res->onData([this, res, body_ptr](std::string_view data, bool last) mutable {
body_ptr->append(data.data(), data.size());
if (last) {
handle_put_ladder_config(res, nullptr, *body_ptr);
}
});
res->onAborted([]() {});
});
// WebSocket endpoint
app.ws<void*>("/*", {
.open = [this](auto* ws) {
handle_ws_open(ws);
},
.message = [this](auto* ws, std::string_view message, uWS::OpCode opCode) {
handle_ws_message(ws, message);
},
.close = [this](auto* ws, int code, std::string_view message) {
handle_ws_close(ws);
}
});
// Static file serving
app.get("/*", [this](auto* res, auto* req) {
std::string url(req->getUrl());
// Default to index.html for root path
if (url == "/" || url == "") {
url = "/index.html";
}
// Construct file path
std::filesystem::path file_path = std::filesystem::path(config_.static_files_path) / url.substr(1);
// Security check: prevent directory traversal
auto canonical_base = std::filesystem::weakly_canonical(config_.static_files_path);
auto canonical_path = std::filesystem::weakly_canonical(file_path);
if (canonical_path.string().find(canonical_base.string()) != 0) {
send_error_response(res, "Invalid path", 403);
return;
}
// Check if file exists
if (!std::filesystem::exists(file_path) || !std::filesystem::is_regular_file(file_path)) {
send_error_response(res, "File not found", 404);
return;
}
// Read file
std::ifstream file(file_path, std::ios::binary);
if (!file) {
send_error_response(res, "Failed to read file", 500);
return;
}
std::ostringstream content;
content << file.rdbuf();
std::string file_content = content.str();
// Determine content type
std::string content_type = "application/octet-stream";
std::string extension = file_path.extension().string();
if (extension == ".html") content_type = "text/html";
else if (extension == ".css") content_type = "text/css";
else if (extension == ".js") content_type = "application/javascript";
else if (extension == ".json") content_type = "application/json";
else if (extension == ".png") content_type = "image/png";
else if (extension == ".jpg" || extension == ".jpeg") content_type = "image/jpeg";
else if (extension == ".svg") content_type = "image/svg+xml";
else if (extension == ".ico") content_type = "image/x-icon";
// Send response
add_cors_headers(res);
res->writeStatus("200 OK");
res->writeHeader("Content-Type", content_type);
res->writeHeader("Cache-Control", "public, max-age=3600");
res->end(file_content);
});
}
void WebServer::handle_get_brokers(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
try {
auto& reg = BrokerStatusRegistry::instance();
json brokers = json::array();
const auto& all = reg.all();
for (size_t i = 1; i < all.size(); ++i) {
const auto& s = all[i];
if (s.name[0] == '\0') continue;
brokers.push_back({
{"id", i},
{"name", s.name},
{"md", {
{"enabled", s.md_enabled.load(std::memory_order_acquire)},
{"connected", s.md_connected.load(std::memory_order_acquire)}
}},
{"order", {
{"enabled", s.order_enabled.load(std::memory_order_acquire)},
{"connected", s.order_connected.load(std::memory_order_acquire)}
}}
});
}
send_json_response(res, json{{"brokers", brokers}}.dump());
} catch (const std::exception& e) {
send_error_response(res, e.what(), 500);
}
}
void WebServer::handle_get_strategies(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
try {
json response = json::array();
const auto& strategies = strategy_manager_.get_all_strategies();
for (const auto& strategy : strategies) {
// Collect unique instruments from all subscriptions
std::set<std::string> instruments_set;
auto subscriptions = strategy->get_subscriptions();
for (const auto& sub : subscriptions) {
for (const auto& instrument : sub.instruments) {
instruments_set.insert(instrument);
}
}
// Convert to array
json instruments_array = json::array();
for (const auto& inst : instruments_set) {
instruments_array.push_back(inst);
}
const std::string sname = strategy->name();
std::string status;
std::string pause_reason;
if (risk_manager_.is_halted(sname)) {
status = "halted";
pause_reason = risk_manager_.get_halt_reason(sname);
} else if (strategy_manager_.is_auto_paused(sname)) {
status = "paused";
pause_reason = strategy_manager_.get_auto_pause_reason(sname);
} else if (auto* base = dynamic_cast<StrategyBase*>(strategy.get()); base && base->is_running()) {
status = "running";
} else {
status = "stopped";
}
response.push_back({
{"name", sname},
{"id", sname},
{"status", status},
{"halt_reason", pause_reason},
{"type", "plugin"},
{"instruments", instruments_array}
});
}
send_json_response(res, response.dump());
} catch (const std::exception& e) {
send_error_response(res, e.what(), 500);
}
}
void WebServer::handle_get_positions(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
try {
auto all_positions = position_tracker_.get_all_positions();
json response = json::object();
for (const auto& [strategy_id, positions] : all_positions) {
json strategy_positions = json::array();
for (const auto& [instrument, position] : positions) {
if (position.is_flat()) continue; // Skip flat positions
const price_t mark = pnl_calculator_.get_mark_price(instrument);
const double unrealized = position.get_unrealized_pnl(mark);
strategy_positions.push_back({
{"instrument", position.instrument},
{"quantity", from_qty_t(position.quantity)},
{"avg_price", from_price_t(position.avg_price)},
{"realized_pnl", from_price_t(position.realized_pnl)},
{"unrealized_pnl", unrealized},
{"mark_price", from_price_t(mark)},
{"last_update_time", position.last_update_time}
});
}
if (!strategy_positions.empty()) {
response[strategy_id] = strategy_positions;
}
}
send_json_response(res, response.dump());
} catch (const std::exception& e) {
send_error_response(res, e.what(), 500);
}
}
void WebServer::handle_get_pnl(uWS::HttpResponse<false>* res, uWS::HttpRequest* req) {
try {
const uint64_t now_ns = get_timestamp_ns();
auto all_pnl = pnl_calculator_.calculate_all_pnl(now_ns);
json response = json::object();
for (const auto& [strategy_id, pnl] : all_pnl) {
response[strategy_id] = {
{"realized_pnl", pnl.get_realized()},
{"unrealized_pnl", pnl.get_unrealized()},
{"total_fees", pnl.get_fees()},
{"total_pnl", pnl.get_total()},
{"timestamp_ns", pnl.timestamp_ns}
};
}
send_json_response(res, response.dump());
} catch (const std::exception& e) {
send_error_response(res, e.what(), 500);
}
}
void WebServer::handle_get_strategy_positions(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
const std::string& strategy_id) {
try {
auto positions = position_tracker_.get_all_positions(strategy_id);
json response = json::array();
for (const auto& [instrument, position] : positions) {
if (position.is_flat()) continue; // Skip flat positions
response.push_back({
{"instrument", position.instrument},
{"quantity", from_qty_t(position.quantity)},
{"avg_price", from_price_t(position.avg_price)},
{"realized_pnl", from_price_t(position.realized_pnl)},
{"last_update_time", position.last_update_time}
});
}
send_json_response(res, response.dump());
} catch (const std::exception& e) {
send_error_response(res, e.what(), 500);
}
}
void WebServer::handle_get_strategy_pnl(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
const std::string& strategy_id) {
try {
const uint64_t now_ns = get_timestamp_ns();
auto pnl = pnl_calculator_.calculate_pnl(strategy_id, now_ns);
json response = {
{"strategy_id", pnl.strategy_id},
{"realized_pnl", pnl.get_realized()},
{"unrealized_pnl", pnl.get_unrealized()},
{"total_fees", pnl.get_fees()},
{"total_pnl", pnl.get_total()},
{"timestamp_ns", pnl.timestamp_ns}
};
send_json_response(res, response.dump());
} catch (const std::exception& e) {
send_error_response(res, e.what(), 500);
}
}
void WebServer::handle_ws_open(uWS::WebSocket<false, true, void*>* ws) {
LOG_INFO("WebServer: WebSocket connection opened");
all_ws_clients_.insert(ws);
// Send welcome message
std::string welcome = R"({"type":"welcome","message":"Connected to SlickTrader"})";
ws->send(welcome, uWS::OpCode::TEXT);
}
void WebServer::handle_ws_message(uWS::WebSocket<false, true, void*>* ws, std::string_view message) {
try {
auto msg = json::parse(message);
std::string type = msg.value("type", "");
if (type == "subscribe") {
std::string channel = msg.value("channel", "");
std::string instrument = msg.value("instrument", "");
if (channel == "level2" && !instrument.empty()) {
level2_subscriptions_[instrument].clients.insert(ws);
LOG_INFO("WebServer: Client subscribed to level2 for {}", instrument);
json response = {
{"type", "subscribed"},
{"channel", channel},
{"instrument", instrument}
};
ws->send(response.dump(), uWS::OpCode::TEXT);
} else {
LOG_WARN("WebServer: Invalid subscription request - channel: {}, instrument: {}", channel, instrument);
}
} else if (type == "unsubscribe") {
std::string channel = msg.value("channel", "");
std::string instrument = msg.value("instrument", "");
if (channel == "level2" && !instrument.empty()) {
auto it = level2_subscriptions_.find(instrument);
if (it != level2_subscriptions_.end()) {
it->second.clients.erase(ws);
LOG_INFO("WebServer: Client unsubscribed from level2 for {}", instrument);
}
}
} else if (type == "ping") {
ws->send(R"({"type":"pong"})", uWS::OpCode::TEXT);
} else {
LOG_WARN("WebServer: Unknown WebSocket message type: {}", type);
}
} catch (const std::exception& e) {
LOG_ERROR("WebServer: Error handling WebSocket message: {}", e.what());
}
}
void WebServer::handle_ws_close(uWS::WebSocket<false, true, void*>* ws) {
// Remove from all connected clients and subscriptions
all_ws_clients_.erase(ws);
for (auto& [instrument, sub] : level2_subscriptions_) {
sub.clients.erase(ws);
}
LOG_INFO("WebServer: WebSocket connection closed and cleaned up");
}
void WebServer::send_json_response(uWS::HttpResponse<false>* res, const std::string& json, int status) {
add_cors_headers(res);
res->writeStatus(std::to_string(status));
res->writeHeader("Content-Type", "application/json");
res->end(json);
}
void WebServer::send_error_response(uWS::HttpResponse<false>* res, const std::string& error, int status) {
json response = {
{"error", error}
};
send_json_response(res, response.dump(), status);
}
void WebServer::add_cors_headers(uWS::HttpResponse<false>* res) {
if (config_.enable_cors) {
res->writeHeader("Access-Control-Allow-Origin", "*");
res->writeHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res->writeHeader("Access-Control-Allow-Headers", "Content-Type");
}
}
void WebServer::handle_post_order(uWS::HttpResponse<false>* res, uWS::HttpRequest* req, std::string_view body) {
try {
auto order_data = json::parse(body);
// Validate required fields
if (!order_data.contains("instrument") ||
!order_data.contains("side") || !order_data.contains("quantity") || !order_data.contains("broker_id")) {
send_error_response(res, "Missing required fields: instrument, broker_id, side, quantity", 400);
return;
}
const std::string strategy_id = ManualStrategy::ID;
std::string instrument = order_data["instrument"];
uint8_t broker_id_raw = order_data["broker_id"];
std::string side_str = order_data["side"];
double quantity = order_data["quantity"];
// Optional fields
std::string order_type = order_data.value("type", "market");
double price = order_data.value("price", std::numeric_limits<double>::quiet_NaN());
uint8_t tif_raw = order_data.value("time_in_force", 0); // Default to GTC
// Validate broker_id
BrokerId broker_id = static_cast<BrokerId>(broker_id_raw);
if (broker_id == BrokerId::UNKNOWN || broker_id >= BrokerId::_BROKER_ID_COUNT_) {
send_error_response(res, "Invalid broker_id: must be 1 (Coinbase), 2 (Alpaca), 3 (Hyperliquid), 4 (Simulated) or 5 (CME)", 400);
return;
}
// Validate time_in_force
TimeInForce tif = static_cast<TimeInForce>(tif_raw);
if (tif_raw > static_cast<uint8_t>(TimeInForce::DAY)) { // Valid range is 0-4
send_error_response(res, "Invalid time_in_force: must be 0 (GTC), 1 (IOC), 2 (FOK), 3 (GTD) or 4 (DAY)", 400);
return;
}
// Validate side
Side side;
if (side_str == "buy" || side_str == "BUY") {
side = Side::BUY;
} else if (side_str == "sell" || side_str == "SELL") {
side = Side::SELL;
} else {
send_error_response(res, "Invalid side: must be 'buy' or 'sell'", 400);
return;
}
// Validate order type
OrderType type;
if (order_type == "market") {
type = OrderType::MARKET;
} else if (order_type == "limit") {
type = OrderType::LIMIT;
if (price <= 0.0) {
send_error_response(res, "Limit orders require a valid price", 400);
return;
}
} else {
send_error_response(res, "Invalid order type: must be 'market' or 'limit'", 400);
return;
}
// Submit the order through the strategy
LOG_INFO("WebServer: Manual order request - Strategy: {}, Instrument: {}, Broker: {}, Side: {}, {}@{}, Type: {}, TIF: {}",
strategy_id, instrument, static_cast<int>(broker_id), side_str, quantity, price, order_type, tif_raw);
auto strategy = strategy_manager_.get_strategy(strategy_id);
if (!strategy) {
LOG_ERROR("WebServer: strategy {} not found", strategy_id);
send_error_response(res, "Strategy not found", 404);
return;
}
std::string client_order_id = reinterpret_pointer_cast<StrategyBase>(strategy)->submit_order(
instrument, broker_id, side, to_qty_t(quantity), type, to_price_t(price), tif);
// Seed WebServer-side tracking so handle_get_orders() can return it immediately
if (!client_order_id.empty()) {
TrackedOrder t;
t.strategy_id = strategy_id;
t.client_order_id = client_order_id;
t.instrument = instrument;
t.side = side_str;
t.type = static_cast<int>(type);
t.price = price;
t.qty = quantity;
t.remaining_qty = quantity;
t.status = "PENDING_NEW";
t.created_time = static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now().time_since_epoch()).count());
t.last_update_time = t.created_time;
open_orders_[client_order_id] = std::move(t);
}
json response = {
{"success", true},
{"message", "Order submitted successfully"},
{"order", {
{"strategy_id", strategy_id},
{"instrument", instrument},
{"broker_id", broker_id_raw},
{"side", side_str},
{"quantity", quantity},
{"type", order_type},
{"price", price},
{"time_in_force", tif_raw}
}}
};
send_json_response(res, response.dump(), 202); // 202 Accepted
} catch (const json::exception& e) {
send_error_response(res, std::string("Invalid JSON: ") + e.what(), 400);
} catch (const std::exception& e) {
send_error_response(res, e.what(), 500);
}
}
void WebServer::handle_post_strategy_control(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
const std::string& strategy_id, std::string_view body) {
try {
auto control_data = json::parse(body);
if (!control_data.contains("action")) {
send_error_response(res, "Missing required field: action", 400);
return;
}
std::string action = control_data["action"];
// TODO: Implement actual strategy control
// For now, just log and return
LOG_INFO("WebServer: Strategy control request - Strategy: {}, Action: {}", strategy_id, action);
if (action == "start" || action == "resume") {
bool ok = strategy_manager_.start_strategy(strategy_id);
if (!ok) {
send_error_response(res, "Strategy not found: " + strategy_id, 404);
return;
}
send_json_response(res, json{{"success", true}, {"strategy_id", strategy_id}, {"action", action}}.dump());
} else if (action == "stop" || action == "pause") {
bool ok = strategy_manager_.stop_strategy(strategy_id);
if (!ok) {
send_error_response(res, "Strategy not found: " + strategy_id, 404);
return;
}
send_json_response(res, json{{"success", true}, {"strategy_id", strategy_id}, {"action", action}}.dump());
} else {
send_error_response(res, "Invalid action: must be 'start', 'stop', 'pause', or 'resume'", 400);
}
} catch (const json::exception& e) {
send_error_response(res, std::string("Invalid JSON: ") + e.what(), 400);
} catch (const std::exception& e) {
send_error_response(res, e.what(), 500);
}
}
void WebServer::handle_get_risk_limits(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
const std::string& strategy_id) {
try {
auto limits = risk_manager_.get_limits(strategy_id);
json response = {
{"strategy_id", strategy_id},
{"max_position_size", from_qty_t(limits.max_position_size)},
{"max_order_value", from_price_t(limits.max_order_value)},
{"max_orders_per_second", limits.max_orders_per_second},
{"max_loss_per_strategy", from_price_t(limits.max_loss_per_strategy)},
{"halted", risk_manager_.is_halted(strategy_id)}
};
// Add per-instrument limits if any
if (!limits.instrument_limits.empty()) {
json inst_limits = json::object();
for (const auto& [instrument, inst_limit] : limits.instrument_limits) {
inst_limits[instrument] = {
{"max_position_size", from_qty_t(inst_limit.max_position_size)},
{"max_order_value", from_price_t(inst_limit.max_order_value)}
};
}
response["instrument_limits"] = inst_limits;
}
send_json_response(res, response.dump());
} catch (const std::exception& e) {
send_error_response(res, e.what(), 500);
}
}
void WebServer::handle_put_risk_limits(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
const std::string& strategy_id, std::string_view body) {
try {
auto update_data = json::parse(body);
// Get current limits
auto limits = risk_manager_.get_limits(strategy_id);
// Update provided fields
if (update_data.contains("max_position_size")) {
limits.max_position_size = to_qty_t(update_data["max_position_size"].get<double>());
}
if (update_data.contains("max_order_value")) {
limits.max_order_value = to_price_t(update_data["max_order_value"].get<double>());
}
if (update_data.contains("max_orders_per_second")) {
limits.max_orders_per_second = update_data["max_orders_per_second"].get<uint32_t>();
}
if (update_data.contains("max_loss_per_strategy")) {
limits.max_loss_per_strategy = to_price_t(update_data["max_loss_per_strategy"].get<double>());
}
// Update per-instrument limits
if (update_data.contains("instrument_limits") && update_data["instrument_limits"].is_object()) {
for (const auto& [instrument, inst_data] : update_data["instrument_limits"].items()) {
InstrumentRiskLimits inst_limits;
if (inst_data.contains("max_position_size")) {
inst_limits.max_position_size = to_qty_t(inst_data["max_position_size"].get<double>());
}
if (inst_data.contains("max_order_value")) {
inst_limits.max_order_value = to_price_t(inst_data["max_order_value"].get<double>());
}
limits.instrument_limits[instrument] = inst_limits;
}
}
// Apply updated limits
risk_manager_.set_limits(strategy_id, limits);
LOG_INFO("WebServer: Updated risk limits for strategy {}", strategy_id);
json response = {
{"success", true},
{"message", "Risk limits updated successfully"},
{"strategy_id", strategy_id}
};
send_json_response(res, response.dump());
} catch (const json::exception& e) {
send_error_response(res, std::string("Invalid JSON: ") + e.what(), 400);
} catch (const std::exception& e) {
send_error_response(res, e.what(), 500);
}
}
void WebServer::handle_get_strategy_config(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
const std::string& strategy_id) {
auto strategy = strategy_manager_.get_strategy(strategy_id);
if (!strategy) {
send_error_response(res, "Strategy not found: " + strategy_id, 404);
return;
}
auto* base = dynamic_cast<StrategyBase*>(strategy.get());
if (!base) {
send_error_response(res, "Strategy does not support config", 400);
return;
}
send_json_response(res, base->get_config().dump(2));
}
void WebServer::handle_put_strategy_config(uWS::HttpResponse<false>* res, uWS::HttpRequest* req,
const std::string& strategy_id, std::string_view body) {
try {
auto params = json::parse(body);
if (!params.is_object()) {
send_error_response(res, "Parameters must be a JSON object", 400);
return;
}
auto strategy = strategy_manager_.get_strategy(strategy_id);
if (!strategy) {
send_error_response(res, "Strategy not found: " + strategy_id, 404);
return;
}
auto* base = dynamic_cast<StrategyBase*>(strategy.get());
if (!base) {
send_error_response(res, "Strategy does not support config", 400);
return;
}
// Hand the update to the worker thread rather than calling set_config() from here:
// a strategy's on_config() may touch state that only its own thread owns.
if (!publish_strategy_config(strategy_id, params)) {
send_error_response(res, "Could not publish the config update", 503);
return;
}
save_strategy_parameters(strategy_id, params);
LOG_INFO("WebServer: Published config update for strategy {}", strategy_id);
json response = {
{"success", true},
{"message", "Config updated successfully"},
{"strategy_id", strategy_id}
};
send_json_response(res, response.dump());
} catch (const json::exception& e) {
send_error_response(res, std::string("Invalid JSON: ") + e.what(), 400);
} catch (const std::exception& e) {
send_error_response(res, e.what(), 500);
}
}
bool WebServer::publish_strategy_config(const std::string& strategy_id, const nlohmann::json& params) {
if (!config_producer_buffer_) {
LOG_ERROR("WebServer: no config producer registered — cannot publish an update for {}",
strategy_id);
return false;
}
const std::string text = params.dump();
if (text.size() > MAX_STRATEGY_CONFIG_LENGTH) {
LOG_ERROR("WebServer: config for {} is {} bytes, over the {} byte limit",
strategy_id, text.size(), MAX_STRATEGY_CONFIG_LENGTH);
return false;
}
if (strategy_id.size() >= MAX_STRATEGY_NAME_LENGTH) {
LOG_ERROR("WebServer: strategy name '{}' is too long to publish", strategy_id);
return false;
}
// Trailing flexible array, so the published size covers the header plus the JSON text.
const uint32_t size = StrategyConfigEvent::size_for(text.size());
return EventSerializer::publish<StrategyConfigEvent>(
*config_producer_buffer_, size, [&](StrategyConfigEvent& event) {
event.timestamp_ns = get_timestamp_ns();
event.set_strategy(strategy_id);
event.set_config(text);
});
}
// Mirrors StrategyManager::load_strategies(): the per-strategy files live in
// strategy_configs_folder as *.config.json and are keyed by the "name" INSIDE the
// file, not by the filename, so that is what we match on here.
bool WebServer::save_to_strategy_config_file(const std::string& configs_folder,
const std::string& strategy_id,
const nlohmann::json& params) {
std::error_code ec;
if (configs_folder.empty() || !std::filesystem::exists(configs_folder, ec)) {
return false;
}
for (const auto& entry : std::filesystem::directory_iterator(configs_folder, ec)) {
if (ec) break;
if (!entry.is_regular_file()) continue;
if (!entry.path().filename().string().ends_with(".config.json")) continue;
json strategy_json;
{
std::ifstream in(entry.path());
if (!in.is_open()) continue;
try {
strategy_json = json::parse(in);
} catch (const json::exception& e) {
LOG_WARN("WebServer: skipping unparsable strategy config {}: {}",
entry.path().filename().string(), e.what());
continue;
}
}
if (strategy_json.value("name", "") != strategy_id) continue;
// Only the parameters block is ours; enabled and risk_limits stay as written.