Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
order_book_publisher.hpp
Go to the documentation of this file.
1#pragma once
2
12#include <slick/logger.hpp>
13#include <algorithm>
14#include <cstdint>
15#include <functional>
16#include <string>
17#include <string_view>
18#include <unordered_map>
19#include <utility>
20#include <vector>
21
22namespace slick::trader {
23
24// One order of an order-by-order feed changing, in the exchange's wire units.
26 enum class Action : uint8_t { ADD, CHANGE, REMOVE };
27
28 uint64_t order_id = 0;
29 uint64_t priority = 0; // place in the queue at its price: lower trades first
33 int64_t price = 0;
34 int64_t prev_price = 0;
35 int64_t qty = 0; // lots shown; 0 when not on the book
36 int64_t prev_qty = 0;
37 uint64_t event_time = 0; // the exchange's time, ns
38};
39
40// The exchange-neutral half of a market-by-order channel: from order changes in wire
41// units to SlickTrader's price levels, order-by-order updates, trades and trading status.
42//
43// Every listed instrument's levels are kept, subscribed or not, so a later subscription
44// is answered with a snapshot at once. At each end of an exchange event the changed
45// levels of every instrument subscribed for levels are published, the order changes of
46// every instrument subscribed order by order (SubscriptionType::MBO), and trades as they
47// arrive. When the book is built or rebuilt after a gap each subscribed instrument gets
48// a full snapshot of levels, orders, or both. Each instrument's best bid and offer
49// go to its SharedTopOfBook, if it has one, for the order side.
50//
51// CRTP, so nothing per order goes through a virtual call. `Derived` supplies:
52// bool live() const - the book is in sequence
53// void for_each_resting_order(Key, F&& f) - f(const BookOrderChange&) per resting order
54// `Instrument` has `symbol` (std::string), `scale` (PriceScale) and `top`
55// (SharedTopOfBook*, may be null). `Sink` takes, on the thread driving the channel:
56// publish_trade(const Instrument&, price_t, qty_t, Side aggressor, uint64_t time)
57// publish_levels(const Instrument&, const std::vector<PriceLevel>&, bool snapshot, uint64_t time, uint64_t seq)
58// publish_orders(const Instrument&, const std::vector<MboOrder>&, bool snapshot, uint64_t time, uint64_t seq)
59// publish_status(const Instrument&, TradingStatus, bool cancel_allowed, std::string_view reason, uint64_t time)
60//
61// Single-threaded.
62template <typename Derived, typename Instrument, typename Sink, typename Key = int32_t>
64public:
65 enum class Listing : uint8_t {
66 LISTED, // on this channel
67 PENDING, // not known yet: the channel has not learned its instruments
68 UNKNOWN, // not on this channel
69 };
70
71 Listing subscribe(std::string_view symbol, SubscriptionType type) {
72 if (!instruments_known_) {
73 pending_.emplace_back(std::string(symbol), type);
74 return Listing::PENDING;
75 }
76 auto it = by_symbol_.find(symbol);
77 if (it == by_symbol_.end()) {
78 return Listing::UNKNOWN;
79 }
80 apply_subscription(states_[it->second], type);
81 return Listing::LISTED;
82 }
83
84 void unsubscribe(std::string_view symbol, SubscriptionType type) {
85 std::erase_if(pending_, [&](const auto& p) { return p.first == symbol && p.second == type; });
86 auto it = by_symbol_.find(symbol);
87 if (it == by_symbol_.end()) {
88 return;
89 }
90 auto& state = states_[it->second];
91 subscribed(state, type) = false;
92 if (!state.orders) {
93 state.order_updates.clear();
94 }
95 }
96
97 [[nodiscard]] const Instrument* find(std::string_view symbol) const {
98 auto it = by_symbol_.find(symbol);
99 return it == by_symbol_.end() ? nullptr : &states_.at(it->second).instrument;
100 }
101
102 // The channel knows which instruments it lists.
103 [[nodiscard]] bool instruments_known() const noexcept { return instruments_known_; }
104
105protected:
107 Instrument instrument;
108 Key key{};
110 bool trades = false;
111 bool levels = false;
112 bool orders = false; // subscribed order by order
113 bool touched = false; // changed in the current event
115 bool cancel_allowed = true;
116 // What the instrument's SharedTopOfBook was last given.
119 uint64_t last_time = 0;
120 std::vector<MboOrder> order_updates; // the current event's, for an order subscriber
121 };
122
123 OrderBookPublisher(Sink& sink, std::string who) : sink_(sink), who_(std::move(who)) {}
124
125 // Lists an instrument. It replaces one already listed under `key`.
126 InstrumentState& add_instrument(Key key, Instrument instrument) {
127 by_symbol_.insert_or_assign(instrument.symbol, key);
128 auto& state = states_[key];
129 state.instrument = std::move(instrument);
130 state.key = key;
131 return state;
132 }
133
134 // Every instrument is listed: the subscriptions that waited for them are applied.
136 instruments_known_ = true;
137 auto pending = std::move(pending_);
138 pending_.clear();
139 for (const auto& [symbol, type] : pending) {
140 auto it = by_symbol_.find(symbol);
141 if (it != by_symbol_.end()) {
142 apply_subscription(states_[it->second], type);
143 }
144 }
145 }
146
147 [[nodiscard]] InstrumentState* state_of(Key key) {
148 auto it = states_.find(key);
149 return it == states_.end() ? nullptr : &it->second;
150 }
151 [[nodiscard]] std::unordered_map<Key, InstrumentState>& states() noexcept { return states_; }
152 [[nodiscard]] Sink& sink() noexcept { return sink_; }
153 [[nodiscard]] const std::string& who() const noexcept { return who_; }
154
155 // Room for `n` instruments up front.
156 void reserve_instruments(size_t n) { states_.reserve(n); }
157
158 // One order changed. Its instrument publishes at end_of_event(). With
159 // `publish_order` false the change reaches the levels only: an order the exchange
160 // re-listed under a new id, whose subscribers still know it by its old one.
161 void apply_order(Key key, const BookOrderChange& u, bool publish_order = true) {
162 auto it = states_.find(key);
163 if (it == states_.end()) {
164 return;
165 }
166 auto& state = it->second;
167 state.book.apply(u.prev_side, u.prev_price, u.prev_qty, u.side, u.price, u.qty);
168 state.last_time = u.event_time;
169 // While the book is being rebuilt nothing is published order by order: the
170 // snapshot that follows the rebuild carries it whole.
171 if (publish_order && state.orders && derived().live()) {
172 append_order(state.order_updates, state.instrument, u);
173 }
174 if (!state.touched) {
175 state.touched = true;
176 touched_.push_back(key);
177 }
178 }
179
180 // A trade, published at once to the instrument's trade subscribers.
181 void trade(Key key, int64_t wire_price, int64_t lots, Side aggressor, uint64_t event_time) {
182 auto it = states_.find(key);
183 if (it == states_.end() || !it->second.trades) {
184 return;
185 }
186 const auto& instrument = it->second.instrument;
187 price_t price;
188 if (!instrument.scale.to_price(wire_price, price)) {
189 LOG_WARN("{}: trade price {} of {} is off its scale - dropped", who_, wire_price, instrument.symbol);
190 return;
191 }
192 sink_.publish_trade(instrument, price, lots_to_qty(lots), aggressor, event_time);
193 }
194
195 // The exchange event is complete: what it changed is published.
197 const bool in_sequence = derived().live();
198 for (const Key key : touched_) {
199 auto& state = states_[key];
200 state.touched = false;
201 // While the book is being rebuilt its top is not the market's: it stays unknown
202 // until book_rebuilt().
203 if (in_sequence && state.instrument.top) {
204 publish_top(state);
205 }
206 if (!state.order_updates.empty()) {
207 sink_.publish_orders(state.instrument, state.order_updates, false, state.last_time, ++order_sequence_);
208 state.order_updates.clear();
209 }
210 if (!state.levels) {
211 state.book.flush([](const LevelBook::LevelChange&) {});
212 continue;
213 }
214 levels_.clear();
215 state.book.flush([&](const LevelBook::LevelChange& change) {
216 bool ok = false;
217 const auto level = to_level(state.instrument, change, ok);
218 if (ok) {
219 levels_.push_back(level);
220 }
221 });
222 if (!levels_.empty()) {
223 sink_.publish_levels(state.instrument, levels_, false, state.last_time, ++level_sequence_);
224 }
225 }
226 touched_.clear();
227 }
228
229 // Publishes the instrument's trading state if it changed.
230 void set_status(InstrumentState& state, TradingStatus status, bool cancel_allowed, std::string_view reason,
231 uint64_t event_time) {
232 if (status == state.status && cancel_allowed == state.cancel_allowed) {
233 return;
234 }
235 state.status = status;
236 state.cancel_allowed = cancel_allowed;
237 sink_.publish_status(state.instrument, status, cancel_allowed, reason, event_time);
238 }
239
240 // The book fell out of sequence: what it showed may no longer be so, and nothing is
241 // checked against it now.
242 void book_gap() {
243 for (auto& [key, state] : states_) {
244 if (state.instrument.top) {
246 }
247 }
248 }
249
250 // Forgets every level, for a feed that will build its book again from nothing. The
251 // tops read unknown until book_rebuilt().
252 void clear_books() {
253 for (auto& [key, state] : states_) {
254 state.book = LevelBook{};
255 state.touched = false;
256 state.order_updates.clear();
257 }
258 touched_.clear();
259 book_gap();
260 }
261
262 // The book is built, or rebuilt after a gap. Its own changes were published as they
263 // were applied; a snapshot as well makes every subscriber's book exactly this one,
264 // whatever it held.
266 for (auto& [key, state] : states_) {
267 if (state.instrument.top) {
268 publish_top(state);
269 }
270 if (state.levels) {
271 publish_snapshot(state);
272 }
273 if (state.orders) {
274 publish_order_snapshot(state);
275 }
276 }
277 }
278
279private:
280 [[nodiscard]] Derived& derived() noexcept { return static_cast<Derived&>(*this); }
281 [[nodiscard]] const Derived& derived() const noexcept { return static_cast<const Derived&>(*this); }
282
283 // The flag of `state` a subscription of `type` sets.
284 static bool& subscribed(InstrumentState& state, SubscriptionType type) noexcept {
285 switch (type) {
287 return state.trades;
289 return state.orders;
290 default:
291 return state.levels; // quotes and both kinds of book are served from the levels
292 }
293 }
294
295 void apply_subscription(InstrumentState& state, SubscriptionType type) {
296 bool& flag = subscribed(state, type);
297 if (flag) {
298 return;
299 }
300 flag = true;
301 // A new book subscriber starts from the whole book: at once if it is built,
302 // otherwise when it is.
303 if (derived().live()) {
304 if (&flag == &state.levels) {
305 publish_snapshot(state);
306 } else if (&flag == &state.orders) {
307 publish_order_snapshot(state);
308 }
309 }
310 }
311
312 static PriceLevel to_level(const Instrument& instrument, const LevelBook::LevelChange& change, bool& ok) {
313 // PriceLevel is packed: to_price() gets a local, not a reference to its field.
314 price_t price = 0;
315 ok = instrument.scale.to_price(change.price, price);
316 PriceLevel level;
317 level.price = price;
318 level.quantity = lots_to_qty(change.qty > 0 ? change.qty : 0);
319 level.num_orders = change.qty > 0 ? change.orders : 0;
320 level.side = change.side;
321 return level;
322 }
323
324 // Appends `u` to `out` as a subscriber's book applies it.
325 static void append_order(std::vector<MboOrder>& out, const Instrument& instrument, const BookOrderChange& u) {
326 const MboOrder gone{u.order_id, 0, 0, 0, u.prev_side, MboAction::REMOVE};
327 if (u.action == BookOrderChange::Action::REMOVE) {
328 out.push_back(gone);
329 return;
330 }
331 const bool changed = u.action == BookOrderChange::Action::CHANGE;
332 price_t price;
333 if (!instrument.scale.to_price(u.price, price)) {
334 // A price the framework cannot express: the order cannot be shown, and one
335 // shown at its old price must not stay there.
336 if (changed) {
337 out.push_back(gone);
338 }
339 return;
340 }
341 // An order book keeps an order on its side, so one that changed side leaves and
342 // comes back.
343 const bool same_side = u.prev_side == u.side;
344 if (changed && !same_side) {
345 out.push_back(gone);
346 }
347 out.push_back(MboOrder{u.order_id, u.priority, price, lots_to_qty(u.qty), u.side,
348 changed && same_side ? MboAction::MODIFY : MboAction::ADD});
349 }
350
351 void publish_snapshot(InstrumentState& state) {
352 levels_.clear();
353 state.book.for_each_level([&](const LevelBook::LevelChange& change) {
354 bool ok = false;
355 const auto level = to_level(state.instrument, change, ok);
356 if (ok) {
357 levels_.push_back(level);
358 }
359 });
360 sink_.publish_levels(state.instrument, levels_, true, state.last_time, ++level_sequence_);
361 }
362
363 void publish_order_snapshot(InstrumentState& state) {
364 orders_.clear();
365 derived().for_each_resting_order(state.key, [&](const BookOrderChange& order) {
366 append_order(orders_, state.instrument, order);
367 });
368 // Whatever this event has changed so far is in the snapshot already.
369 state.order_updates.clear();
370 sink_.publish_orders(state.instrument, orders_, true, state.last_time, ++order_sequence_);
371 }
372
373 // Stores what changed of the two; the order worker reads them.
374 static void set_top(InstrumentState& state, price_t bid, price_t ask) noexcept {
375 SharedTopOfBook& top = *state.instrument.top;
376 if (bid != state.top_bid) {
377 state.top_bid = bid;
378 top.bid.store(bid, std::memory_order_release);
379 }
380 if (ask != state.top_ask) {
381 state.top_ask = ask;
382 top.ask.store(ask, std::memory_order_release);
383 }
384 }
385
386 // Gives the instrument's SharedTopOfBook the book's best bid and offer.
387 static void publish_top(InstrumentState& state) {
388 const auto best = [&](Side side) {
389 const int64_t wire = state.book.best(side);
390 if (wire == LevelBook::NO_PRICE) {
392 }
393 price_t price;
394 // A price the framework cannot express is one nothing can be checked against.
395 return state.instrument.scale.to_price(wire, price) ? price : SharedTopOfBook::UNKNOWN;
396 };
397 set_top(state, best(Side::BUY), best(Side::SELL));
398 }
399
400 Sink& sink_;
401 std::string who_;
402 bool instruments_known_ = false;
403 std::unordered_map<Key, InstrumentState> states_;
404 std::unordered_map<std::string, Key, StringHash, std::equal_to<>> by_symbol_;
405 // Subscriptions made before the instruments were known.
406 std::vector<std::pair<std::string, SubscriptionType>> pending_;
407 std::vector<Key> touched_;
408 std::vector<PriceLevel> levels_; // reused for each publish
409 std::vector<MboOrder> orders_; // reused for each order snapshot
410 uint64_t level_sequence_ = 0;
411 uint64_t order_sequence_ = 0;
412};
413
414} // namespace slick::trader
static constexpr int64_t NO_PRICE
void set_status(InstrumentState &state, TradingStatus status, bool cancel_allowed, std::string_view reason, uint64_t event_time)
void unsubscribe(std::string_view symbol, SubscriptionType type)
std::unordered_map< Key, InstrumentState > & states() noexcept
void apply_order(Key key, const BookOrderChange &u, bool publish_order=true)
void trade(Key key, int64_t wire_price, int64_t lots, Side aggressor, uint64_t event_time)
Listing subscribe(std::string_view symbol, SubscriptionType type)
InstrumentState & add_instrument(Key key, Instrument instrument)
const std::string & who() const noexcept
OrderBookPublisher(Sink &sink, std::string who)
const Instrument * find(std::string_view symbol) const
qty_t lots_to_qty(int64_t lots) noexcept
int64_t price_t
Definition types.hpp:16
static constexpr price_t UNKNOWN