FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
book_syncer.hpp
Go to the documentation of this file.
1#pragma once
2// BookSyncer: venue-agnostic snapshot/delta synchronisation FSM (5.4), instantiated per
3// instrument on the net thread. Venue rules are supplied by SyncTraits; the engine only
4// ever sees normalised BookSnapshot / BookDelta events, so replay is protocol-free.
5//
6// Idle --start()--> Buffering --snapshot ok--> Synced --gap--> Resync --start()--> Buffering
7//
8// Sink interface (a struct or lambda-holder):
9// void on_snapshot(const BookDeltaMsg&) // kSnapshot set
10// void on_delta(const BookDeltaMsg&)
11// void on_resync(SyncReason) // emitted before the next snapshot request
12// void request_snapshot() // REST fetch (venues with kNeedsRestSnapshot)
13//
14// Buffered deltas are copied into a fixed byte arena (no allocation after construction).
15#include "fastmm/core/config_macros.hpp"
17
18#include <cstddef>
19#include <cstdint>
20#include <cstring>
21#include <memory>
22
23namespace fastmm {
24
25enum class SyncState : std::uint8_t { Idle = 0, Buffering = 1, Synced = 2, Resync = 3 };
26enum class SyncReason : std::uint8_t {
27 None = 0,
30 SnapshotTooOld = 3, // buffered deltas start after the snapshot; need a newer one
31 Explicit = 4,
32 SnapshotMarker = 5, // venue signalled a reset (Bybit u == 1)
33 ChecksumMismatch = 6, // the venue's book checksum disagrees with ours (OKX)
34};
35[[nodiscard]] constexpr const char* to_string(SyncReason r) noexcept {
36 switch (r) {
38 return "none";
40 return "sequence gap";
42 return "buffer overflow";
44 return "snapshot too old";
46 return "explicit";
48 return "venue reset";
50 return "checksum mismatch";
51 }
52 return "?";
53}
54[[nodiscard]] constexpr const char* to_string(SyncState s) noexcept {
55 switch (s) {
57 return "Idle";
59 return "Buffering";
61 return "Synced";
63 return "Resync";
64 }
65 return "?";
66}
67
68// Binance Spot: snapshot via REST (lastUpdateId = L). Drop deltas with u <= L. The first
69// applied delta must satisfy U <= L+1 <= u; each subsequent one U == prev_u + 1.
70struct BinanceSpotSyncTraits {
71 static constexpr bool kNeedsRestSnapshot = true;
72 static constexpr bool kBuffersDeltas = true;
73 static constexpr bool is_stale(const BookDeltaMsg& d, std::uint64_t snap) noexcept {
74 return d.last_update_id <= snap;
75 }
76 static constexpr bool first_applies(const BookDeltaMsg& d, std::uint64_t snap) noexcept {
77 return d.first_update_id <= snap + 1 && snap + 1 <= d.last_update_id;
78 }
79 static constexpr bool next_applies(const BookDeltaMsg& d, std::uint64_t prev_u) noexcept {
80 return d.first_update_id == prev_u + 1;
81 }
82 static constexpr bool is_snapshot_marker(const BookDeltaMsg&) noexcept { return false; }
83};
85// Binance USDT-M futures: first applied delta must have U <= L and u >= L, or follow the snapshot
86// directly (pu == L); afterwards each delta's pu must equal the previous delta's u.
87//
88// The REST depth is current to the stream's 100 ms batch, so L is often the u of a batch that went
89// out before the stream (re)started or before the buffer was reset, and the next event begins after
90// L. It does not bracket L, but its pu names L: it is the update that follows the snapshot. Without
91// the pu rule a quiet book resynced on its first event after every snapshot, 2 s away each time.
93 static constexpr bool kNeedsRestSnapshot = true;
94 static constexpr bool kBuffersDeltas = true;
95 static constexpr bool is_stale(const BookDeltaMsg& d, std::uint64_t snap) noexcept {
96 return d.last_update_id < snap;
97 }
98 static constexpr bool first_applies(const BookDeltaMsg& d, std::uint64_t snap) noexcept {
99 return (d.first_update_id <= snap && d.last_update_id >= snap) || d.prev_update_id == snap;
101 static constexpr bool next_applies(const BookDeltaMsg& d, std::uint64_t prev_u) noexcept {
102 return d.prev_update_id == prev_u;
104 static constexpr bool is_snapshot_marker(const BookDeltaMsg&) noexcept { return false; }
105};
107// Bybit v5: the stream itself sends a snapshot first (kSnapshot flag), then deltas whose
108// `u` must be strictly increasing; `u == 1` means the venue restarted the book (treated as
109// a snapshot marker -> resubscribe). No REST snapshot, no buffering.
110struct BybitSyncTraits {
111 static constexpr bool kNeedsRestSnapshot = false;
112 static constexpr bool kBuffersDeltas = false;
113 static constexpr bool is_stale(const BookDeltaMsg& d, std::uint64_t snap) noexcept {
114 return d.last_update_id <= snap;
116 static constexpr bool first_applies(const BookDeltaMsg& d, std::uint64_t snap) noexcept {
117 return d.last_update_id > snap;
119 static constexpr bool next_applies(const BookDeltaMsg& d, std::uint64_t prev_u) noexcept {
120 return d.last_update_id > prev_u;
122 static constexpr bool is_snapshot_marker(const BookDeltaMsg& d) noexcept {
123 return d.last_update_id == 1 && !d.is_snapshot();
125};
126
127template <class Traits, class Sink>
128class BookSyncer {
129 public:
130 static constexpr std::size_t kMaxBuffered = 4096;
131 static constexpr std::size_t kDefaultBufferBytes = 8U << 20;
133 explicit BookSyncer(Sink& sink, std::size_t buffer_bytes = kDefaultBufferBytes)
134 : sink_(sink), buf_bytes_(Traits::kBuffersDeltas ? buffer_bytes : 0) {
135 if (buf_bytes_ > 0) {
136 buf_.reset(new std::byte[buf_bytes_]);
137 offsets_.reset(new std::uint32_t[kMaxBuffered]);
138 }
139 }
140
141 [[nodiscard]] SyncState state() const noexcept { return state_; }
142 [[nodiscard]] bool synced() const noexcept { return state_ == SyncState::Synced; }
143 [[nodiscard]] std::uint64_t last_update_id() const noexcept { return prev_u_; }
144 [[nodiscard]] std::uint32_t resync_count() const noexcept { return resyncs_; }
145 [[nodiscard]] std::size_t buffered() const noexcept { return count_; }
147 // Begin (or restart) synchronisation.
148 void start() noexcept {
149 reset_buffer();
150 awaiting_first_ = false;
151 state_ = SyncState::Buffering;
152 if constexpr (Traits::kNeedsRestSnapshot) sink_.request_snapshot();
153 }
154
155 // Force a resync (e.g. crossed book beyond grace, or a disconnect).
156 void resync(SyncReason reason) noexcept {
157 ++resyncs_;
159 sink_.on_resync(reason);
160 start();
161 }
162
163 // Delta from the stream. For venues whose stream carries snapshots (Bybit) a message
164 // flagged kSnapshot is routed to on_snapshot().
165 void on_delta(const BookDeltaMsg& d) noexcept {
166 if (d.is_snapshot()) {
168 return;
169 }
170 if (Traits::is_snapshot_marker(d)) {
172 return;
173 }
174 switch (state_) {
175 case SyncState::Idle:
177 return; // not started / waiting for start()
179 if constexpr (Traits::kBuffersDeltas) {
180 if (!buffer(d)) resync(SyncReason::BufferOverflow);
181 }
182 return;
184 if constexpr (Traits::kBuffersDeltas) {
185 // No buffered delta was newer than the snapshot, so the first live one must be checked
186 // with the first-delta rule: it may overlap the snapshot (U <= L+1 <= u on Binance
187 // spot) rather than follow it exactly, and must not be mistaken for a gap.
188 if (FASTMM_UNLIKELY(awaiting_first_)) {
189 if (Traits::is_stale(d, prev_u_)) return;
190 if (!Traits::first_applies(d, prev_u_)) {
191 resync_keeping(d);
192 return;
193 }
194 awaiting_first_ = false;
195 prev_u_ = d.last_update_id;
196 sink_.on_delta(d);
197 return;
198 }
199 }
200 if (FASTMM_LIKELY(Traits::next_applies(d, prev_u_))) {
201 prev_u_ = d.last_update_id;
202 sink_.on_delta(d);
203 } else if (!Traits::is_stale(d, prev_u_)) {
204 resync_keeping(d);
205 }
206 // stale duplicates are silently dropped
207 return;
208 }
209 }
210
211 // Snapshot (REST response or in-stream snapshot). Replays the buffer.
212 void on_snapshot(const BookDeltaMsg& snap) noexcept {
213 if (state_ == SyncState::Idle) return;
214 const std::uint64_t L = snap.last_update_id;
215 if constexpr (Traits::kBuffersDeltas) {
216 // Find the first non-stale buffered delta; it must bracket L.
217 std::size_t i = 0;
218 while (i < count_ && Traits::is_stale(*at(i), L)) ++i;
219 if (i < count_ && !Traits::first_applies(*at(i), L)) {
220 // Buffered stream starts after the snapshot: the snapshot is too old. Keep
221 // buffering and ask again.
222 ++resyncs_;
223 sink_.on_resync(SyncReason::SnapshotTooOld);
224 // keep only the deltas we still need
225 drop_front(i);
226 sink_.request_snapshot();
227 return;
228 }
229 sink_.on_snapshot(snap);
230 prev_u_ = L;
231 state_ = SyncState::Synced;
232 bool first = true;
233 for (; i < count_; ++i) {
234 const BookDeltaMsg& d = *at(i);
235 const bool ok = first ? Traits::first_applies(d, L) : Traits::next_applies(d, prev_u_);
236 if (!ok) {
237 // The stream itself has a gap before d: d and what follows it start the next attempt.
238 drop_front(i);
239 ++resyncs_;
240 state_ = SyncState::Resync;
241 sink_.on_resync(SyncReason::SequenceGap);
242 awaiting_first_ = false;
243 state_ = SyncState::Buffering;
244 sink_.request_snapshot();
245 return;
246 }
247 first = false;
248 prev_u_ = d.last_update_id;
249 sink_.on_delta(d);
250 }
251 awaiting_first_ = first; // nothing newer than the snapshot was buffered
252 reset_buffer();
253 } else {
254 sink_.on_snapshot(snap);
255 prev_u_ = L;
256 state_ = SyncState::Synced;
257 }
258 }
259
260 private:
261 // A gap revealed by d. d itself is the next update of the stream, so a venue that buffers for a
262 // REST snapshot keeps it: a snapshot taken inside d's range applies at once, where without d it
263 // would look older than the buffer and cost another request (SnapshotTooOld).
264 void resync_keeping(const BookDeltaMsg& d) noexcept {
266 if constexpr (Traits::kBuffersDeltas) {
267 if (state_ == SyncState::Buffering && !buffer(d)) resync(SyncReason::BufferOverflow);
268 }
269 }
270
271 bool buffer(const BookDeltaMsg& d) noexcept {
272 if (count_ >= kMaxBuffered || used_ + d.hdr.len > buf_bytes_) return false;
273 std::memcpy(buf_.get() + used_, &d, d.hdr.len);
274 offsets_[count_++] = static_cast<std::uint32_t>(used_);
275 used_ += d.hdr.len;
276 return true;
277 }
278 [[nodiscard]] const BookDeltaMsg* at(std::size_t i) const noexcept {
279 return reinterpret_cast<const BookDeltaMsg*>(buf_.get() + offsets_[i]);
280 }
281 void drop_front(std::size_t n) noexcept {
282 if (n == 0) return;
283 if (n >= count_) {
284 reset_buffer();
285 return;
286 }
287 const std::uint32_t base = offsets_[n];
288 std::memmove(buf_.get(), buf_.get() + base, used_ - base);
289 for (std::size_t i = n; i < count_; ++i) offsets_[i - n] = offsets_[i] - base;
290 count_ -= n;
291 used_ -= base;
292 }
293 void reset_buffer() noexcept {
294 count_ = 0;
295 used_ = 0;
296 }
297
298 Sink& sink_;
299 SyncState state_ = SyncState::Idle;
300 bool awaiting_first_ = false; // Synced, but the first-delta rule has not been applied yet
301 std::uint64_t prev_u_ = 0;
302 std::uint32_t resyncs_ = 0;
303 std::unique_ptr<std::byte[]> buf_;
304 std::unique_ptr<std::uint32_t[]> offsets_;
305 std::size_t buf_bytes_;
306 std::size_t used_ = 0;
307 std::size_t count_ = 0;
308};
309
310} // namespace fastmm
Definition book_syncer.hpp:130
static constexpr std::size_t kDefaultBufferBytes
Definition book_syncer.hpp:133
bool synced() const noexcept
Definition book_syncer.hpp:144
void resync(SyncReason reason) noexcept
Force a resync (e.g. crossed book beyond grace, or a disconnect).
Definition book_syncer.hpp:158
std::uint32_t resync_count() const noexcept
Definition book_syncer.hpp:146
std::uint64_t last_update_id() const noexcept
Definition book_syncer.hpp:145
void on_delta(const BookDeltaMsg &d) noexcept
Delta from the stream.
Definition book_syncer.hpp:167
SyncState state() const noexcept
Definition book_syncer.hpp:143
void start() noexcept
Begin (or restart) synchronisation.
Definition book_syncer.hpp:150
std::size_t buffered() const noexcept
Definition book_syncer.hpp:147
void on_snapshot(const BookDeltaMsg &snap) noexcept
Snapshot (REST response or in-stream snapshot). Replays the buffer.
Definition book_syncer.hpp:214
static constexpr std::size_t kMaxBuffered
Definition book_syncer.hpp:132
Event bus message structs (5.5).
Definition strategy.hpp:23
SyncState
Definition book_syncer.hpp:27
SyncReason
Definition book_syncer.hpp:28
@ ChecksumMismatch
the venue's book checksum disagrees with ours (OKX)
@ SnapshotTooOld
buffered deltas start after the snapshot; need a newer one
@ SnapshotMarker
venue signalled a reset (Bybit u == 1)
constexpr std::string_view to_string(ParamType t) noexcept
Definition params.hpp:63
Binance USDT-M futures: first applied delta must have U <= L and u >= L, or follow the snapshot direc...
Definition book_syncer.hpp:94
static constexpr bool kBuffersDeltas
Definition book_syncer.hpp:96
static constexpr bool is_snapshot_marker(const BookDeltaMsg &) noexcept
Definition book_syncer.hpp:106
static constexpr bool kNeedsRestSnapshot
Definition book_syncer.hpp:95
static constexpr bool next_applies(const BookDeltaMsg &d, std::uint64_t prev_u) noexcept
Definition book_syncer.hpp:103
static constexpr bool first_applies(const BookDeltaMsg &d, std::uint64_t snap) noexcept
Definition book_syncer.hpp:100
static constexpr bool is_stale(const BookDeltaMsg &d, std::uint64_t snap) noexcept
Definition book_syncer.hpp:97
static constexpr bool kBuffersDeltas
Definition book_syncer.hpp:74
static constexpr bool next_applies(const BookDeltaMsg &d, std::uint64_t prev_u) noexcept
Definition book_syncer.hpp:81
static constexpr bool is_snapshot_marker(const BookDeltaMsg &) noexcept
Definition book_syncer.hpp:84
static constexpr bool kNeedsRestSnapshot
Definition book_syncer.hpp:73
static constexpr bool first_applies(const BookDeltaMsg &d, std::uint64_t snap) noexcept
Definition book_syncer.hpp:78
static constexpr bool is_stale(const BookDeltaMsg &d, std::uint64_t snap) noexcept
Definition book_syncer.hpp:75
Bids then asks follow the fixed part as a flexible array of Level (bid_count + ask_count).
Definition messages.hpp:100
std::uint64_t last_update_id
Binance u / Bybit u.
Definition messages.hpp:105
Bybit v5: the stream itself sends a snapshot first (kSnapshot flag), then deltas whose u must be stri...
Definition book_syncer.hpp:112
static constexpr bool next_applies(const BookDeltaMsg &d, std::uint64_t prev_u) noexcept
Definition book_syncer.hpp:121
static constexpr bool kBuffersDeltas
Definition book_syncer.hpp:114
static constexpr bool is_snapshot_marker(const BookDeltaMsg &d) noexcept
Definition book_syncer.hpp:124
static constexpr bool is_stale(const BookDeltaMsg &d, std::uint64_t snap) noexcept
Definition book_syncer.hpp:115
static constexpr bool first_applies(const BookDeltaMsg &d, std::uint64_t snap) noexcept
Definition book_syncer.hpp:118
static constexpr bool kNeedsRestSnapshot
Definition book_syncer.hpp:113