Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
level2_book.hpp
Go to the documentation of this file.
1#pragma once
2
7#include <algorithm>
8#include <charconv>
9#include <cmath>
10#include <cstdint>
11#include <functional>
12#include <iterator>
13#include <string>
14#include <string_view>
15#include <type_traits>
16#include <unordered_map>
17#include <unordered_set>
18#include <vector>
19
20namespace slick::trader {
21
22// One instrument's price levels as its LEVEL2_UPDATE events leave them, so a browser that
23// subscribes after the broker's snapshot went by can still start from the book.
24// Single-threaded: the WebServer's event loop owns it. Events are applied as they come, with
25// no sequence check: one connector publishes an instrument's book, in order, so a snapshot
26// is never late. Two publishing the same instrument would need one.
27// It keeps, and hands over, every level: a broker sends a snapshot only as it subscribes, so a
28// level left out would be missing from a subscriber's ladder once the price moved to it.
30public:
31 // An event with more levels than this is merged into the book in one pass.
32 static constexpr uint16_t MERGE_FROM = 64;
33
34 void apply(const Level2UpdateEvent& event) {
35 // Only the first part of a snapshot carries is_snapshot: it clears, the rest add.
36 if (event.is_snapshot) {
37 bids_.clear();
38 asks_.clear();
39 }
40 // A snapshot, or a part of one, is merged: a broker lists it best first, and set() would
41 // put each level in at the front of its side, moving all the others, O(n^2) over a deep
42 // book. A delta's few levels, most near the top, are set one by one.
43 if (event.num_levels > MERGE_FROM) {
44 merge(bids_, event, Side::BUY, std::less<price_t>{});
45 merge(asks_, event, Side::SELL, std::greater<price_t>{});
46 } else {
47 for (uint16_t i = 0; i < event.num_levels; ++i) {
48 // Copied out of the packed event before they bind to a reference.
49 const price_t price = event.levels[i].price;
50 const qty_t qty = event.levels[i].quantity;
51 if (event.levels[i].side == Side::BUY) {
52 set(bids_, price, qty, std::less<price_t>{});
53 } else {
54 set(asks_, price, qty, std::greater<price_t>{});
55 }
56 }
57 }
58 event_time_ns_ = event.event_time_ns;
59 sequence_num_ = event.sequence_num;
60 broker_ = event.broker_id;
61 }
62
63 // Calls `f(price, qty, side)` for every level, bids then asks, each from its best.
64 template <typename F>
65 void for_each(F&& f) const {
66 for (auto it = bids_.rbegin(); it != bids_.rend(); ++it) {
67 f(it->price, it->qty, Side::BUY);
68 }
69 for (auto it = asks_.rbegin(); it != asks_.rend(); ++it) {
70 f(it->price, it->qty, Side::SELL);
71 }
72 }
73
74 size_t size() const noexcept { return bids_.size() + asks_.size(); }
75 BrokerId broker() const noexcept { return broker_; } // UNKNOWN until an event came
76 uint64_t event_time_ns() const noexcept { return event_time_ns_; }
77 uint64_t sequence_num() const noexcept { return sequence_num_; }
78
79private:
80 struct Level {
81 price_t price;
82 qty_t qty;
83 };
84
85 // Sets one level of a side kept worst first, so the best, where most changes land, moves
86 // least. `worse(a, b)`: price a is worse than b, which is lower for bids, higher for asks.
87 template <typename Worse>
88 static void set(std::vector<Level>& side, price_t price, qty_t qty, Worse worse) {
89 const auto it = std::lower_bound(side.begin(), side.end(), price,
90 [&](const Level& level, price_t p) { return worse(level.price, p); });
91 if (it != side.end() && it->price == price) {
92 if (qty == 0) {
93 side.erase(it);
94 } else {
95 it->qty = qty;
96 }
97 } else if (qty != 0) {
98 side.insert(it, Level{price, qty});
99 }
100 }
101
102 // Merges the levels of `event` on side `s` into `side`, as set() would one by one: a price
103 // listed twice takes its last quantity, and a quantity of 0 removes its level.
104 template <typename Worse>
105 static void merge(std::vector<Level>& side, const Level2UpdateEvent& event, Side s, Worse worse) {
106 std::vector<Level> changes;
107 for (uint16_t i = 0; i < event.num_levels; ++i) {
108 if (event.levels[i].side == s) {
109 changes.push_back(Level{event.levels[i].price, event.levels[i].quantity});
110 }
111 }
112 if (changes.empty()) {
113 return;
114 }
115 std::stable_sort(changes.begin(), changes.end(),
116 [&](const Level& a, const Level& b) { return worse(a.price, b.price); });
117 std::vector<Level> merged;
118 merged.reserve(side.size() + changes.size());
119 auto kept = side.begin();
120 for (size_t i = 0; i < changes.size(); ++i) {
121 if (i + 1 < changes.size() && changes[i + 1].price == changes[i].price) {
122 continue; // the price comes again, later in the event
123 }
124 const Level& change = changes[i];
125 while (kept != side.end() && worse(kept->price, change.price)) {
126 merged.push_back(*kept++);
127 }
128 if (kept != side.end() && kept->price == change.price) {
129 ++kept; // set again, or removed
130 }
131 if (change.qty != 0) {
132 merged.push_back(change);
133 }
134 }
135 merged.insert(merged.end(), kept, side.end());
136 side.swap(merged);
137 }
138
139 std::vector<Level> bids_; // ascending
140 std::vector<Level> asks_; // descending
142 uint64_t event_time_ns_{0};
143 uint64_t sequence_num_{0};
144};
145
146// Appends `text` to `out` as a JSON string.
147inline void append_json_string(std::string& out, std::string_view text) {
148 out += '"';
149 for (const char c : text) {
150 if (c == '"' || c == '\\') {
151 out += '\\';
152 out += c;
153 } else if (static_cast<unsigned char>(c) < 0x20) {
154 constexpr char HEX[] = "0123456789abcdef";
155 out += "\\u00";
156 out += HEX[(c >> 4) & 0xf];
157 out += HEX[c & 0xf];
158 } else {
159 out += c;
160 }
161 }
162 out += '"';
163}
164
165// Appends `value` to `out` as a JSON number, in the fewest digits that read back as it.
166// null when it is not finite, as JSON has no NaN.
167template <typename T>
168void append_json_number(std::string& out, T value) {
169 if constexpr (std::is_floating_point_v<T>) {
170 if (!std::isfinite(value)) {
171 out += "null";
172 return;
173 }
174 }
175 char digits[32];
176 out.append(digits, std::to_chars(std::begin(digits), std::end(digits), value).ptr);
177}
178
179// Writes the dashboard's level2 message into `out`, cleared first so one buffer and its
180// capacity serve every message: {"type":"level2","instrument":...,"timestamp":<ms>,"seq_num":...,
181// "is_snapshot":...,"levels":[[price,quantity,side],...]}. `for_each_level(emit)` calls
182// emit(price, qty, side) for each level, as Level2Book::for_each() does.
183template <typename ForEachLevel>
184void write_level2_message(std::string& out, std::string_view instrument, uint64_t event_time_ns,
185 uint64_t sequence_num, bool is_snapshot, ForEachLevel&& for_each_level) {
186 out.assign(R"({"type":"level2","instrument":)");
187 append_json_string(out, instrument);
188 out += R"(,"timestamp":)";
189 append_json_number(out, event_time_ns / 1'000'000);
190 out += R"(,"seq_num":)";
191 append_json_number(out, sequence_num);
192 out += is_snapshot ? R"(,"is_snapshot":true,"levels":[)" : R"(,"is_snapshot":false,"levels":[)";
193 const size_t first = out.size();
194 for_each_level([&](price_t price, qty_t qty, Side side) {
195 out += out.size() == first ? "[" : ",[";
196 append_json_number(out, from_price_t(price));
197 out += ',';
199 out += ',';
200 append_json_number(out, static_cast<int>(side));
201 out += ']';
202 });
203 out += "]}";
204}
205
206// The last trade of an instrument, as a ladder's LTQ column shows it. `side` is the aggressor's,
207// UNKNOWN when the broker did not say; qty 0 is no trade yet.
213
214// Writes the dashboard's trade message into `out`, cleared first as write_level2_message() does:
215// {"type":"trade","instrument":...,"price":...,"qty":...,"side":<0 buy, 1 sell, 2 unknown>}.
216inline void write_trade_message(std::string& out, std::string_view instrument, const LastTrade& trade) {
217 out.assign(R"({"type":"trade","instrument":)");
218 append_json_string(out, instrument);
219 out += R"(,"price":)";
221 out += R"(,"qty":)";
222 append_json_number(out, from_qty_t(trade.qty));
223 out += R"(,"side":)";
224 append_json_number(out, static_cast<int>(trade.side));
225 out += '}';
226}
227
228// Every instrument's level 2 book as it streams, and the clients watching each. A book that has
229// streamed is kept, watched or not, for the life of the process: a client that subscribes late
230// starts from it. One only asked for goes with its last watcher, so what clients ask for cannot
231// grow this beyond what they watch.
232// Single-threaded: the WebServer's event loop owns it. `Client` is only compared and hashed.
233template <typename Client>
235public:
236 using Clients = std::unordered_set<Client*>;
237
238 // How many instruments one client may watch. A dashboard watches one, its ladder's.
239 static constexpr size_t MAX_STREAMS_PER_CLIENT = 1024;
240
241 // Applies `event` to its instrument's book and returns who watches it.
242 const Clients& apply(const Level2UpdateEvent& event) {
243 Stream& stream = stream_of(std::string_view(event.instrument));
244 stream.streamed = true;
245 ++stream.events;
246 stream.book.apply(event);
247 return stream.clients;
248 }
249
250 // Keeps `event` as the last trade of its instrument and returns who watches it. A trade for an
251 // instrument with no stream is dropped. Trades never create a stream, so a strategy's trade
252 // feed costs one lookup here.
253 const Clients& trade(const TradeEvent& event) {
254 static const Clients none;
255 const auto it = streams_.find(std::string_view(event.instrument));
256 if (it == streams_.end()) {
257 return none;
258 }
259 it->second.last_trade = LastTrade{event.price, event.quantity, event.side};
260 return it->second.clients;
261 }
262
263 // The last trade of `instrument`, nullptr when none came.
264 const LastTrade* last_trade(std::string_view instrument) const {
265 const auto it = streams_.find(instrument);
266 return it != streams_.end() && it->second.last_trade.qty != 0 ? &it->second.last_trade : nullptr;
267 }
268
269 // Adds `client` to the watchers of `instrument` and returns the book to send it as a
270 // snapshot, empty when nothing has streamed. Again on a repeat, as a client asks again when
271 // it builds its ladder anew. nullptr when refused: an empty name or one too long for an
272 // instrument, or a client watching MAX_STREAMS_PER_CLIENT already. Any other name is taken,
273 // as a broker may not have streamed a book it subscribed yet; the cap bounds the rest.
274 const Level2Book* subscribe(Client* client, std::string_view instrument) {
275 if (instrument.empty() || instrument.size() >= MAX_INSTRUMENT_LENGTH) {
276 return nullptr;
277 }
278 auto it = streams_.find(instrument);
279 if (it != streams_.end() && it->second.clients.contains(client)) {
280 return &it->second.book;
281 }
282 auto& watched = watching_[client];
283 if (watched.size() >= MAX_STREAMS_PER_CLIENT) {
284 return nullptr;
285 }
286 Stream& stream = it != streams_.end() ? it->second : stream_of(instrument);
287 stream.clients.insert(client);
288 watched.insert(&stream);
289 return &stream.book;
290 }
291
292 // Returns whether `client` was watching `instrument`.
293 bool unsubscribe(Client* client, std::string_view instrument) {
294 const auto it = streams_.find(instrument);
295 if (it == streams_.end() || it->second.clients.erase(client) == 0) {
296 return false;
297 }
298 watching_[client].erase(&it->second);
299 drop_if_unused(it->second);
300 return true;
301 }
302
303 // Drops `client` from the streams it watches, and from those alone. `unwatched(instrument)`
304 // is called for each it was the last watcher of.
305 template <typename F>
306 void remove(Client* client, F&& unwatched) {
307 const auto it = watching_.find(client);
308 if (it == watching_.end()) {
309 return;
310 }
311 for (Stream* stream : it->second) {
312 stream->clients.erase(client);
313 if (stream->clients.empty()) {
314 unwatched(stream->instrument); // before drop_if_unused() takes the name with it
315 }
316 drop_if_unused(*stream);
317 }
318 watching_.erase(it);
319 }
320 void remove(Client* client) {
321 remove(client, [](std::string_view) {});
322 }
323
324 // How many clients watch `instrument`.
325 size_t watchers(std::string_view instrument) const {
326 const auto it = streams_.find(instrument);
327 return it != streams_.end() ? it->second.clients.size() : 0;
328 }
329
330 // Its broker was told to stop streaming `instrument`: from here, the book goes stale once its
331 // events stop. renew(), as the broker is asked for it again, empties a book no event came for
332 // since, so a subscriber starts from the snapshot the broker sends, not from what it left. A
333 // book whose events kept coming, from a connector that streams on regardless, is current and
334 // kept: emptied, it would be built from increments alone.
335 void release(std::string_view instrument) {
336 if (const auto it = streams_.find(instrument); it != streams_.end()) {
337 it->second.released = true;
338 it->second.events_at_release = it->second.events;
339 }
340 }
341 void renew(std::string_view instrument) {
342 const auto it = streams_.find(instrument);
343 if (it == streams_.end() || !it->second.released) {
344 return;
345 }
346 Stream& stream = it->second;
347 stream.released = false;
348 if (stream.events == stream.events_at_release) {
349 stream.book = Level2Book{};
350 stream.last_trade = LastTrade{}; // stale along with the book
351 }
352 }
353
354 // How many streams are kept.
355 size_t size() const noexcept { return streams_.size(); }
356
357private:
358 struct Stream {
359 Clients clients;
360 Level2Book book;
361 LastTrade last_trade;
362 std::string_view instrument; // its key in streams_
363 bool streamed = false; // an event came for it
364 uint64_t events = 0; // how many came
365 bool released = false; // its broker was told to stop, as release() says
366 uint64_t events_at_release = 0;
367 };
368
369 Stream& stream_of(std::string_view instrument) {
370 auto it = streams_.find(instrument);
371 if (it == streams_.end()) {
372 it = streams_.try_emplace(std::string(instrument)).first;
373 it->second.instrument = it->first;
374 }
375 return it->second;
376 }
377
378 void drop_if_unused(Stream& stream) {
379 if (!stream.streamed && stream.clients.empty()) {
380 streams_.erase(streams_.find(stream.instrument));
381 }
382 }
383
384 // A map's elements stay put, so the pointers in watching_ hold until their stream is erased,
385 // which it is only once nobody watches it.
386 std::unordered_map<std::string, Stream, StringHash, std::equal_to<>> streams_;
387 std::unordered_map<Client*, std::unordered_set<Stream*>> watching_;
388};
389
390} // namespace slick::trader
size_t size() const noexcept
void apply(const Level2UpdateEvent &event)
uint64_t event_time_ns() const noexcept
void for_each(F &&f) const
uint64_t sequence_num() const noexcept
static constexpr uint16_t MERGE_FROM
BrokerId broker() const noexcept
std::unordered_set< Client * > Clients
size_t size() const noexcept
void release(std::string_view instrument)
void remove(Client *client, F &&unwatched)
size_t watchers(std::string_view instrument) const
void renew(std::string_view instrument)
static constexpr size_t MAX_STREAMS_PER_CLIENT
const Level2Book * subscribe(Client *client, std::string_view instrument)
bool unsubscribe(Client *client, std::string_view instrument)
const LastTrade * last_trade(std::string_view instrument) const
void remove(Client *client)
const Clients & apply(const Level2UpdateEvent &event)
const Clients & trade(const TradeEvent &event)
void write_level2_message(std::string &out, std::string_view instrument, uint64_t event_time_ns, uint64_t sequence_num, bool is_snapshot, ForEachLevel &&for_each_level)
double from_price_t(price_t value)
Definition types.hpp:36
void write_trade_message(std::string &out, std::string_view instrument, const LastTrade &trade)
void append_json_number(std::string &out, T value)
int64_t qty_t
Definition types.hpp:17
int64_t price_t
Definition types.hpp:16
double from_qty_t(qty_t value)
Definition types.hpp:40
constexpr size_t MAX_INSTRUMENT_LENGTH
Definition event.hpp:13
void append_json_string(std::string &out, std::string_view text)
char instrument[MAX_INSTRUMENT_LENGTH]
Definition event.hpp:61