Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
trading_engine.cpp
Go to the documentation of this file.
1#include <slick/logger.hpp>
10#ifdef SLICK_TRADER_HAS_SLICK_NET
11#include <slick/net/logging.hpp>
12#endif
13#include <nlohmann/json.hpp>
14#include <algorithm>
15#include <cctype>
16#include <fstream>
17#include <sstream>
18#include <iostream>
19#include <thread>
20
21namespace slick::trader {
22
23using Logger = slick::logger::Logger;
24
25// Helper function to join strings
26static std::string join_strings(const std::vector<std::string>& vec, const std::string& delimiter) {
27 if (vec.empty()) return "";
28 std::ostringstream oss;
29 oss << vec[0];
30 for (size_t i = 1; i < vec.size(); ++i) {
31 oss << delimiter << vec[i];
32 }
33 return oss.str();
34}
35
36TradingEngine::TradingEngine()
37 : pnl_calculator_(position_tracker_)
38 , risk_manager_(position_tracker_)
39{
40}
41
42TradingEngine::~TradingEngine() {
43 shutdown();
44}
45
46bool TradingEngine::initialize(const std::string& config_path) {
47 std::ifstream config_file(config_path);
48 if (!config_file.is_open()) {
49 std::cerr << "Failed to open config file: " << config_path << std::endl;
50 return false;
51 }
52
53 json config;
54 try {
55 config = json::parse(config_file);
56 } catch (const std::exception& e) {
57 std::cerr << "Failed to parse config file: " << e.what() << std::endl;
58 return false;
59 }
60
61 std::string log_file = config.value<std::string>("log_file_path", "logs/slick_trader.log");
62 auto str_log_level = config.value<std::string>("log_level", "info");
63 slick::logger::LogLevel log_level = slick::logger::to_log_level(str_log_level);
64
65 // Initialize logger with console and file output
66 auto &logger = Logger::instance();
67 logger.clear_sinks();
68#ifdef DEBUG
69 logger.add_console_sink(true, true);
70#endif
71 logger.add_file_sink(log_file);
72 logger.set_level(log_level);
73 logger.init();
74
75 std::string environment;
76 if (!read_environment(config, environment)) {
77 LOG_ERROR("Config 'environment' must be a string, such as \"Sim\" or \"Production\"");
78 return false;
79 }
80 if (is_production_environment(environment)) {
81 LOG_INFO("Environment: {}", environment);
82 } else {
83 LOG_WARN("Environment: {} (not production)", environment);
84 }
85
86 // Where slick-sim is, required in Sim: the web server asks it for its feeds.
87 SimControlConfig sim_control;
88 if (is_sim_environment(environment)) {
89 std::string error;
90 if (!read_sim_control(config, sim_control, error)) {
91 LOG_ERROR("Environment Sim: config {}", error);
92 return false;
93 }
94 } else if (config.contains(SimControlConfig::ADDR_KEY) || config.contains(SimControlConfig::PORT_KEY)) {
95 LOG_WARN("Config '{}' and '{}' are for environment Sim alone: ignored", SimControlConfig::ADDR_KEY,
97 }
98
99#ifdef SLICK_TRADER_HAS_SLICK_NET
100 // Route slick-net logs to slick-logger. The Coinbase and Hyperliquid SDKs use it for networking.
101 slick::net::set_log_handler(
102 [&logger](slick::net::LogLevel level, const char* format_text, std::format_args args) {
103 logger.log(static_cast<slick::logger::LogLevel>(level), format_text, std::move(args));
104 },
105 [&logger] {
106 return static_cast<slick::net::LogLevel>(logger.get_level());
107 }
108 );
109#endif
110
111 // Positions kept across restarts, if asked for. Restored here, before anything can
112 // book a fill or read a position.
113 if (config.contains("position_store")) {
114 const auto& store_config = config["position_store"];
115 const auto store_path = store_config.value<std::string>("path", "state/positions.dat");
116 try {
117 position_store_ = std::make_unique<PositionStore>(
118 store_path, store_config.value<size_t>("capacity", PositionStore::DEFAULT_CAPACITY));
119 } catch (const std::exception& e) {
120 // Trading on with positions that start flat, or that will not be kept, is not
121 // what was asked for: stop instead.
122 LOG_ERROR("Failed to open position store: {}", e.what());
123 return false;
124 }
125 position_tracker_.attach_store(*position_store_);
126 }
127
128 // Create event queue
129 auto event_queue_size = config.value("event_queue_size", 1u << 24 /* 16M */);
130 const char* event_queue_shm_name = config.contains("event_queue_shm_name") ? config["event_queue_shm_name"].get_ref<std::string&>().c_str() : nullptr;
131
132 LOG_INFO("event queue size: {}", event_queue_size);
133 LOG_INFO("event queue shm name: {}", event_queue_shm_name ? event_queue_shm_name : "");
134
135 event_mux_ = std::make_unique<slick::stream_buffer_multiplexer>(event_queue_size, event_queue_shm_name);
136
137 // Create control queue
138 auto control_queue_size = config.value("control_queue_size", 1u << 20 /* 1M */);
139 const char* control_queue_shm_name = config.contains("control_queue_shm_name") ? config["control_queue_shm_name"].get_ref<std::string&>().c_str() : nullptr;
140
141 LOG_INFO("control queue size: {}", control_queue_size);
142 LOG_INFO("control queue shm name: {}", control_queue_shm_name ? control_queue_shm_name : "");
143
144 control_queue_ = std::make_unique<slick::queue<uint8_t>>(control_queue_size, control_queue_shm_name);
145
146 // MD request queues, one per broker, made as each broker is
147 auto md_request_queue_size = config.value("md_request_queue_size", 1u << 20 /* 1M */);
148 const std::string md_request_queue_shm_name = config.value("md_request_queue_shm_name", "");
149
150 LOG_INFO("md request queue size: {} per broker", md_request_queue_size);
151 LOG_INFO("md request queue shm name: {}", md_request_queue_shm_name.empty() ? "" : md_request_queue_shm_name + "_<BROKER>");
152
153 md_request_queues_ = std::make_unique<MdRequestQueues>(md_request_queue_size, md_request_queue_shm_name);
154
155 // Create order request queue
156 auto order_request_queue_size = config.value("order_request_queue_size", 1u << 24 /* 16M */);
157 const char* order_request_queue_shm_name = config.contains("order_request_queue_shm_name") ? config["order_request_queue_shm_name"].get_ref<std::string&>().c_str() : nullptr;
158
159 LOG_INFO("order request queue size: {}", order_request_queue_size);
160 LOG_INFO("order request queue shm name: {}", order_request_queue_shm_name ? order_request_queue_shm_name : "");
161
162 order_request_queue_ = std::make_unique<slick::queue<uint8_t>>(order_request_queue_size, order_request_queue_shm_name);
163
164 // ========================================================================
165 // Broker Setup from Configuration
166 // ========================================================================
167 if (config.contains("brokers") && config["brokers"].is_array()) {
168 LOG_INFO("");
169 LOG_INFO("==================================================");
170 LOG_INFO(" Initialize Brokers...");
171 LOG_INFO("==================================================");
172
173 std::string built_in;
174 for (const auto& key : BrokerRegistry::instance().keys()) {
175 built_in += built_in.empty() ? key : ", " + key;
176 }
177 LOG_INFO("Broker adapters built in: {}", built_in.empty() ? "(none)" : built_in);
178
179 for (const auto& broker_json : config["brokers"]) {
180 // Parse broker configuration
181 auto enabled = broker_json.value("enabled", true);
182 auto broker_name = broker_json.value("name", "unknown");
183
184 if (!enabled) {
185 LOG_INFO("Skipping disabled broker: {}", broker_name);
186 continue;
187 }
188
189 // An enabled broker with no adapter compiled in - a typo, or an
190 // out-of-tree broker left out of SLICK_TRADER_EXTERNAL_BROKERS - is fatal
191 // rather than silently skipped.
192 auto factory = BrokerRegistry::instance().find(broker_name);
193 if (!factory) {
194 LOG_ERROR("No broker adapter for '{}'. This build has: {}",
195 broker_name, built_in.empty() ? "(none)" : built_in);
196 return false;
197 }
198
199 // Its market data requests come on a queue of its own, found by its BrokerId.
200 std::string upper(broker_name);
201 std::transform(upper.begin(), upper.end(), upper.begin(),
202 [](unsigned char c) { return static_cast<char>(std::toupper(c)); });
203 const BrokerId broker_id = to_broker_id(upper);
204 if (broker_id == BrokerId::UNKNOWN) {
205 LOG_ERROR("Broker '{}' names no BrokerId, so no market data request can reach it", broker_name);
206 return false;
207 }
208
209 std::string error;
210 auto broker = BrokerRegistry::instance().create(broker_name, broker_json, *event_mux_, *control_queue_,
211 md_request_queues_->get(broker_id), *order_request_queue_,
212 error);
213 if (!broker) {
214 LOG_ERROR("Failed to create broker {}: {}", broker_name, error);
215 return false;
216 }
217
218 broker->register_broker();
219 LOG_INFO("✓ Registered broker: {}", broker_name);
220
221 brokers_.push_back(broker);
222 }
223
224 LOG_INFO("✓ Registered {} broker(s)", brokers_.size());
225
226 publish_regiter_end(event_mux_->producer_count());
227 } else {
228 LOG_WARN("⚠ No brokers configured in {}", config_path);
229 LOG_WARN("⚠ Add a 'brokers' array to enable market data and trading");
230 }
231
232 // Load strategies if configured
233 if (config.contains("strategies")) {
234 strategy_manager_ = std::make_unique<StrategyManager>(config["strategies"], position_tracker_, pnl_calculator_, risk_manager_, *event_mux_, *md_request_queues_, *order_request_queue_);
235 if (config["strategies"].value("enabled", true)) {
236 LOG_INFO("");
237 LOG_INFO("==================================================");
238 LOG_INFO(" Initialize Strategies...");
239 LOG_INFO("==================================================");
240 strategy_manager_->load_strategies(config["strategies"]);
241 }
242 }
243
244 // Initialize web server (optional, configurable)
245 if (config.contains("web_service") && config["web_service"].value("enabled", true)) {
246 LOG_INFO("");
247 LOG_INFO("==================================================");
248 LOG_INFO(" Initialize Web Service...");
249 LOG_INFO("==================================================");
250 web_server_ = std::make_unique<WebServer>(config_path, *strategy_manager_, position_tracker_, pnl_calculator_, risk_manager_, *event_mux_);
251 if (!web_server_->initialize(config["web_service"], environment, sim_control)) {
252 LOG_ERROR("Failed to initialize web server");
253 return false;
254 }
255 }
256
257 LOG_INFO("");
258 LOG_INFO("==================================================");
259 LOG_INFO(" Waiting for Brokers Ready...");
260 LOG_INFO("==================================================");
261
262 auto timed_out = wait_for_brokers_ready(std::chrono::seconds(config.value("waiting_time_out", 30)));
263 if (timed_out) {
264 LOG_WARN("Waiting for Brokers ready timed out");
265 }
266 return true;
267}
268
269void TradingEngine::publish_regiter_end(uint32_t num_producers) {
271 e.num_producers = num_producers;
272 });
273}
274
275bool TradingEngine::wait_for_brokers_ready(std::chrono::seconds timeout_sec) {
276 uint64_t cursor{0};
277 size_t num_producers{0};
278 size_t num_ipc_producers{0};
279 auto start = std::chrono::steady_clock::now();
280 auto end = start + timeout_sec;
281 bool timed_out = false;
282 do {
283 auto [data, size] = control_queue_->read(cursor);
284 if (!data) {
285 std::this_thread::yield();
286 }
287
288 auto *event = reinterpret_cast<Event*>(data);
289 if (event->type == EventType::REGISTER) {
290 ++num_producers;
291 auto &register_event = reinterpret_cast<RegisterEvent&>(*event);
292 if (register_event.shm_name[0] != '\0') {
293 // add_producer() throws if the id is already taken. An out-of-process broker
294 // picks its own id, so a clash with an in-process producer is possible; losing
295 // that one broker's events beats taking the engine down on the way up.
296 try {
297 event_mux_->add_producer(register_event.producer_id, register_event.shm_name);
298 LOG_INFO("Register IPC producer {}: borker={} type={}, shm_name={}", register_event.producer_id,
299 to_string(register_event.broker_id), to_string(register_event.component_type), register_event.shm_name);
300 ++num_ipc_producers;
301 } catch (const std::exception& e) {
302 LOG_ERROR("Failed to register IPC producer {} (broker={}): {}",
303 register_event.producer_id, to_string(register_event.broker_id), e.what());
304 }
305 }
306
307 } else if (event->type == EventType::REGISTER_END) {
308 break;
309 }
310 } while (!(timed_out = std::chrono::steady_clock::now() < end));
311 LOG_INFO("{} broker(s) registered, {} ipc producer(s). event_mux.producer_count={}", num_producers, num_ipc_producers, event_mux_->producer_count());
312 return !timed_out;
313}
314
316 if (running_.load(std::memory_order_relaxed)) [[unlikely]] {
317 LOG_WARN("TradingEngine already running");
318 return;
319 }
320
321 if (!brokers_.empty()) {
322 LOG_INFO("");
323 LOG_INFO("==================================================");
324 LOG_INFO(" Start Brokers...");
325 LOG_INFO("==================================================");
326 for (auto &broker : brokers_) {
327 broker->start();
328 }
329 }
330
331 if (strategy_manager_) {
332 LOG_INFO("");
333 LOG_INFO("==================================================");
334 LOG_INFO(" Start Strategies...");
335 LOG_INFO("==================================================");
336 strategy_manager_->start();
337 }
338
339 // Start web server (if initialized)
340 if (web_server_) {
341 LOG_INFO("");
342 LOG_INFO("==================================================");
343 LOG_INFO(" Start Web Service...");
344 LOG_INFO("==================================================");
345 web_server_->start();
346 }
347
348 // // Fetch and wire fee structures before strategies begin trading
349 // for (auto& [broker_id, broker] : brokers_) {
350 // FeeStructure fs = broker->get_fees("");
351 // if (fs.rate > 0.0) {
352 // position_tracker_->set_fee_structure(fs);
353 // LOG_INFO("TradingEngine: {} fee structure — type={} rate={:.4f}",
354 // broker->get_broker_name(),
355 // fs.type == FeeType::PERCENTAGE ? "percentage" : "fixed",
356 // fs.rate);
357 // }
358 // }
359
360 // // Start all brokers
361 // for (auto& [broker_id, broker] : brokers_) {
362 // LOG_INFO("Starting broker: {}", broker->get_broker_name());
363
364 // auto md_connector = broker->get_market_data_connector();
365 // if (md_connector) {
366 // md_connector->set_md_queue(md_queue_);
367 // md_connector->start();
368 // }
369
370 // auto order_connector = broker->get_order_connector();
371 // if (order_connector) {
372 // order_connector->set_order_submission_queue(order_request_queue_);
373 // order_connector->set_order_event_queue(order_event_queue_);
374 // order_connector->start();
375 // }
376 // }
377
378 running_.store(true, std::memory_order_release);
379 LOG_INFO("");
380 LOG_INFO("==================================================");
381 LOG_INFO(" TradingEngine started");
382 LOG_INFO("==================================================");
383}
384
386 if (!running_.load(std::memory_order_acquire)) {
387 return;
388 }
389
390 LOG_INFO("Stopping TradingEngine");
391
392 // // Stop all brokers
393 // for (auto& [broker_id, broker] : brokers_) {
394 // LOG_INFO("Stopping broker: {}", broker->get_broker_name());
395
396 // auto md_connector = broker->get_market_data_connector();
397 // if (md_connector) {
398 // md_connector->stop();
399 // }
400
401 // auto order_connector = broker->get_order_connector();
402 // if (order_connector) {
403 // order_connector->stop();
404 // }
405 // }
406
407 // Brokers hear of it first: the cancels a strategy sends as it stops reach them next.
408 for (auto &broker : brokers_) {
409 broker->begin_stop();
410 }
411
412 // Stop strategy manager
413 if (strategy_manager_) {
414 LOG_INFO("");
415 LOG_INFO("==================================================");
416 LOG_INFO(" Stop Strategies...");
417 LOG_INFO("==================================================");
418 strategy_manager_->stop();
419 }
420
421 if (!brokers_.empty()) {
422 LOG_INFO("");
423 LOG_INFO("==================================================");
424 LOG_INFO(" Stop Brokers...");
425 LOG_INFO("==================================================");
426 for (auto &broker : brokers_) {
427 broker->stop();
428 }
429 }
430
431 // Stop web server
432 if (web_server_) {
433 LOG_INFO("");
434 LOG_INFO("==================================================");
435 LOG_INFO(" Stop Web Service...");
436 LOG_INFO("==================================================");
437 web_server_->stop();
438 }
439
440 running_.store(false, std::memory_order_release);
441 LOG_INFO("TradingEngine stopped");
442}
443
444// void TradingEngine::apply_strategy_subscriptions() {
445// LOG_INFO("Applying strategy-driven market data subscriptions...");
446
447// // Collect all subscription requests from all strategies
448// // key: broker_id << 8 | sub.type
449// std::unordered_map<uint16_t, std::vector<std::string>> subscription_map;
450
451// // Get all strategies from strategy manager
452// for (const auto& strategy : strategy_manager_.get_all_strategies()) {
453// auto subscriptions = strategy->get_subscriptions();
454
455// for (const auto& sub : subscriptions) {
456// // Add instruments to the subscription map (keyed by broker + type)
457// auto& instruments = subscription_map[(static_cast<uint16_t>(sub.broker_id) << 8) | static_cast<uint16_t>(sub.type)];
458// instruments.insert(instruments.end(), sub.instruments.begin(), sub.instruments.end());
459
460// LOG_DEBUG("Strategy {} requests {} subscription for: {}",
461// strategy->name(),
462// sub.type == SubscriptionType::TRADE ? "TRADE" :
463// sub.type == SubscriptionType::QUOTE ? "QUOTE" :
464// sub.type == SubscriptionType::LEVEL2 ? "LEVEL2" : "ORDERBOOK",
465// join_strings(sub.instruments, ", "));
466// }
467// }
468
469// // Apply subscriptions to each broker
470// int total_subscriptions = 0;
471// for (const auto& [key, instruments] : subscription_map) {
472// auto broker_id = static_cast<BrokerId>(key >> 8);
473// auto broker = get_broker(broker_id);
474// if (!broker) {
475// LOG_WARN("Broker ID {} not registered - skipping subscriptions", static_cast<int>(broker_id));
476// continue;
477// }
478
479// auto md_connector = broker->get_market_data_connector();
480// if (!md_connector) {
481// LOG_WARN("Broker {} has no market data connector", broker->get_broker_name());
482// continue;
483// }
484
485// // Remove duplicates
486// std::vector<std::string> unique_instruments = instruments;
487// std::sort(unique_instruments.begin(), unique_instruments.end());
488// unique_instruments.erase(
489// std::unique(unique_instruments.begin(), unique_instruments.end()),
490// unique_instruments.end()
491// );
492
493// // Subscribe
494// auto sub_type = static_cast<SubscriptionType>(key & 0xFF);
495// md_connector->subscribe(sub_type, unique_instruments);
496
497// std::string type_str;
498// switch (sub_type) {
499// case SubscriptionType::TRADE: type_str = "trades"; break;
500// case SubscriptionType::QUOTE: type_str = "quotes"; break;
501// case SubscriptionType::LEVEL2: {
502// type_str = "level2";
503// strategy_manager_->subscribe_book_update(unique_instruments);
504// break;
505// }
506// case SubscriptionType::ORDER_BOOK: {
507// type_str = "orderbook";
508// strategy_manager_->subscribe_book_update(unique_instruments);
509// break;
510// }
511// }
512
513// LOG_INFO("✓ Subscribed {} to {} for: {}",
514// broker->get_broker_name(), type_str,
515// join_strings(unique_instruments, ", "));
516// total_subscriptions += unique_instruments.size();
517// }
518
519// if (total_subscriptions == 0) {
520// LOG_WARN("⚠ No market data subscriptions from strategies");
521// } else {
522// LOG_INFO("✓ Applied {} strategy-driven subscription(s)", total_subscriptions);
523// }
524// }
525
526} // namespace slick::trader
static BrokerRegistry & instance()
static bool publish(slick::SlickQueue< uint8_t > &queue, uint32_t size, populate_event_fn &&populate_event_func)
static constexpr std::size_t DEFAULT_CAPACITY
bool initialize(const std::string &config_path)
const char * to_string(BrokerId bid)
Definition event.hpp:78
static std::string join_strings(const std::vector< std::string > &vec, const std::string &delimiter)
bool is_sim_environment(std::string_view env) noexcept
bool is_production_environment(std::string_view env) noexcept
bool read_sim_control(const nlohmann::json &config, SimControlConfig &sim, std::string &error)
nlohmann::json json
slick::logger::Logger Logger
bool read_environment(const nlohmann::json &config, std::string &env)
BrokerId to_broker_id(const std::string &broker)
Definition event.hpp:97
static constexpr const char * PORT_KEY
static constexpr const char * ADDR_KEY