FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
l2_book.hpp
Go to the documentation of this file.
1#pragma once
2// L2Book<kMaxDepth>: price-aggregated book for crypto feeds (5.4).
3//
4// Each side is a sorted StaticVector<Level> with the BEST level at back(): top-of-book is
5// O(1), and the common near-top insert/erase only memmoves a handful of 16-byte levels; an
6// insert or erase moves the levels better than its own (into a full side, the ones worse than
7// it, as the worst level goes), and a snapshot loads in O(levels).
8// Bids are stored ascending by price, asks descending, so both sides share one code path
9// keyed on "distance from best". Lookups scan the top 16 linearly and bisect the rest.
10//
11// Depth is capped at kMaxDepth: levels worse than the worst stored one are dropped and the
12// side is flagged truncated() until the next snapshot (crypto venues resend snapshots on
13// resync; we deliberately do not try to repair). Crossed books are tolerated (Binance can
14// cross for ~100 ms between updates); the engine polls crossed_for(now) against a grace.
16#include "fastmm/core/config_macros.hpp"
17#include "fastmm/core/containers/static_vector.hpp"
19
20#include <algorithm>
21#include <cstddef>
22#include <cstdint>
23#include <span>
24#include <type_traits>
25
26namespace fastmm {
27
28template <std::size_t kMaxDepth = 256>
29class L2Book {
30 static_assert(kMaxDepth >= 2);
32 public:
33 static constexpr std::size_t kDepth = kMaxDepth;
34 static constexpr std::size_t kLinearScan = 16;
36 L2Book() noexcept = default;
37
38 // ---- mutation --------------------------------------------------------------------------
39
40 void clear() noexcept {
41 bids_.clear();
42 asks_.clear();
43 truncated_[0] = truncated_[1] = false;
44 have_snapshot_ = false;
45 crossed_since_ = Timestamp{};
46 seq_ = 0;
47 }
48
49 // Sets/updates/deletes (qty == 0) one level. Returns false if the level was dropped
50 // because the side is full and the price is worse than everything stored.
51 FASTMM_FORCE_INLINE bool apply_level(Side side, Price price, Qty qty) noexcept {
52 Qty old;
53 return apply_level(side, price, qty, old);
54 }
55 // The same; `old` is the quantity the level had (zero when absent).
56 FASTMM_FORCE_INLINE bool apply_level(Side side, Price price, Qty qty, Qty& old) noexcept {
57 old = Qty{};
58 auto& v = levels(side);
59 bool found = false;
60 const std::size_t i = locate(v, side, price, found);
61 if (found) {
62 old = v[i].qty;
63 if (qty.is_zero()) {
64 v.erase_at(i);
65 } else {
66 v[i].qty = qty;
67 }
68 return true;
69 }
70 if (qty.is_zero()) return true; // delete of an unknown level: no-op
71 if (FASTMM_UNLIKELY(v.size() >= kMaxDepth)) {
72 truncated_[static_cast<std::size_t>(side)] = true;
73 if (i == 0) return false; // worse than everything we hold
74 // Drop the worst level and insert in one shift: only the i - 1 levels worse than the
75 // new one move, as an insert into a side with room moves the ones better than it.
76 std::copy(v.begin() + 1, v.begin() + i, v.begin());
77 v[i - 1] = Level{price, qty};
78 return true;
79 }
80 v.insert_at(i, Level{price, qty});
81 return true;
82 }
83
84 // Our own quantity shown in a book that is otherwise the market's (the engine's view of a
85 // simulated feed that shows our orders, OwnLevelsMsg): add_own() adds `qty` at `price`, a level
86 // of its own where there is none, beyond kMaxDepth if the side is full (a side has room for
87 // kOwnLevels more); remove_own() takes it out again, which leaves the book as it was when nothing
88 // else changed it in between. add_own() returns false, adding nothing, when there is no room.
89 static constexpr std::size_t kOwnLevels = 32;
90 bool add_own(Side side, Price price, Qty qty, bool& inserted) noexcept {
91 auto& v = levels(side);
92 bool found = false;
93 const std::size_t i = locate(v, side, price, found);
94 inserted = !found;
95 if (found) {
96 v[i].qty += qty;
97 return true;
98 }
99 return v.insert_at(i, Level{price, qty});
100 }
101 void remove_own(Side side, Price price, Qty qty, bool inserted) noexcept {
102 auto& v = levels(side);
103 bool found = false;
104 const std::size_t i = locate(v, side, price, found);
105 if (!found) return;
106 if (inserted) {
107 v.erase_at(i);
108 } else {
109 v[i].qty -= qty;
110 }
111 }
112
113 // O(levels) for a snapshot sorted best-first or worst-first with no empty level (what every
114 // parser sends); any other input is applied level by level.
115 void apply_snapshot(std::span<const Level> bids,
116 std::span<const Level> asks,
117 std::uint64_t seq,
118 Timestamp ts) noexcept {
119 clear();
120 load_side(Side::Buy, bids);
121 load_side(Side::Sell, asks);
122 have_snapshot_ = true;
123 seq_ = seq;
124 last_update_ = ts;
125 update_crossed(ts);
126 }
127
128 // Applies a BookDeltaMsg (or snapshot with kSnapshot). Uses last_update_id as seq and
129 // exch_ts (falling back to recv_ts) as the update time.
130 void apply_delta(const BookDeltaMsg& d) noexcept {
131 const Timestamp ts = d.hdr.exch_ts.valid() ? d.hdr.exch_ts : d.hdr.recv_ts;
132 if (d.is_snapshot()) {
133 apply_snapshot(d.bids(), d.asks(), d.last_update_id, ts);
134 return;
135 }
136 for (const Level& l : d.bids()) apply_level(Side::Buy, l.price, l.qty);
137 for (const Level& l : d.asks()) apply_level(Side::Sell, l.price, l.qty);
138 constexpr std::uint8_t kCut = EventHeader::kTruncatedBids | EventHeader::kTruncatedAsks;
139 if (FASTMM_UNLIKELY((d.hdr.flags & kCut) != 0)) trim_truncated(d);
140 seq_ = d.last_update_id;
141 last_update_ = ts;
142 update_crossed(ts);
143 }
144
145 void set_seq(std::uint64_t s) noexcept { seq_ = s; }
146 void set_last_update(Timestamp t) noexcept { last_update_ = t; }
147 void mark_snapshot() noexcept { have_snapshot_ = true; }
149 // ---- BookView --------------------------------------------------------------------------
150
151 [[nodiscard]] FASTMM_FORCE_INLINE Level best_bid() const noexcept {
152 return bids_.empty() ? Level{} : bids_.back();
153 }
154 [[nodiscard]] FASTMM_FORCE_INLINE Level best_ask() const noexcept {
155 return asks_.empty() ? Level{} : asks_.back();
156 }
157 [[nodiscard]] Price mid() const noexcept {
158 if (bids_.empty() || asks_.empty()) return Price{};
159 return Price::from_raw((bids_.back().price.raw + asks_.back().price.raw) / 2);
160 }
161 [[nodiscard]] Price spread() const noexcept {
162 if (bids_.empty() || asks_.empty()) return Price{};
163 return asks_.back().price - bids_.back().price;
164 }
165 // i == 0 is best. Level{} if out of range.
166 [[nodiscard]] Level level(Side side, std::size_t i) const noexcept {
167 const auto& v = levels(side);
168 return i < v.size() ? v[v.size() - 1 - i] : Level{};
169 }
170 [[nodiscard]] std::size_t depth(Side side) const noexcept { return levels(side).size(); }
171 [[nodiscard]] std::size_t depth() const noexcept { return bids_.size() + asks_.size(); }
172
173 // Total quantity on `side` at prices at-or-better than `limit`.
174 [[nodiscard]] Qty qty_at_or_better(Side side, Price limit) const noexcept {
175 const auto& v = levels(side);
176 Qty sum{};
177 for (std::size_t i = v.size(); i > 0; --i) {
178 const Level& l = v[i - 1];
179 if (!at_or_better(side, l.price, limit)) break;
180 sum += l.qty;
181 }
182 return sum;
183 }
184 // Price of the level at which cumulative quantity from the best reaches `qty`;
185 // Price{} if the side is too thin.
186 [[nodiscard]] Price price_for_qty(Side side, Qty qty) const noexcept {
187 const auto& v = levels(side);
188 Qty cum{};
189 for (std::size_t i = v.size(); i > 0; --i) {
190 cum += v[i - 1].qty;
191 if (cum >= qty) return v[i - 1].price;
192 }
193 return Price{};
194 }
195 // Visits levels best-first. F(const Level&) may return bool (false stops) or void.
196 template <class F>
197 void for_each_level(Side side, F&& f) const noexcept {
198 const auto& v = levels(side);
199 for (std::size_t i = v.size(); i > 0; --i) {
200 if constexpr (std::is_same_v<std::invoke_result_t<F, const Level&>, bool>) {
201 if (!f(v[i - 1])) return;
202 } else {
203 f(v[i - 1]);
204 }
205 }
206 }
207 template <std::size_t N>
208 [[nodiscard]] TopLevels<N> top(Side side) const noexcept {
209 TopLevels<N> out;
210 const auto& v = levels(side);
211 const std::size_t n = v.size() < N ? v.size() : N;
212 for (std::size_t i = 0; i < n; ++i) out.levels[i] = v[v.size() - 1 - i];
213 out.count = static_cast<std::uint32_t>(n);
214 return out;
215 }
216
217 [[nodiscard]] bool crossed() const noexcept {
218 return !bids_.empty() && !asks_.empty() && bids_.back().price >= asks_.back().price;
219 }
220 // How long the book has been crossed as of `now` (zero if not crossed).
221 [[nodiscard]] Duration crossed_for(Timestamp now) const noexcept {
222 return crossed_since_.valid() ? now - crossed_since_ : Duration{};
223 }
224 [[nodiscard]] bool truncated(Side side) const noexcept {
225 return truncated_[static_cast<std::size_t>(side)];
226 }
227 [[nodiscard]] bool truncated() const noexcept { return truncated_[0] || truncated_[1]; }
228 [[nodiscard]] bool has_snapshot() const noexcept { return have_snapshot_; }
229 [[nodiscard]] bool is_valid() const noexcept {
230 return have_snapshot_ && !bids_.empty() && !asks_.empty() && !crossed();
231 }
232 [[nodiscard]] std::uint64_t seq() const noexcept { return seq_; }
233 [[nodiscard]] Timestamp last_update() const noexcept { return last_update_; }
234
235 // Raw access (worst..best order) for tests/tools.
236 using Levels = StaticVector<Level, kMaxDepth + kOwnLevels>;
237 [[nodiscard]] const Levels& raw(Side side) const noexcept { return levels(side); }
238
239 private:
240 FASTMM_FORCE_INLINE Levels& levels(Side s) noexcept { return s == Side::Buy ? bids_ : asks_; }
241 FASTMM_FORCE_INLINE const Levels& levels(Side s) const noexcept {
242 return s == Side::Buy ? bids_ : asks_;
243 }
244 // The index of the first level at or better than `price` counted from the worst (front): a
245 // lower_bound in "goodness" order; `found` when that level is at `price`. Scans the top
246 // kLinearScan levels from the best (back), then bisects the rest.
247 FASTMM_FORCE_INLINE static std::size_t locate(const Levels& v,
248 Side side,
249 Price price,
250 bool& found) noexcept {
251 std::size_t i = v.size();
252 found = false;
253 const std::size_t stop = v.size() > kLinearScan ? v.size() - kLinearScan : 0;
254 while (i > stop) {
255 const Price p = v[i - 1].price;
256 if (p == price) {
257 found = true;
258 return i - 1;
259 }
260 if (better(side, price, p)) return i; // insert after v[i-1]
261 --i;
262 }
263 if (stop == 0) return 0;
264 std::size_t lo = 0;
265 std::size_t hi = stop;
266 while (lo < hi) {
267 const std::size_t mid = lo + (hi - lo) / 2;
268 if (better(side, price, v[mid].price)) {
269 lo = mid + 1;
270 } else {
271 hi = mid;
272 }
273 }
274 found = lo < v.size() && v[lo].price == price;
275 return lo;
276 }
277 // A side flagged kTruncatedBids/Asks left out the venue's changes behind the last level it
278 // carries: the book's levels behind that one may be stale, so they go (the side is truncated()
279 // until the next snapshot). A no-op for a book at most half as deep as the side carried
280 // (level_spill.hpp), such as the engine's.
281 [[gnu::noinline, gnu::cold]] void trim_truncated(const BookDeltaMsg& d) noexcept {
282 if ((d.hdr.flags & EventHeader::kTruncatedBids) != 0) trim_behind(Side::Buy, d.bids());
283 if ((d.hdr.flags & EventHeader::kTruncatedAsks) != 0) trim_behind(Side::Sell, d.asks());
284 }
285 void trim_behind(Side side, std::span<const Level> carried) noexcept {
286 if (carried.empty()) return;
287 Price bound = carried[0].price;
288 for (const Level& l : carried) {
289 if (better(side, bound, l.price)) bound = l.price;
290 }
291 auto& v = levels(side);
292 std::size_t k = 0;
293 while (k < v.size() && better(side, bound, v[k].price)) ++k;
294 if (k == 0) return;
295 v.erase_front(k);
296 truncated_[static_cast<std::size_t>(side)] = true;
297 }
298 // Snapshot side into an empty side. Levels arrive one at a time best-first would each go to
299 // the front of the array (the worst end) and move everything stored: O(levels^2).
300 void load_side(Side side, std::span<const Level> in) noexcept {
301 auto& v = levels(side);
302 const std::size_t n = in.size();
303 int order = 0; // 1: best-first, -1: worst-first, 0: neither
304 if (n > 0 && in[0].qty.is_positive()) {
305 order = n == 1 ? 1 : better(side, in[0].price, in[1].price) ? 1 : -1;
306 for (std::size_t k = 1; k < n && order != 0; ++k) {
307 const bool ok =
308 in[k].qty.is_positive() && (order == 1 ? better(side, in[k - 1].price, in[k].price)
309 : better(side, in[k].price, in[k - 1].price));
310 if (!ok) order = 0;
311 }
312 }
313 if (order == 0) {
314 for (const Level& l : in) apply_level(side, l.price, l.qty);
315 return;
316 }
317 const std::size_t m = n < kMaxDepth ? n : kMaxDepth; // the best m levels
318 v.resize_uninitialized(m);
319 if (order == 1) {
320 for (std::size_t k = 0; k < m; ++k) v[m - 1 - k] = in[k];
321 } else {
322 for (std::size_t k = 0; k < m; ++k) v[k] = in[n - m + k];
323 }
324 if (n > m) truncated_[static_cast<std::size_t>(side)] = true;
325 }
326 void update_crossed(Timestamp ts) noexcept {
327 if (crossed()) {
328 if (!crossed_since_.valid()) crossed_since_ = ts;
329 } else {
330 crossed_since_ = Timestamp{};
331 }
332 }
333
334 Levels bids_;
335 Levels asks_;
336 std::uint64_t seq_ = 0;
337 Timestamp last_update_{};
338 Timestamp crossed_since_{};
339 bool truncated_[2] = {false, false};
340 bool have_snapshot_ = false;
341};
342
343static_assert(BookView<L2Book<256>>);
344
345} // namespace fastmm
BookView: the read interface every book implementation (L2Book, L3Book::to_l2 view,...
void mark_snapshot() noexcept
Definition l2_book.hpp:148
std::size_t depth() const noexcept
Definition l2_book.hpp:171
Price price_for_qty(Side side, Qty qty) const noexcept
Price of the level at which cumulative quantity from the best reaches qty; Price{} if the side is too...
Definition l2_book.hpp:186
void clear() noexcept
Definition l2_book.hpp:41
bool add_own(Side side, Price price, Qty qty, bool &inserted) noexcept
Definition l2_book.hpp:91
Price mid() const noexcept
Definition l2_book.hpp:157
std::uint64_t seq() const noexcept
Definition l2_book.hpp:232
bool is_valid() const noexcept
Definition l2_book.hpp:229
Qty qty_at_or_better(Side side, Price limit) const noexcept
Total quantity on side at prices at-or-better than limit.
Definition l2_book.hpp:174
Level level(Side side, std::size_t i) const noexcept
i == 0 is best. Level{} if out of range.
Definition l2_book.hpp:166
Timestamp last_update() const noexcept
Definition l2_book.hpp:233
StaticVector< Level, kMaxDepth+kOwnLevels > Levels
Raw access (worst..best order) for tests/tools.
Definition l2_book.hpp:236
void for_each_level(Side side, F &&f) const noexcept
Visits levels best-first. F(const Level&) may return bool (false stops) or void.
Definition l2_book.hpp:197
static constexpr std::size_t kLinearScan
Definition l2_book.hpp:36
Price spread() const noexcept
Definition l2_book.hpp:161
std::size_t depth(Side side) const noexcept
Definition l2_book.hpp:170
bool truncated(Side side) const noexcept
Definition l2_book.hpp:224
bool crossed() const noexcept
Definition l2_book.hpp:217
bool truncated() const noexcept
Definition l2_book.hpp:227
void set_seq(std::uint64_t s) noexcept
Definition l2_book.hpp:146
void apply_snapshot(std::span< const Level > bids, std::span< const Level > asks, std::uint64_t seq, Timestamp ts) noexcept
O(levels) for a snapshot sorted best-first or worst-first with no empty level (what every parser send...
Definition l2_book.hpp:116
FASTMM_FORCE_INLINE Level best_ask() const noexcept
Definition l2_book.hpp:154
FASTMM_FORCE_INLINE bool apply_level(Side side, Price price, Qty qty) noexcept
Sets/updates/deletes (qty == 0) one level.
Definition l2_book.hpp:52
static constexpr std::size_t kDepth
Definition l2_book.hpp:35
void remove_own(Side side, Price price, Qty qty, bool inserted) noexcept
Definition l2_book.hpp:102
const Levels & raw(Side side) const noexcept
Definition l2_book.hpp:237
void set_last_update(Timestamp t) noexcept
Definition l2_book.hpp:147
Duration crossed_for(Timestamp now) const noexcept
How long the book has been crossed as of now (zero if not crossed).
Definition l2_book.hpp:221
static constexpr std::size_t kOwnLevels
Our own quantity shown in a book that is otherwise the market's (the engine's view of a simulated fee...
Definition l2_book.hpp:90
bool has_snapshot() const noexcept
Definition l2_book.hpp:228
FASTMM_FORCE_INLINE Level best_bid() const noexcept
Definition l2_book.hpp:151
L2Book() noexcept=default
void apply_delta(const BookDeltaMsg &d) noexcept
Applies a BookDeltaMsg (or snapshot with kSnapshot).
Definition l2_book.hpp:131
TopLevels< N > top(Side side) const noexcept
Definition l2_book.hpp:208
Event bus message structs (5.5).
Definition strategy.hpp:23
Side
Definition enums.hpp:12
Fixed< struct QtyTag > Qty
Definition fixed_point.hpp:333
constexpr bool at_or_better(Side s, Price p, Price q) noexcept
true if p is at least as good as q from the point of view of side s.
Definition book_view.hpp:45
Fixed< struct PriceTag > Price
Definition fixed_point.hpp:332
constexpr bool better(Side s, Price p, Price q) noexcept
Definition book_view.hpp:48
Bids then asks follow the fixed part as a flexible array of Level (bid_count + ask_count).
Definition messages.hpp:100
Definition time.hpp:22
@ kTruncatedBids
BookDelta: the venue's update changed more levels on this side than the message carries,...
Definition messages.hpp:51
@ kTruncatedAsks
Definition messages.hpp:52
static constexpr Fixed from_raw(std::int64_t r) noexcept
Definition fixed_point.hpp:155
One price level. Shared by book messages and the L2 book.
Definition messages.hpp:31
Price price
Definition messages.hpp:32
Qty qty
Definition messages.hpp:33
Definition time.hpp:45
constexpr bool valid() const noexcept
Definition time.hpp:55
Fixed-size result of top<N>().
Definition book_view.hpp:20
std::uint32_t count
Definition book_view.hpp:22
Level levels[N]
Definition book_view.hpp:21