Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
strategy_manager.cpp
Go to the documentation of this file.
1#include <slick/logger.hpp>
6#include <algorithm>
7#include <cassert>
8#include <cstring>
9#include <filesystem>
10#include <fstream>
11#include <limits>
12#include <new>
13#include <ranges>
14
15using namespace slick;
16using namespace slick::trader;
17
19 const json& config,
20 PositionTracker& position_tracker,
21 PnLCalculator& pnl_calculator,
22 RiskManager& risk_manager,
23 slick::stream_buffer_multiplexer& event_mux,
24 MdRequestQueues& md_request_queues,
25 slick::queue<uint8_t>& order_request_queue
26)
27 : reader_stall_timeout_(config.value("md_request_stall_timeout_ms", 5000))
28 , position_tracker_(position_tracker)
29 , pnl_calculator_(pnl_calculator)
30 , risk_manager_(risk_manager)
31 , event_mux_(event_mux)
32 , md_request_queues_(md_request_queues)
33 , order_request_queue_(order_request_queue)
34 , tob_producer_buffer_(
35 event_mux.add_producer(
36 event_mux.producer_count(),
37 config.value("TOB_queue_size", 1048576),
38 config.value("TOB_control_size", 65536),
39 config.contains("TOB_shm_name") ? config["TOB_shm_name"].get_ref<const std::string&>().c_str() : nullptr
40 ))
41{
42 // Each queue's write index. The connectors were made before this manager and nothing else
43 // publishes requests, so it is where each starts reading.
44 for (size_t i = 0; i < BROKER_COUNT; ++i) {
45 if (const auto* queue = md_request_queues_.find(static_cast<BrokerId>(i))) {
46 request_baseline_[i] = queue->initial_reading_index();
47 }
48 }
49}
50
51// ========================================================================
52// Strategy Loading (Dynamic Discovery)
53// ========================================================================
55
56 auto strategy_plugins_folder = config.value("strategy_plugins_folder", "strategies");
57 auto strategy_configs_folder = config.value("strategy_configs_folder", strategy_plugins_folder);
58
59 // Check if folder exists
60 if (!std::filesystem::exists(strategy_plugins_folder)) {
61 LOG_WARN("⚠ Strategy plugins folder does not exist: {}", strategy_plugins_folder);
62 LOG_WARN("⚠ Creating folder...");
63 std::filesystem::create_directories(strategy_plugins_folder);
64 }
65
66 LOG_INFO("Loading strategies from strategy plugins folder: {} ...", strategy_plugins_folder);
67
68 std::unordered_map<std::string, StrategyConfig> strategy_configs;
69
70 // look for strategy-specific config files in strategy configs folder
71 // Format: <strategy_name>.config.json
72 if (std::filesystem::exists(strategy_configs_folder)) {
73 try {
74 for (const auto& entry : std::filesystem::directory_iterator(strategy_configs_folder)) {
75 if (entry.is_regular_file()) {
76 const auto& path = entry.path();
77 std::string filename = path.filename().string();
78
79 // Check if it's a strategy config file (*.config.json)
80 if (filename.ends_with(".config.json")) {
81 std::ifstream config_file(path);
82 if (config_file.is_open()) {
83 try {
84 json strategy_json = json::parse(config_file);
85 auto strategy_config = StrategyConfig::from_json(strategy_json);
86
87 if (!strategy_config.name.empty()) {
88 // Strategy-specific file takes precedence over main config
89 strategy_configs[strategy_config.name] = strategy_config;
90 LOG_INFO("Loaded config for strategy '{}' from {}", strategy_config.name, filename);
91 }
92 } catch (const json::exception& e) {
93 LOG_WARN("Failed to parse strategy config file {}: {}",
94 filename, e.what());
95 }
96 }
97 }
98 }
99 }
100 } catch (const std::filesystem::filesystem_error& e) {
101 LOG_WARN("Failed to scan for strategy config files: {}", e.what());
102 }
103 }
104 else {
105 LOG_WARN("Strategy configs folder does not exist: {}", strategy_configs_folder);
106 }
107
108 const std::string plugin_extension(PLUGIN_EXTENSION);
109
110 // Scan folder for all plugin files
111 std::vector<std::string> plugin_paths;
112 try {
113 for (const auto& entry : std::filesystem::directory_iterator(strategy_plugins_folder)) {
114 if (entry.is_regular_file()) {
115 const auto& path = entry.path();
116 if (path.extension() == plugin_extension) {
117 plugin_paths.push_back(path.string());
118 }
119 }
120 }
121 } catch (const std::filesystem::filesystem_error& e) {
122 LOG_ERROR("Failed to scan strategy folder: {}", e.what());
123 }
124
125 if (plugin_paths.empty()) {
126 LOG_WARN("⚠ No strategy plugins found in: {}", strategy_configs_folder);
127 LOG_WARN("⚠ Looking for files with extension: {}", plugin_extension);
128 } else {
129 LOG_INFO("Found {} plugin file(s) in {}", plugin_paths.size(), strategy_configs_folder);
130
131 // Sort for deterministic loading order
132 std::sort(plugin_paths.begin(), plugin_paths.end());
133
134 // Load each plugin
135 for (const auto& plugin_path : plugin_paths) {
136 auto strategy = loader_.load(plugin_path);
137 if (strategy) {
138 std::string strategy_name = strategy->name();
139
140 // Check if strategy is enabled in config (default: enabled)
141 bool enabled = true;
142 auto iter = strategy_configs.find(strategy_name);
143 bool has_config = iter != strategy_configs.end();
144 if (has_config) {
145 enabled = iter->second.enabled;
146 } else {
147 LOG_WARN("No config find for strategy {}", strategy_name);
148 }
149
150 if (!enabled) {
151 LOG_INFO("⊘ Strategy {} is disabled in config, skipping", strategy_name);
152 continue;
153 }
154
155 // Initialized whatever its config holds: initialize() hands it the risk manager and
156 // order queue it trades through, and a config with no "parameters" left them null.
157 static const json no_parameters = json::object();
158 const json& params = has_config ? iter->second.parameters : no_parameters;
159 strategy->initialize(params, position_tracker_, pnl_calculator_, risk_manager_, order_request_queue_);
160 LOG_INFO(" Passed {} parameter(s) to strategy {}", params.size(), strategy_name);
161
162 add_strategy(strategy);
163 LOG_INFO("✓ Loaded strategy: {} from {}", strategy_name,
164 std::filesystem::path(plugin_path).filename().string());
165
166 // Apply risk limits from config or use defaults
167 RiskLimits limits;
168 if (strategy_configs.count(strategy_name)) {
169 limits = strategy_configs[strategy_name].risk_limits;
170 LOG_INFO(" Using custom risk limits from config");
171 } else {
172 // Default risk limits
173 limits.max_position_size = to_qty_t(1.0); // Max 1 BTC/ETH
174 limits.max_order_value = to_price_t(50000.0); // Max $50k per order
175 limits.max_orders_per_second = 10; // Max 10 orders/sec
176 LOG_INFO(" Using default risk limits (no config found)");
177 }
178
179 risk_manager_.set_limits(strategy_name, limits);
180 } else {
181 LOG_WARN("⚠ Failed to load plugin: {}", std::filesystem::path(plugin_path).filename().string());
182 LOG_WARN(" Error: {}", loader_.get_last_error());
183 }
184 }
185 }
186
187 // Always register ManualStrategy for orders placed through the Web UI, configured by a
188 // <name>.config.json naming it if there is one: its "instruments" narrow what ladders list.
189 {
190 auto manual = std::make_shared<ManualStrategy>();
191 const auto config = strategy_configs.find(ManualStrategy::ID);
192 const bool has_config = config != strategy_configs.end();
193 manual->initialize(has_config ? config->second.parameters : json::object(), position_tracker_,
194 pnl_calculator_, risk_manager_, order_request_queue_);
195 risk_manager_.set_limits(ManualStrategy::ID, has_config ? config->second.risk_limits : RiskLimits{});
197 LOG_INFO("✓ Registered ManualStrategy for web UI orders");
198 }
199
200 if (strategies_.size() == 1) {
201 LOG_WARN("⚠ No strategy plugins loaded - system will receive market data but won't auto-trade");
202 LOG_WARN("⚠ Place strategy plugins ({}) in: {}", plugin_extension, strategy_plugins_folder);
203 } else {
204 LOG_INFO("✓ Successfully loaded {} strategy/strategies", strategies_.size() - 1);
205 }
206}
207
208void StrategyManager::add_strategy(std::shared_ptr<IStrategy> strategy) {
209 strategies_.push_back(strategy);
210 strategy_map_[strategy->name()] = strategy;
211 if (auto manual = std::dynamic_pointer_cast<ManualStrategy>(strategy)) {
212 manual_ = std::move(manual);
213 }
214
215 // Track which MD brokers this strategy depends on (for auto-pause on MD disconnect)
216 for (const auto& sub : strategy->get_subscriptions()) {
217 strategy_md_brokers_[strategy->name()].insert(sub.broker_id);
218 }
219
220 // If the engine is already running, start the strategy immediately (hot-loading)
221 // Otherwise, it will be started when engine.start() is called
222 if (is_running()) [[unlikely]] {
223 strategy->start();
224 LOG_INFO("StrategyManager: Added and started strategy: {}", strategy->name());
225 } else {
226 LOG_INFO("StrategyManager: Added strategy '{}'", strategy->name());
227 }
228}
229
230bool StrategyManager::start_strategy(const std::string& strategy_id) {
231 auto it = strategy_map_.find(strategy_id);
232 if (it == strategy_map_.end()) return false;
233 auto_paused_strategies_.erase(strategy_id);
234 auto_pause_reasons_.erase(strategy_id);
235 it->second->start();
236 return true;
237}
238
239bool StrategyManager::stop_strategy(const std::string& strategy_id) {
240 auto it = strategy_map_.find(strategy_id);
241 if (it == strategy_map_.end()) return false;
242 auto_paused_strategies_.erase(strategy_id);
243 auto_pause_reasons_.erase(strategy_id);
244 it->second->stop();
245 return true;
246}
247
249 if (running_.load(std::memory_order_relaxed)) [[unlikely]] {
250 LOG_WARN("StrategyManager: Already running");
251 return;
252 }
253
254 LOG_INFO("StrategyManager: Starting");
255
256 // Requests wait only on the connectors enabled in this module's BrokerStatusRegistry: say
257 // which, since one that enabled itself in another module's is not waited on.
258 std::string readers;
259 for (size_t i = 1; i < BROKER_COUNT; ++i) {
260 if (BrokerStatusRegistry::instance().is_md_enabled(static_cast<BrokerId>(i))) {
261 readers += readers.empty() ? "" : ", ";
262 readers += to_string(static_cast<BrokerId>(i));
263 }
264 }
265 LOG_INFO("StrategyManager: market data requests wait on the connectors of: {}", readers.empty() ? "none" : readers);
266
267 // Start all strategies
268 for (auto& strategy : strategies_) {
269 strategy->start();
270
271 // subscribe MD update. MANUAL's are subscribed as ladders hold them.
272 if (strategy == manual_) {
273 continue;
274 }
275 for (const auto& subscription : strategy->get_subscriptions()) {
276 subscribe(subscription);
277 }
278 }
279
280 running_.store(true, std::memory_order_release);
281 worker_thread_ = std::thread(&StrategyManager::run, this);
282
283 LOG_INFO("StrategyManager: Started");
284}
285
287 if (!running_.load(std::memory_order_relaxed)) {
288 return;
289 }
290
291 LOG_INFO("StrategyManager: Stopping");
292
293 running_.store(false, std::memory_order_release);
294
295 // Join the worker before unsubscribing: it subscribes at runtime (a ladder holding an
296 // instrument of MANUAL's), so the subscription map is its state until it stops.
297 if (worker_thread_.joinable()) {
298 worker_thread_.join();
299 }
300
301 // Stop all strategies
302 for (auto& strategy : strategies_) {
303 auto subscriptions = strategy->get_subscriptions();
304 for (const auto &subscription : subscriptions) {
305 unsubscribe(subscription);
306 }
307 if (strategy == manual_) {
308 manual_->release_all(); // a ladder holds them again after a restart
309 }
310
311 strategy->stop();
312 }
313 drain_requests();
314
315 LOG_INFO("StrategyManager: Stopped");
316}
317
318// One instrument's slot in an MDSubscription.
319static constexpr size_t REQUEST_SLOT_SIZE = sizeof(MDSubscription::instruments[0]);
320
321size_t StrategyManager::max_instruments_per_request(const slick::queue<uint8_t>& queue) {
322 // A quarter of the queue: send_requests() asks for twice a request's size, and that has
323 // to fit with room left for the requests still unread. A queue too small for even one
324 // instrument that way gets requests of one, which go out once its connector has caught up.
325 const size_t budget = queue.size() / 4;
326 constexpr size_t header = sizeof(MDSubscription);
327 return budget > header + REQUEST_SLOT_SIZE ? (budget - header) / REQUEST_SLOT_SIZE : 1;
328}
329
330void StrategyManager::publish_subscription(EventType type, const SubscriptionRequest& sub,
331 const std::vector<std::string>& instruments) {
332 auto* queue = md_request_queues_.find(sub.broker_id);
333 if (queue == nullptr) {
334 // Held all the same: no broker of this engine reads them.
335 if (type == EventType::SUBSCRIBE) {
336 LOG_WARN("StrategyManager: no {} broker was built, so {} instrument(s) are not subscribed there",
337 to_string(sub.broker_id), instruments.size());
338 }
339 return;
340 }
341 const auto broker = static_cast<size_t>(sub.broker_id);
342 auto& outbox = request_outbox_[broker];
343 for_each_part(instruments.size(), max_instruments_per_request(*queue), [&](size_t offset, size_t n) {
344 const auto size = static_cast<uint32_t>(sizeof(MDSubscription) + n * REQUEST_SLOT_SIZE);
345 const auto write = [&](uint8_t* record) {
346 // Zeroed, so each name's slot is padded with zeros: the queue does not clear what
347 // it hands out.
348 std::memset(record, 0, size);
349 auto& event = *new (record) MDSubscription();
350 event.type = type;
351 event.broker_id = sub.broker_id;
352 event.subscription_type = sub.type;
353 event.depth = sub.depth;
354 event.num_instruments = static_cast<uint32_t>(n);
355 for (size_t i = 0; i < n; ++i) {
356 const auto& inst = instruments[offset + i];
357 auto& slot = event.instruments[i];
358 assert(inst.size() < sizeof(slot));
359 std::memcpy(slot, inst.data(), std::min(inst.size(), sizeof(slot) - 1));
360 }
361 };
362 if (outbox.empty() && has_room(broker, *queue, size)) {
363 const uint64_t index = queue->reserve(size);
364 write((*queue)[index]);
365 queue->publish(index, size);
366 } else {
367 // Out from run(), or from stop()'s drain. start(), the worker and stop() never
368 // run at once, so the outbox takes no lock.
369 write(outbox.emplace_back(size).data());
370 ++requests_queued_;
371 }
372 });
373}
374
375uint64_t StrategyManager::request_cursor(size_t i) const {
376 const uint64_t cursor = BrokerStatusRegistry::instance().md_request_cursor(static_cast<BrokerId>(i));
377 // None reported: it has read none of what this manager published.
378 return cursor == BrokerStatus::NO_MD_REQUEST_CURSOR ? request_baseline_[i] : cursor;
379}
380
381bool StrategyManager::has_room(size_t i, const slick::queue<uint8_t>& queue, uint32_t size) const {
382 // Enabled is taken for reading. A disabled connector that reads anyway, as Hyperliquid's
383 // does, drops its requests, so nothing is lost by not waiting on it.
384 if (!BrokerStatusRegistry::instance().is_md_enabled(static_cast<BrokerId>(i))) {
385 return true;
386 }
387 // Where the request ends at worst: a record that would cross the end of the ring is written
388 // from its start instead. Capped at the queue, which any request fits once the connector
389 // has caught up.
390 const uint64_t capacity = queue.size();
391 const uint64_t end = queue.initial_reading_index() + std::min<uint64_t>(2ull * size, capacity);
392 return end <= request_cursor(i) + capacity;
393}
394
395bool StrategyManager::send_requests(std::chrono::steady_clock::time_point now) {
396 last_request_send_ = now;
397 for (size_t i = 0; i < BROKER_COUNT; ++i) {
398 auto& outbox = request_outbox_[i];
399 if (outbox.empty()) {
400 continue;
401 }
402 const auto broker = static_cast<BrokerId>(i);
403 auto& queue = *md_request_queues_.find(broker); // nothing is queued for a broker without one
404 while (!outbox.empty()) {
405 const auto& record = outbox.front();
406 const auto size = static_cast<uint32_t>(record.size());
407 if (!has_room(i, queue, size)) {
408 break;
409 }
410 const uint64_t index = queue.reserve(size);
411 std::memcpy(queue[index], record.data(), size);
412 queue.publish(index, size);
413 outbox.pop_front();
414 --requests_queued_;
415 }
416
417 const uint64_t cursor = request_cursor(i);
418 auto& wait = request_waits_[i];
419 if (outbox.empty() || wait.since == std::chrono::steady_clock::time_point{} || cursor != wait.cursor) {
420 if (wait.reported) {
421 LOG_INFO("StrategyManager: {} market data connector is reading requests again", to_string(broker));
422 }
423 wait = outbox.empty() ? RequestWait{} : RequestWait{cursor, now, false};
424 } else if (!wait.reported && now - wait.since >= reader_stall_timeout_) {
425 wait.reported = true;
426 LOG_WARN("StrategyManager: {} market data connector has read no request in {} ms, with {} of its "
427 "own waiting for it",
428 to_string(broker), reader_stall_timeout_.count(), outbox.size());
429 }
430 }
431 return requests_queued_ == 0;
432}
433
434void StrategyManager::drain_requests() {
435 // A connector still reading takes the rest. One that has read nothing in
436 // md_request_stall_timeout_ms is given up on, here alone: its broker is stopping too.
437 while (!send_requests(std::chrono::steady_clock::now())) {
438 const bool any_reading = std::ranges::any_of(std::views::iota(size_t{0}, BROKER_COUNT), [&](size_t i) {
439 return !request_outbox_[i].empty() && !request_waits_[i].reported;
440 });
441 if (!any_reading) {
442 for (size_t i = 0; i < BROKER_COUNT; ++i) {
443 auto& outbox = request_outbox_[i];
444 if (!outbox.empty()) {
445 LOG_WARN("StrategyManager: {} market data request(s) to {} dropped at stop: its connector reads none",
446 outbox.size(), to_string(static_cast<BrokerId>(i)));
447 requests_queued_ -= outbox.size();
448 outbox.clear();
449 request_waits_[i] = {}; // or, started again, it would never be reported nor waited on
450 }
451 }
452 return;
453 }
454 std::this_thread::yield();
455 }
456}
457
458void StrategyManager::subscribe(const SubscriptionRequest& sub, bool book) {
459 // Only what nobody holds yet goes to the broker; the rest just gains a holder.
460 std::vector<std::string> instruments;
461 for (auto& inst : sub.instruments) {
462 if (++subscriptions_[SubscriptionKey{sub.broker_id, sub.type, inst}] == 1) {
463 instruments.push_back(inst);
464 }
465 }
466 if (!instruments.empty()) {
467 publish_subscription(EventType::SUBSCRIBE, sub, instruments);
468 }
469 if (!book) {
470 return;
471 }
472
473 // Every instrument of the request, not only those new to the broker: MANUAL may hold one
474 // already, with no book kept. Books are made in start() alone, before the worker reads the
475 // bus, so each takes in its broker's snapshot, which no SUBSCRIBE before start() has had
476 // read yet. One made later, for one MANUAL streams, would be built from increments alone.
477 assert(!is_running());
478 if (streams_book(sub.type)) {
480 } else if (sub.type == SubscriptionType::MBO) {
481 // Built now, not on the first event the worker dispatches.
482 for (const auto& inst : sub.instruments) {
483 get_or_create_mbo_book(inst);
484 }
485 }
486}
487
488void StrategyManager::unsubscribe(const SubscriptionRequest& sub) {
489 // Only what its last holder lets go of is unsubscribed at the broker.
490 std::vector<std::string> instruments;
491 for (auto& inst : sub.instruments) {
492 auto iter = subscriptions_.find(SubscriptionKey{sub.broker_id, sub.type, inst});
493 if (iter != subscriptions_.end() && --iter->second == 0) {
494 subscriptions_.erase(iter);
495 instruments.push_back(inst);
496 }
497 }
498
499 if (!instruments.empty()) {
500 publish_subscription(EventType::UNSUBSCRIBE, sub, instruments);
501 }
502}
503
504void StrategyManager::run() {
505 LOG_INFO("StrategyManager: Worker thread started");
506
507 auto last_periodic_check = std::chrono::steady_clock::now();
508 constexpr auto check_interval = std::chrono::seconds(1);
509
510 while (running_.load(std::memory_order_relaxed)) {
511 bool busy = false;
512 if (auto record = event_mux_.read(event_cursor_)) {
513 process_event(reinterpret_cast<const Event*>(record.data));
514 busy = true;
515 }
516
517 auto now = std::chrono::steady_clock::now();
518 // Retried at an interval, not on every event: a connector frees room a request at a time.
519 if (requests_queued_ != 0 && now - last_request_send_ >= REQUEST_RETRY_INTERVAL) {
520 send_requests(now);
521 }
522 if (now - last_periodic_check >= check_interval) {
523 check_loss_limits();
524 check_broker_status();
525 last_periodic_check = now;
526 busy = true;
527 }
528
529 if (!busy) {
530 std::this_thread::yield();
531 }
532 }
533
534 LOG_INFO("StrategyManager: Worker thread stopped");
535}
536
537// A parameter update published by the WebServer. Running it here is the point of routing it
538// through the bus: on_config() lands on the worker thread, so a strategy can apply the change
539// straight into state only this thread owns, with no latch and no lock.
540//
541// Deliberately unconditional on run state — a paused or halted strategy still has to see a
542// config change, and applying one is not the same as trading on it.
543void StrategyManager::dispatch_strategy_config(const StrategyConfigEvent& event) {
544 const std::string strategy_id(event.strategy);
545
546 auto strategy = get_strategy(strategy_id);
547 if (!strategy) {
548 LOG_WARN("StrategyManager: config update for unknown strategy '{}'", strategy_id);
549 return;
550 }
551 auto* base = dynamic_cast<StrategyBase*>(strategy.get());
552 if (base == nullptr) {
553 LOG_WARN("StrategyManager: strategy '{}' does not support config updates", strategy_id);
554 return;
555 }
556
557 // The WebServer validated the JSON before publishing, so a parse failure here means the
558 // record was truncated or corrupted in transit — never apply half a config.
559 json params;
560 try {
561 params = json::parse(event.config_text());
562 } catch (const json::exception& e) {
563 LOG_ERROR("StrategyManager: unparsable config for '{}': {}", strategy_id, e.what());
564 return;
565 }
566
567 base->set_config(params);
568 LOG_INFO("StrategyManager: Applied config update to strategy {}", strategy_id);
569
570 // A list MANUAL is given now names instruments brokers defined already, and they may not
571 // define them again.
572 if (strategy == manual_) {
573 for (size_t i = 0; i < BROKER_COUNT; ++i) {
574 for (const auto& [instrument, defined] : defined_[i]) {
575 list(static_cast<BrokerId>(i), instrument, defined.tick_size, defined.min_qty);
576 }
577 }
578 }
579}
580
581void StrategyManager::check_broker_status() {
582 auto& reg = BrokerStatusRegistry::instance();
583
584 for (auto& strategy : strategies_) {
585 const std::string name(strategy->name());
586
587 if (risk_manager_.is_halted(name)) continue;
588
589 auto it = strategy_md_brokers_.find(name);
590 if (it == strategy_md_brokers_.end()) continue;
591
592 bool md_lost = false;
593 std::string reason;
594 for (BrokerId bid : it->second) {
595 if (reg.is_md_enabled(bid) && !reg.is_md_connected(bid)) {
596 md_lost = true;
597 reason = std::string("MD disconnected for broker ") + reg.get(bid).name;
598 break;
599 }
600 }
601
602 const bool is_auto_paused = auto_paused_strategies_.count(name) > 0;
603 auto* base = dynamic_cast<StrategyBase*>(strategy.get());
604
605 if (md_lost && !is_auto_paused && base && base->is_running()) {
606 LOG_WARN("StrategyManager: Auto-pausing '{}' - {}", name, reason);
607 strategy->stop();
608 auto_paused_strategies_.insert(name);
609 auto_pause_reasons_[name] = reason;
610 } else if (!md_lost && is_auto_paused) {
611 LOG_INFO("StrategyManager: Auto-resuming '{}' after MD reconnect", name);
612 strategy->start();
613 auto_paused_strategies_.erase(name);
614 auto_pause_reasons_.erase(name);
615 }
616 }
617}
618
620 switch (event->type) {
621 case EventType::TRADE:
622 dispatch_trade(*reinterpret_cast<const TradeEvent*>(event));
623 break;
624 case EventType::QUOTE:
625 dispatch_quote(*reinterpret_cast<const QuoteEvent*>(event));
626 break;
627 case EventType::TOB:
628 // This manager's own top of book, back off the bus: the strategies were given
629 // it when it was published.
630 break;
632 dispatch_level2_updates(*reinterpret_cast<const Level2UpdateEvent*>(event));
633 break;
635 dispatch_mbo_update(*reinterpret_cast<const MboUpdateEvent*>(event));
636 break;
638 dispatch_order_book(*reinterpret_cast<const OrderBookEvent*>(event));
639 break;
641 dispatch_order_ack(*reinterpret_cast<const OrderAckEvent*>(event));
642 break;
644 dispatch_order_fill(*reinterpret_cast<const OrderFillEvent*>(event));
645 break;
647 dispatch_order_reject(*reinterpret_cast<const OrderRejectEvent*>(event));
648 break;
650 dispatch_order_cancel(*reinterpret_cast<const OrderCancelEvent*>(event));
651 break;
653 dispatch_strategy_config(*reinterpret_cast<const StrategyConfigEvent*>(event));
654 break;
656 dispatch_instrument_definition(*reinterpret_cast<const InstrumentDefinitionEvent*>(event));
657 break;
659 dispatch_instrument_status(*reinterpret_cast<const InstrumentStatusEvent*>(event));
660 break;
662 dispatch_ladder_subscription(*reinterpret_cast<const LadderSubscriptionEvent*>(event));
663 break;
664 default:
665 LOG_WARN("StrategyManager: Unknown event type: {}", static_cast<int>(event->type));
666 break;
667 }
668}
669
670void StrategyManager::check_loss_limits() {
671 const auto now_ns = get_timestamp_ns();
672
673 // Check each strategy
674 for (auto& strategy : strategies_) {
675 const std::string strategy_name(strategy->name());
676
677 // Skip if already halted
678 if (risk_manager_.is_halted(strategy_name)) {
679 continue;
680 }
681
682 // Get risk limits
683 const auto limits = risk_manager_.get_limits(strategy_name);
684
685 // Calculate current PnL
686 const auto pnl = pnl_calculator_.calculate_pnl(strategy_name, now_ns);
687
688 // Check if total PnL has breached the loss limit
689 if (pnl.total_pnl < limits.max_loss_per_strategy) {
690 const double loss = from_price_t(pnl.total_pnl);
691 const double max_loss = from_price_t(limits.max_loss_per_strategy);
692
693 const std::string reason = "Loss limit breached: PnL=" +
694 std::to_string(loss) + " < max_loss=" + std::to_string(max_loss);
695
696 LOG_ERROR("StrategyManager: {} - {}", strategy_name, reason);
697
698 // Close all open positions before halting — leaves no unmanaged exposure
699 if (auto* base = dynamic_cast<StrategyBase*>(strategy.get())) {
700 base->close_all_positions();
701 }
702
703 risk_manager_.halt_strategy(strategy_name, reason);
704
705 // Stop the strategy
706 strategy->stop();
707 }
708 }
709}
710
711// Every strategy is added by load_strategies() before brokers publish anything, so a
712// definition reaches all of them as it arrives. defined_ keeps it for a list MANUAL is given later.
713void StrategyManager::dispatch_instrument_definition(const InstrumentDefinitionEvent& event) {
714 const std::string_view instrument(event.instrument);
715 position_tracker_.set_contract_multiplier(instrument, event.contract_multiplier);
716 LOG_INFO("StrategyManager: instrument {} on {}: tick={} multiplier={} currency={}",
717 instrument, to_string(event.broker_id), from_price_t(event.tick_size),
718 event.contract_multiplier, event.currency);
719 for (auto& strategy : strategies_) {
720 strategy->on_instrument_definition(event);
721 }
722
723 // A replay, as a venue loops its definitions, was listed or not the first time it came: MANUAL
724 // takes a new list over defined_ itself. Only a first one goes to it.
725 const auto broker = static_cast<size_t>(event.broker_id);
726 if (broker < BROKER_COUNT && !defined_[broker].contains(instrument)) {
727 // A copy: the event is packed, and emplace() would bind a reference to its field.
728 const Defined defined{price_t{event.tick_size}, qty_t{event.min_quantity}};
729 defined_[broker].emplace(std::string(instrument), defined);
730 list(event.broker_id, instrument, defined.tick_size, defined.min_qty);
731 }
732}
733
734void StrategyManager::list(BrokerId broker, std::string_view instrument, price_t tick_size, qty_t min_qty) {
735 // For the Web UI's ladders to pick from. Nothing is subscribed until one holds it.
736 if (manual_) {
737 manual_->add_listing(broker, instrument, tick_size, min_qty);
738 }
739}
740
741void StrategyManager::dispatch_ladder_subscription(const LadderSubscriptionEvent& event) {
742 // Held or released once, whatever the WebServer sends: the subscription map counts MANUAL as
743 // one holder, so a strategy holding the same book keeps it.
744 // One a strategy only quotes or trades is the ladder's to hold too: it streams no book.
745 const std::string_view instrument(event.instrument);
746 if (!manual_) {
747 return;
748 }
749 const uint8_t asked = event.feeds;
750 const uint8_t feeds = !event.subscribe ? manual_->release(event.broker_id, instrument)
751 : manual_->hold(event.broker_id, instrument, subscribed(event.broker_id, instrument), asked)
752 ? asked
753 : 0;
754 if (feeds == 0) {
755 return;
756 }
757 if (event.subscribe) {
758 LOG_INFO("StrategyManager: a ladder holds {} on {}", instrument, to_string(event.broker_id));
759 } else {
760 LOG_INFO("StrategyManager: no ladder holds {} on {} now", instrument, to_string(event.broker_id));
761 }
762 for (size_t i = 0; i < ManualStrategy::SUBSCRIPTIONS.size(); ++i) {
763 if (!(feeds & (1u << i))) {
764 continue; // a strategy streams it
765 }
766 const SubscriptionRequest request(event.broker_id, ManualStrategy::SUBSCRIPTIONS[i], {std::string(instrument)});
767 if (event.subscribe) {
768 subscribe(request, false);
769 } else {
770 unsubscribe(request);
771 }
772 }
773}
774
775bool StrategyManager::subscribed(BrokerId broker, std::string_view instrument) const {
776 std::string name(instrument);
779 SubscriptionKey key{broker, type, std::move(name)};
780 if (subscriptions_.contains(key)) {
781 return true;
782 }
783 name = std::move(std::get<2>(key));
784 }
785 return false;
786}
787
788void StrategyManager::dispatch_instrument_status(const InstrumentStatusEvent& event) {
789 LOG_INFO("StrategyManager: instrument {} on {} is {}{}{}{}", event.instrument, to_string(event.broker_id),
790 to_string(event.status), event.cancel_allowed ? "" : " (no cancels)",
791 event.reason[0] != '\0' ? ": " : "", event.reason);
792 for (auto& strategy : strategies_) {
793 strategy->on_instrument_status(event);
794 }
795}
796
797void StrategyManager::dispatch_trade(const TradeEvent& event) {
798 pnl_calculator_.update_mark_price(std::string(event.instrument), event.price, event.timestamp_ns);
799 for (auto& strategy : strategies_) {
800 strategy->on_trade(event);
801 }
802}
803
804void StrategyManager::dispatch_quote(const QuoteEvent& event) {
805 const bool bid_valid = event.bid_price != NULL_PRICE;
806 const bool ask_valid = event.ask_price != NULL_PRICE;
807 if (bid_valid && ask_valid) {
808 pnl_calculator_.update_top_of_book(std::string(event.instrument),
809 event.bid_price,
810 event.ask_price,
811 event.timestamp_ns);
812 } else {
813 LOG_DEBUG("dispatch_quote: pnl calculator skipping mark price update for {} — bid={} ask={} (NULL_PRICE={})",
814 event.instrument,
815 event.bid_price, event.ask_price, NULL_PRICE);
816 }
817 for (auto& strategy : strategies_) {
818 strategy->on_quote(event);
819 }
820}
821
822void StrategyManager::dispatch_level2_updates(const Level2UpdateEvent& event) {
823 // Only the books strategies subscribed. MANUAL's instruments stream to the Web UI alone.
824 slick::orderbook::OrderBookL2* book = find_l2_book(event.instrument);
825 if (book == nullptr) {
826 return;
827 }
828
829 if (event.is_snapshot) {
830 book->clear();
831 LOG_DEBUG("StrategyManager: dispatch snapshot {}", event.instrument);
832 }
833
834 for (uint16_t i = 0, last = event.num_levels - 1; i < event.num_levels; ++i) {
835 if (event.levels[i].side == Side::BUY) {
836 book->updateLevel(slick::orderbook::Side::Buy,
837 static_cast<slick::orderbook::Price>(event.levels[i].price),
838 static_cast<slick::orderbook::Quantity>(event.levels[i].quantity),
839 event.event_time_ns,
840 event.sequence_num,
841 i == last);
842 }
843 else {
844 book->updateLevel(slick::orderbook::Side::Sell,
845 static_cast<slick::orderbook::Price>(event.levels[i].price),
846 static_cast<slick::orderbook::Quantity>(event.levels[i].quantity),
847 event.event_time_ns,
848 event.sequence_num,
849 i == last);
850 }
851 }
852}
853
854void StrategyManager::on_top_of_book_update(const std::string &instrument, const slick::orderbook::TopOfBook& tob) {
855 // A side with nothing on it has no price. The book reports such a side as price 0 - a
856 // real price for a futures spread - so it is told apart by its quantity, and goes out as
857 // NULL_PRICE: marking a position against it would value it at zero, or at half the
858 // price of the side that is there.
859 const price_t bid = tob.bid_quantity > 0 ? static_cast<price_t>(tob.best_bid) : NULL_PRICE;
860 const price_t ask = tob.ask_quantity > 0 ? static_cast<price_t>(tob.best_ask) : NULL_PRICE;
861 if (bid != NULL_PRICE && ask != NULL_PRICE) {
862 pnl_calculator_.update_top_of_book(instrument, bid, ask, tob.timestamp);
863 }
864
865 QuoteEvent event;
866 event.set_instrument(instrument);
867 event.bid_price = bid;
868 event.bid_quantity = static_cast<qty_t>(tob.bid_quantity);
869 event.ask_price = ask;
870 event.ask_quantity = static_cast<qty_t>(tob.ask_quantity);
871 event.event_time_ns = tob.timestamp;
872
873 // Published for readers outside this thread - the dashboard refreshes PnL on it - as a
874 // TOB record, not a QUOTE: this thread reads the same bus, and a QUOTE would come back
875 // and be handed to the strategies a second time.
876 EventSerializer::publish<QuoteEvent>(*tob_producer_buffer_, [&](QuoteEvent& q) {
877 q = event;
879 });
880
881 for (auto& strategy : strategies_) {
882 strategy->on_quote(event);
883 }
884}
885
886StrategyManager::MboBook& StrategyManager::get_or_create_mbo_book(std::string_view instrument) {
887 auto it = mbo_books_.find(instrument);
888 if (it == mbo_books_.end()) [[unlikely]] {
889 std::string name(instrument);
890 // Quotes come from this book unless an L2 book of the instrument already gives them.
891 // Found by name, so its id only labels it: with every id taken, 0 shares no book.
892 auto entry = std::make_unique<MboBook>(get_or_create_symbol_id(name).value_or(0), name,
893 !l2_books_.contains(name));
894 it = mbo_books_.emplace(std::move(name), std::move(entry)).first;
895 }
896 return *it->second;
897}
898
899void StrategyManager::dispatch_mbo_update(const MboUpdateEvent& event) {
900 MboBook& entry = get_or_create_mbo_book(event.instrument);
901 auto& book = entry.book;
902
903 if (event.is_snapshot) {
904 book.clear(event.event_time_ns);
905 LOG_DEBUG("StrategyManager: dispatch MBO snapshot {}", entry.instrument);
906 }
907
908 for (uint16_t i = 0; i < event.num_orders; ++i) {
909 const MboOrder& order = event.orders[i];
910 // The broker already put the feed in order, so the book checks no sequence numbers.
911 const bool is_last = event.is_last && i + 1 == event.num_orders;
912 if (order.action == MboAction::REMOVE) {
913 book.deleteOrder(order.order_id, event.event_time_ns, 0, is_last);
914 } else {
915 book.addOrModifyOrder(order.order_id,
916 order.side == Side::BUY ? slick::orderbook::Side::Buy : slick::orderbook::Side::Sell,
917 static_cast<slick::orderbook::Price>(order.price),
918 static_cast<slick::orderbook::Quantity>(order.quantity),
919 event.event_time_ns,
920 order.priority,
921 0,
922 is_last);
923 }
924 }
925
926 // Strategies see the book only when it is whole: at the end of the exchange event.
927 if (!event.is_last) {
928 return;
929 }
930
931 if (entry.publishes_top) {
932 const auto top = book.getTopOfBook();
933 if (top.best_bid != entry.top.best_bid || top.bid_quantity != entry.top.bid_quantity ||
934 top.best_ask != entry.top.best_ask || top.ask_quantity != entry.top.ask_quantity) {
935 entry.top = top;
936 on_top_of_book_update(entry.instrument, top);
937 }
938 }
939
940 for (auto& strategy : strategies_) {
941 strategy->on_order_book_l3(entry.instrument, book);
942 }
943}
944
945void StrategyManager::on_order_book_update(const std::string& instrument, const slick::orderbook::OrderBookL2& book) {
946 for (auto& strategy : strategies_) {
947 strategy->on_order_book(instrument, book);
948 }
949}
950
951void StrategyManager::dispatch_order_book(const OrderBookEvent& event) {
952 slick::orderbook::OrderBookL2* book = find_l2_book(event.instrument);
953 if (book == nullptr) {
954 return;
955 }
956
957 if (event.is_snapshot) {
958 book->clear();
959 }
960
961 const bool is_last_bid = (event.num_asks == 0);
962 for (uint16_t i = 0; i < event.num_bids; ++i) {
963 book->updateLevel(slick::orderbook::Side::Buy,
964 static_cast<slick::orderbook::Price>(event.bids[i].price),
965 static_cast<slick::orderbook::Quantity>(event.bids[i].quantity),
966 event.event_time_ns,
967 event.sequence_num,
968 is_last_bid && (i == event.num_bids - 1));
969 }
970 for (uint16_t i = 0; i < event.num_asks; ++i) {
971 book->updateLevel(slick::orderbook::Side::Sell,
972 static_cast<slick::orderbook::Price>(event.asks[i].price),
973 static_cast<slick::orderbook::Quantity>(event.asks[i].quantity),
974 event.event_time_ns,
975 event.sequence_num,
976 i == event.num_asks - 1);
977 }
978}
979
980std::optional<slick::orderbook::SymbolId> StrategyManager::get_or_create_symbol_id(std::string_view instrument) {
981 if (const auto it = symbol_ids_.find(instrument); it != symbol_ids_.end()) {
982 return it->second;
983 }
984 if (symbol_ids_.size() > std::numeric_limits<slick::orderbook::SymbolId>::max()) {
985 LOG_ERROR("StrategyManager: no book for {}: all {} book ids are taken", instrument, symbol_ids_.size());
986 return std::nullopt;
987 }
988 const slick::orderbook::SymbolId sid = next_symbol_id_++;
989 symbol_ids_.emplace(std::string(instrument), sid);
990 LOG_DEBUG("StrategyManager: Assigned symbol_id={} for {}", sid, instrument);
991 return sid;
992}
993
994void StrategyManager::dispatch_order_ack(const OrderAckEvent& event) {
995 LOG_INFO("StrategyManager: dispatch_order_ack order_id={} client_order_id={} to {} strategies",
996 std::string(event.order_id), std::string(event.client_order_id), strategies_.size());
997 for (auto& strategy : strategies_) {
998 strategy->on_order_ack(event);
999 }
1000}
1001
1002void StrategyManager::dispatch_order_fill(const OrderFillEvent& event) {
1003 // A broker replays its fill journal after a restart: what the strategies had before
1004 // the process stopped - booked, or seen to be no one's - is not had twice.
1005 if (position_tracker_.fill_handled(event)) {
1006 LOG_DEBUG("StrategyManager: fill {} of {} (journal {}) was handled before a restart - dropped",
1007 std::string(event.fill_id), std::string(event.client_order_id), event.journal_seq);
1008 return;
1009 }
1010
1011 // Update mark price for PnL calculation
1012 pnl_calculator_.update_mark_price(std::string(event.instrument),
1013 event.fill_price,
1014 event.timestamp_ns);
1015
1016 // Dispatch to strategies (they track their own fills)
1017 for (auto& strategy : strategies_) {
1018 strategy->on_order_fill(event);
1019 }
1020 position_tracker_.fill_dispatched(event);
1021}
1022
1023void StrategyManager::dispatch_order_reject(const OrderRejectEvent& event) {
1024 for (auto& strategy : strategies_) {
1025 strategy->on_order_reject(event);
1026 }
1027}
1028
1029void StrategyManager::dispatch_order_cancel(const OrderCancelEvent& event) {
1030 for (auto& strategy : strategies_) {
1031 strategy->on_order_cancel(event);
1032 }
1033}
static BrokerStatusRegistry & instance()
uint64_t md_request_cursor(BrokerId id) const noexcept
static bool publish(slick::SlickQueue< uint8_t > &queue, uint32_t size, populate_event_fn &&populate_event_func)
static constexpr const char * ID
static constexpr std::array< SubscriptionType, 2 > SUBSCRIPTIONS
PnLSnapshot calculate_pnl(const std::string &strategy_id, uint64_t timestamp_ns) const
void halt_strategy(const std::string &strategy_id, const std::string &reason)
RiskLimits get_limits(const std::string &strategy_id) const
bool is_halted(const std::string &strategy_id) const
bool is_auto_paused(const std::string &strategy_id) const
StrategyManager(const json &config, PositionTracker &position_tracker, PnLCalculator &pnl_calculator, RiskManager &risk_manager, slick::stream_buffer_multiplexer &event_mux, MdRequestQueues &md_request_queues, slick::queue< uint8_t > &order_request_queue)
void process_event(const Event *event)
void add_strategy(std::shared_ptr< IStrategy > strategy)
bool start_strategy(const std::string &strategy_id)
const ManualStrategy * manual() const noexcept
bool stop_strategy(const std::string &strategy_id)
std::shared_ptr< IStrategy > get_strategy(const std::string &strategy_id) const
void load_strategies(const json &config)
void subscribe_book_update(const std::vector< std::string > &instruments)
static constexpr std::string_view PLUGIN_EXTENSION
double from_price_t(price_t value)
Definition types.hpp:36
price_t to_price_t(double value)
Definition types.hpp:24
uint64_t get_timestamp_ns()
Definition time.hpp:7
const char * to_string(BrokerId bid)
Definition event.hpp:78
constexpr bool streams_book(SubscriptionType type) noexcept
Definition types.hpp:54
constexpr price_t NULL_PRICE
Definition types.hpp:19
void for_each_part(size_t count, size_t max, F &&f)
int64_t qty_t
Definition types.hpp:17
int64_t price_t
Definition types.hpp:16
nlohmann::json json
qty_t to_qty_t(double value)
Definition types.hpp:32
static constexpr size_t REQUEST_SLOT_SIZE
static constexpr uint64_t NO_MD_REQUEST_CURSOR
uint64_t event_time_ns
Definition event.hpp:59
char instrument[MAX_INSTRUMENT_LENGTH]
Definition event.hpp:61
uint64_t timestamp_ns
Definition event.hpp:58
void set_instrument(std::string_view instr)
Definition event.hpp:70
BrokerId broker_id
Definition event.hpp:60
OrderBookPriceLevel asks[MAX_ORDER_BOOK_LEVELS]
OrderBookPriceLevel bids[MAX_ORDER_BOOK_LEVELS]
char order_id[MAX_ORDER_ID_LENGTH]
char fill_id[MAX_ORDER_ID_LENGTH]
char strategy[MAX_STRATEGY_NAME_LENGTH]
static StrategyConfig from_json(const nlohmann::json &j)
std::vector< std::string > instruments
Definition types.hpp:62