Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
strategy_manager.hpp
Go to the documentation of this file.
1#pragma once
2
20#include <slick/queue.hpp>
21#include <nlohmann/json.hpp>
22#include <array>
23#include <deque>
24#include <memory>
25#include <vector>
26#include <thread>
27#include <atomic>
28#include <map>
29#include <optional>
30#include <set>
31#include <string_view>
32#include <tuple>
33#include <unordered_map>
34#include <unordered_set>
35#include <chrono>
36#include <string>
37
38namespace slick::trader {
39
40// Forward declarations
41class PositionTracker;
42class PnLCalculator;
43class RiskManager;
44class StrategyManager;
45using json = nlohmann::json;
46using multiplex_record = slick::stream_buffer_multiplexer::multiplex_record;
47using producer_buffer = slick::stream_buffer_multiplexer::producer_buffer;
48
50 OrderBookObserverImpl(StrategyManager* manager, slick::orderbook::OrderBookL2& order_book, const std::string& instrument)
51 : manager_(manager), order_book_(order_book), instrument_(instrument)
52 {}
53 ~OrderBookObserverImpl() override = default;
54
55 void onPriceLevelUpdate(const slick::orderbook::PriceLevelUpdate& update) override;
56 void onTopOfBookUpdate(const slick::orderbook::TopOfBook& tob) override;
57
58private:
59 StrategyManager* manager_;
60 slick::orderbook::OrderBookL2& order_book_;
61 std::string instrument_;
62};
63
64// Strategy Manager
65// Manages multiple strategies, dispatches events to them
66// Runs on its own thread, consuming from MD and order event queues
68public:
69 // The file extension of a strategy plugin: what CMake gives a shared library on this
70 // platform, and what load_strategies() looks for in the plugins folder.
71#if defined(_WIN32)
72 static constexpr std::string_view PLUGIN_EXTENSION = ".dll";
73#elif defined(__APPLE__)
74 static constexpr std::string_view PLUGIN_EXTENSION = ".dylib";
75#else
76 static constexpr std::string_view PLUGIN_EXTENSION = ".so";
77#endif
78
80 const json& config,
81 PositionTracker& position_tracker,
82 PnLCalculator& pnl_calculator,
83 RiskManager& risk_manager,
84 slick::stream_buffer_multiplexer& event_mux,
85 MdRequestQueues& md_request_queues,
86 slick::queue<uint8_t>& order_request_queue
87 );
88
90 stop();
91 }
92
93 void load_strategies(const json& config);
94
95 // Strategy registration
96 void add_strategy(std::shared_ptr<IStrategy> strategy);
97
98 void start();
99 void stop();
100
101 void shutdown() {
102 LOG_INFO("StrategyManager: Shutting down");
103
104 for (auto& strategy : strategies_) {
105 if (strategy) {
106 strategy->shutdown();
107 }
108 }
109 }
110
111 bool is_running() const {
112 return running_.load(std::memory_order_acquire);
113 }
114
115 // Get all strategies (for subscription collection)
116 const std::vector<std::shared_ptr<IStrategy>>& get_all_strategies() const {
117 return strategies_;
118 }
119
120 std::shared_ptr<IStrategy> get_strategy(const std::string& strategy_id) const {
121 auto it = strategy_map_.find(strategy_id);
122 if (it != strategy_map_.end()) {
123 return it->second;
124 }
125 return nullptr;
126 }
127
128 // Manual strategy control — clears auto-pause state so MD reconnect won't override
129 bool start_strategy(const std::string& strategy_id);
130 bool stop_strategy(const std::string& strategy_id);
131
132 bool is_auto_paused(const std::string& strategy_id) const {
133 return auto_paused_strategies_.count(strategy_id) > 0;
134 }
135
136 const std::string& get_auto_pause_reason(const std::string& strategy_id) const {
137 static const std::string empty;
138 auto it = auto_pause_reasons_.find(strategy_id);
139 return it != auto_pause_reasons_.end() ? it->second : empty;
140 }
141
142 // The strategy holding the Web UI's orders and the instruments it ladders. Null until one
143 // is added, which is before any other thread runs.
144 const ManualStrategy* manual() const noexcept { return manual_.get(); }
145
146 // Keeps the L2 book of each of `instruments` for the strategies: on_order_book(), and
147 // quotes and marks from its top.
148 void subscribe_book_update(const std::vector<std::string>& instruments) {
149 for (const auto& instrument : instruments) {
150 // One observer per book, however many subscription types feed it: a second
151 // one would hand every update to the strategies twice.
152 if (l2_books_.contains(instrument)) {
153 continue;
154 }
155 const auto sid = get_or_create_symbol_id(instrument);
156 if (!sid) {
157 continue;
158 }
159 auto *book = book_manager_.getOrCreateOrderBook(*sid);
160 auto observer = std::make_shared<OrderBookObserverImpl>(this, *book, instrument);
161 book->addObserver(observer);
162 l2_books_.emplace(instrument, book);
163
164 // The L2 book is now this instrument's source of quotes.
165 if (auto it = mbo_books_.find(instrument); it != mbo_books_.end()) {
166 it->second->publishes_top = false;
167 }
168 }
169 }
170
171 // Dispatches one event exactly as the worker thread does. While the manager runs the
172 // worker is the only caller; it is public so a replay or a test can drive the manager
173 // without the thread.
174 void process_event(const Event* event);
175
176 // The market-by-order book of an instrument, or nullptr when none was subscribed or
177 // published. Owned by the worker thread: read it from there (a strategy callback).
178 const slick::orderbook::OrderBookL3* get_order_book_l3(std::string_view instrument) const {
179 const auto it = mbo_books_.find(instrument);
180 return it != mbo_books_.end() ? &it->second->book : nullptr;
181 }
182
183private:
185
186 void run();
187
188 // `book`: whether to keep the book for the strategies too. Not for MANUAL's, which stream
189 // to the Web UI alone: a venue's worth would take a 16-bit book id each, and its quotes and
190 // marks on every change.
191 void subscribe(const SubscriptionRequest& sub, bool book = true);
192 void unsubscribe(const SubscriptionRequest& sub);
193
194 void check_loss_limits();
195 void check_broker_status();
196 void dispatch_strategy_config(const StrategyConfigEvent& event);
197
198 // Sends SUBSCRIBE or UNSUBSCRIBE requests for `instruments` to the request's broker, as
199 // many as it takes to keep each within max_instruments_per_request(). Each goes straight
200 // into the queue if none waits ahead of it and its connector has room, else to the outbox.
201 void publish_subscription(EventType type, const SubscriptionRequest& sub,
202 const std::vector<std::string>& instruments);
203 static size_t max_instruments_per_request(const slick::queue<uint8_t>& queue);
204
205 // A request queue is lossy: a request written a queue's length past where its connector
206 // is reading overwrites one it has not read. has_room() says whether a request of `size`
207 // fits in broker `i`'s queue without that, going by request_cursor(), where it reads.
208 bool has_room(size_t i, const slick::queue<uint8_t>& queue, uint32_t size) const;
209 uint64_t request_cursor(size_t i) const;
210
211 // send_requests() publishes each broker's waiting requests, oldest first, while its
212 // connector has room for them, and returns whether it sent them all. One that read nothing
213 // in md_request_stall_timeout_ms is reported, and still waited on: it would lose them
214 // otherwise. drain_requests() waits for them all, and gives up on a connector there alone.
215 bool send_requests(std::chrono::steady_clock::time_point now);
216 void drain_requests();
217 static constexpr auto REQUEST_RETRY_INTERVAL = std::chrono::milliseconds(1);
218
219 // Has MANUAL list `instrument` if its config takes it.
220 void list(BrokerId broker, std::string_view instrument, price_t tick_size, qty_t min_qty);
221 // A ladder holding or releasing an instrument of MANUAL's, from the WebServer.
222 void dispatch_ladder_subscription(const LadderSubscriptionEvent& event);
223 // Whether any strategy subscribes any kind of data of `instrument` at `broker`.
224 bool subscribed(BrokerId broker, std::string_view instrument) const;
225
226 void dispatch_trade(const TradeEvent& event);
227 void dispatch_quote(const QuoteEvent& event);
228 void dispatch_level2_updates(const Level2UpdateEvent& event);
229 void dispatch_mbo_update(const MboUpdateEvent& event);
230 void dispatch_instrument_status(const InstrumentStatusEvent& event);
231
232 void on_top_of_book_update(const std::string &instrument, const slick::orderbook::TopOfBook& tob);
233 void on_order_book_update(const std::string& instrument, const slick::orderbook::OrderBookL2& book);
234 void dispatch_order_book(const OrderBookEvent& event);
235 // The L2 book kept for `instrument`, or nullptr when no strategy subscribed it.
236 slick::orderbook::OrderBookL2* find_l2_book(std::string_view instrument) const {
237 const auto it = l2_books_.find(instrument);
238 return it != l2_books_.end() ? it->second : nullptr;
239 }
240
241 // Nothing once every SymbolId (16 bits) is taken: a book refused beats two sharing one.
242 std::optional<slick::orderbook::SymbolId> get_or_create_symbol_id(std::string_view instrument);
243
244 // One instrument's market-by-order book. Held here rather than in an OrderBookManager,
245 // whose lookup takes a shared lock: only the worker thread touches these.
246 struct MboBook {
247 MboBook(slick::orderbook::SymbolId symbol, std::string name, bool publishes_top_of_book)
248 : book(symbol, TOP_LEVELS, INITIAL_ORDERS, INITIAL_LEVELS)
249 , instrument(std::move(name))
250 , publishes_top(publishes_top_of_book)
251 {}
252
253 // Sized so a liquid futures book never grows on the dispatch path.
254 static constexpr std::size_t TOP_LEVELS = 10;
255 static constexpr std::size_t INITIAL_ORDERS = 16384;
256 static constexpr std::size_t INITIAL_LEVELS = 256;
257
258 slick::orderbook::OrderBookL3 book;
259 std::string instrument;
260 slick::orderbook::TopOfBook top; // the last top of book published from this book
261 bool publishes_top; // false once an L2 book of the instrument publishes it
262 };
263 MboBook& get_or_create_mbo_book(std::string_view instrument);
264
265 void dispatch_order_ack(const OrderAckEvent& event);
266 void dispatch_order_fill(const OrderFillEvent& event);
267 void dispatch_order_reject(const OrderRejectEvent& event);
268 void dispatch_order_cancel(const OrderCancelEvent& event);
269 void dispatch_instrument_definition(const InstrumentDefinitionEvent& event);
270
271private:
272 std::vector<std::shared_ptr<IStrategy>> strategies_;
273 std::unordered_map<std::string, std::shared_ptr<IStrategy>> strategy_map_;
274 std::shared_ptr<ManualStrategy> manual_; // also in strategies_; null until one is added
275
276 static constexpr size_t BROKER_COUNT = static_cast<size_t>(BrokerId::_BROKER_ID_COUNT_);
277 // Every instrument each broker defined, with its tick, so a list MANUAL is given later takes them too.
278 struct Defined {
279 price_t tick_size;
280 qty_t min_qty;
281 };
282 std::array<StringMap<Defined>, BROKER_COUNT> defined_;
283 // Whole MDSubscription records not yet published, by broker.
284 std::array<std::deque<std::vector<uint8_t>>, BROKER_COUNT> request_outbox_;
285 size_t requests_queued_{0};
286 std::chrono::steady_clock::time_point last_request_send_{};
287 std::array<uint64_t, BROKER_COUNT> request_baseline_{}; // each queue's index when this manager was made
288 std::chrono::milliseconds reader_stall_timeout_;
289 // A broker whose next request waits on its connector: where that was reading, since when,
290 // and whether it was reported, which it is once it has read nothing in reader_stall_timeout_.
291 struct RequestWait {
292 uint64_t cursor = 0;
293 std::chrono::steady_clock::time_point since{};
294 bool reported = false;
295 };
296 std::array<RequestWait, BROKER_COUNT> request_waits_{};
297 slick::orderbook::OrderBookManager<slick::orderbook::OrderBookL2> book_manager_;
298 // Instruments are looked up as they arrive in events, without building a string.
299 std::unordered_map<std::string, slick::orderbook::SymbolId, StringHash, std::equal_to<>> symbol_ids_;
300 // How many strategies hold each subscription. Keyed by all three of broker, type and
301 // instrument: trades and the book of one instrument are separate requests to the broker.
302 using SubscriptionKey = std::tuple<BrokerId, SubscriptionType, std::string>;
303 std::map<SubscriptionKey, uint32_t> subscriptions_;
304 // The L2 books kept for the strategies, each with its observer. Held here so an event finds
305 // its book without the manager's lock: only the worker thread touches them.
306 std::unordered_map<std::string, slick::orderbook::OrderBookL2*, StringHash, std::equal_to<>> l2_books_;
307 std::unordered_map<std::string, std::unique_ptr<MboBook>, StringHash, std::equal_to<>> mbo_books_;
308 std::unordered_map<std::string, std::set<BrokerId>> strategy_md_brokers_;
309 std::unordered_set<std::string> auto_paused_strategies_;
310 std::unordered_map<std::string, std::string> auto_pause_reasons_;
311 slick::orderbook::SymbolId next_symbol_id_{0};
312
313 // Position & PnL tracking (non-owning pointers)
314 PositionTracker& position_tracker_;
315 PnLCalculator& pnl_calculator_;
316 RiskManager& risk_manager_;
317
318 slick::stream_buffer_multiplexer& event_mux_;
319 MdRequestQueues& md_request_queues_;
320 slick::queue<uint8_t>& order_request_queue_;
321 std::shared_ptr<producer_buffer> tob_producer_buffer_;
322
323 std::string strategy_plugins_folder_;
324 std::string strategy_configs_folder_;
325 StrategyLoader loader_;
326
327 std::atomic_bool running_{false};
328 std::thread worker_thread_;
329 uint64_t event_cursor_{0};
330};
331
332inline void OrderBookObserverImpl::onPriceLevelUpdate(const slick::orderbook::PriceLevelUpdate& update) {
333 manager_->on_order_book_update(instrument_, order_book_);
334}
335
336inline void OrderBookObserverImpl::onTopOfBookUpdate(const slick::orderbook::TopOfBook& tob) {
337 manager_->on_top_of_book_update(instrument_, tob);
338}
339
340} // namespace slick::trader
bool is_auto_paused(const std::string &strategy_id) const
const std::string & get_auto_pause_reason(const std::string &strategy_id) const
const slick::orderbook::OrderBookL3 * get_order_book_l3(std::string_view instrument) 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)
const std::vector< std::shared_ptr< IStrategy > > & get_all_strategies() const
void subscribe_book_update(const std::vector< std::string > &instruments)
static constexpr std::string_view PLUGIN_EXTENSION
int64_t qty_t
Definition types.hpp:17
int64_t price_t
Definition types.hpp:16
slick::stream_buffer_multiplexer::multiplex_record multiplex_record
nlohmann::json json
slick::orderbook::IOrderBookObserver OrderBookObserver
slick::stream_buffer_multiplexer::producer_buffer producer_buffer
void onTopOfBookUpdate(const slick::orderbook::TopOfBook &tob) override
OrderBookObserverImpl(StrategyManager *manager, slick::orderbook::OrderBookL2 &order_book, const std::string &instrument)
void onPriceLevelUpdate(const slick::orderbook::PriceLevelUpdate &update) override
~OrderBookObserverImpl() override=default