FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
data_source.hpp
Go to the documentation of this file.
1#pragma once
2// DataSource (8.4): a timestamp-ordered stream of normalized market-data events consumed
3// by the simulator. Every source implements sim::MdSource (a virtual next()/reset() pair;
4// one virtual call per event is noise next to the engine step) and satisfies the
5// DataSourceLike concept. Row-based sources (CSV, arrays) share RowAssembler, which groups
6// consecutive rows of one update into a single BookDelta/BookSnapshot message.
7//
8// Row format (CSV columns / array dtypes):
9// ts_ns int64 event time
10// type S | D | T | B (0 | 1 | 2 | 3 in arrays): snapshot level, delta level,
11// trade, book ticker (a row per side, the two of one (ts, inst) form
12// one message; a side without a row is empty)
13// inst uint32 dense instrument id
14// side B | A (0 | 1): bid/ask, or the aggressor side for trades
15// price decimal string / int64 raw 1e-8 / double
16// qty decimal string / int64 raw 1e-8 / double (0 == delete level)
17// seq uint64 venue update id; consecutive S/D rows with equal (ts, inst, seq) form
18// one message (a snapshot keeps 256 levels a side; a delta with more rows
19// on a side becomes several consecutive messages)
21#include "fastmm/core/time.hpp"
22#include "fastmm/sim/md_source.hpp"
23
24#include <concepts>
25#include <cstddef>
26#include <cstdint>
27#include <cstring>
28#include <memory>
29#include <vector>
30
31namespace fastmm::bt {
32
33using sim::EventBuf;
34using sim::kMaxSourceEventBytes;
35using sim::MdSource;
36
37template <class S>
38concept DataSourceLike = requires(S& s) {
39 { s.next() } -> std::same_as<const EventHeader*>;
40 { s.reset() };
41};
42
43enum class RowType : std::uint8_t { Snapshot = 0, Delta = 1, Trade = 2, Ticker = 3 };
44
45struct Row {
46 std::int64_t ts = 0;
48 std::uint32_t inst = 0;
52 std::uint64_t seq = 0;
53};
55// Builds messages from a row stream. `Provider` is `bool(Row&)` returning false at end.
56class RowAssembler {
57 public:
58 explicit RowAssembler(VenueId venue = VenueId{0}) noexcept : venue_(venue) {}
59
60 template <class Provider>
61 const EventHeader* next(Provider&& provide) {
62 if (!have_row_ && !fetch(provide)) return nullptr;
63 have_row_ = false;
64 const Row first = row_;
65 switch (first.type) {
66 case RowType::Trade: {
67 auto& t = buf_.as<TradeMsg>();
69 stamp(t.hdr, first);
70 t.price = first.price;
71 t.qty = first.qty;
72 t.trade_id = first.seq;
73 t.aggressor = first.side;
74 return &t.hdr;
75 }
76 case RowType::Ticker: {
77 auto& t = buf_.as<BookTickerMsg>();
79 stamp(t.hdr, first);
80 // Each row fills its own side; a side with no row of this (ts, inst) is empty.
81 t.bid_px = t.ask_px = Price{};
82 t.bid_qty = t.ask_qty = Qty{};
83 put_side(t, first);
84 if (fetch(provide) && row_.type == RowType::Ticker && row_.ts == first.ts &&
85 row_.inst == first.inst && row_.side != first.side) {
86 put_side(t, row_);
87 have_row_ = false;
88 }
89 return &t.hdr;
90 }
92 case RowType::Delta: {
93 // Collect bids and asks of the same (ts, inst, seq, type) group. A snapshot keeps the
94 // first kMaxLevels rows of a side; a delta that has more ends its message there and the
95 // rest of the group follows in the next one, so no level change is lost.
96 const bool snap = first.type == RowType::Snapshot;
97 std::uint32_t nb = 0;
98 std::uint32_t na = 0;
99 Row cur = first;
100 for (;;) {
101 if (cur.side == Side::Buy) {
102 if (nb < kMaxLevels) bids_[nb++] = Level{cur.price, cur.qty};
103 } else {
104 if (na < kMaxLevels) asks_[na++] = Level{cur.price, cur.qty};
105 }
106 if (!fetch(provide)) break;
107 if (row_.type != first.type || row_.ts != first.ts || row_.inst != first.inst ||
108 row_.seq != first.seq) {
109 break; // row_ stays buffered (have_row_ == true)
110 }
111 if (!snap && (row_.side == Side::Buy ? nb : na) == kMaxLevels) break; // likewise
112 have_row_ = false;
113 cur = row_;
114 }
115 auto& d = buf_.as<BookDeltaMsg>();
116 init_header(d,
118 InstrumentId{first.inst},
119 venue_,
120 BookDeltaMsg::size_for(nb, na));
121 if (snap) d.hdr.flags |= EventHeader::kSnapshot;
122 stamp(d.hdr, first);
123 d.bid_count = nb;
124 d.ask_count = na;
125 d.first_update_id = d.last_update_id = first.seq;
126 d.prev_update_id = 0;
127 if (nb > 0) std::memcpy(d.levels(), bids_, nb * sizeof(Level));
128 if (na > 0) std::memcpy(d.levels() + nb, asks_, na * sizeof(Level));
129 return &d.hdr;
130 }
131 }
132 return nullptr;
133 }
134 void reset() noexcept { have_row_ = false; }
135
136 private:
137 static constexpr std::uint32_t kMaxLevels = 256;
138 template <class Provider>
139 bool fetch(Provider& provide) {
140 have_row_ = provide(row_);
141 return have_row_;
142 }
143 static void put_side(BookTickerMsg& t, const Row& r) noexcept {
144 (r.side == Side::Buy ? t.bid_px : t.ask_px) = r.price;
145 (r.side == Side::Buy ? t.bid_qty : t.ask_qty) = r.qty;
146 }
147 static void stamp(EventHeader& h, const Row& r) noexcept {
148 h.exch_ts = h.recv_ts = Timestamp{r.ts};
149 h.t0_cycles = Cycles{static_cast<std::uint64_t>(r.ts)};
150 h.venue_seq = r.seq;
151 }
152
153 VenueId venue_;
154 Row row_{};
155 bool have_row_ = false;
156 EventBuf buf_{};
157 Level bids_[kMaxLevels];
158 Level asks_[kMaxLevels];
159};
160
161// Concatenation of sources that cover consecutive spans of time (one file per day). The
162// caller owns them and is responsible for the order; events must not go back in time across a
163// boundary.
164class ChainSource final : public MdSource {
165 public:
166 explicit ChainSource(std::vector<MdSource*> sources) : sources_(std::move(sources)) {}
167 const EventHeader* next() override {
168 while (at_ < sources_.size()) {
169 if (const EventHeader* h = sources_[at_]->next()) return h;
170 ++at_;
171 }
172 return nullptr;
173 }
174 void reset() override {
175 for (MdSource* s : sources_) s->reset();
176 at_ = 0;
177 }
178 [[nodiscard]] Timestamp start_ts() const override {
179 return sources_.empty() ? Timestamp{} : sources_.front()->start_ts();
181 [[nodiscard]] bool order_by_order() const override {
182 return !sources_.empty() && sources_.front()->order_by_order();
184
185 private:
186 std::vector<MdSource*> sources_;
187 std::size_t at_ = 0;
188};
189
190// The events of `inner` in [t0, t1) of event time (exch_ts, recv_ts when unset), for walk-forward
191// folds. The part before t0 is read but not yielded: it only rebuilds the book of every
192// (venue, instrument), the recorded orders resting at t0 of an order-by-order source and the last
193// message of every other kind except trades, and those states come out first, stamped t0 (the
194// resting orders in arrival order, one BookSnapshot per book, then the rest in key order).
195// A fold therefore starts on the book the full run would have had at t0. Ends at the first
196// event at or after t1. `inner` is borrowed; reset() rewinds it.
197class TimeSliceSource final : public MdSource {
198 public:
199 TimeSliceSource(MdSource& inner, Timestamp t0, Timestamp t1);
200 ~TimeSliceSource() override;
203 const EventHeader* next() override;
204 void reset() override;
205 [[nodiscard]] Timestamp start_ts() const override { return t0_; }
206 [[nodiscard]] bool order_by_order() const override { return inner_.order_by_order(); }
208 private:
209 struct Primer;
210 MdSource& inner_;
211 Timestamp t0_;
212 Timestamp t1_;
213 std::unique_ptr<Primer> primer_; // the state before t0 while it is being emitted
214 const EventHeader* first_ = nullptr; // first event at or after t0, held back by the primer
215 bool started_ = false;
216 bool done_ = false;
217};
218
219// k-way merge of several sources by event time (stable: lower source index first on ties).
220// The event yielded is the input's own, not a copy: a journal's record can be larger than an
221// EventBuf (a depth snapshot of up to kMaxBookLevelsPerMsg a side), so the input it came from is
222// advanced on the next call, when the pointer may lapse, not before.
223class MergedSource final : public MdSource {
224 public:
225 explicit MergedSource(std::vector<MdSource*> sources) : sources_(std::move(sources)) {
226 heads_.assign(sources_.size(), nullptr);
227 for (std::size_t i = 0; i < sources_.size(); ++i) heads_[i] = sources_[i]->next();
228 }
229 const EventHeader* next() override {
230 if (last_ != kNone) {
231 heads_[last_] = sources_[last_]->next();
232 last_ = kNone;
233 }
234 std::size_t best = kNone;
235 Timestamp best_ts = Timestamp::max();
236 for (std::size_t i = 0; i < heads_.size(); ++i) {
237 if (heads_[i] == nullptr) continue;
238 const Timestamp ts = time_of(*heads_[i]);
239 if (best == kNone || ts < best_ts) {
240 best = i;
241 best_ts = ts;
242 }
243 }
244 if (best == kNone) return nullptr;
245 last_ = best;
246 return heads_[best];
247 }
248 void reset() override {
249 for (std::size_t i = 0; i < sources_.size(); ++i) {
250 sources_[i]->reset();
251 heads_[i] = sources_[i]->next();
252 }
253 last_ = kNone;
254 }
255 // Earliest start among the inputs (invalid if none reports one).
256 [[nodiscard]] Timestamp start_ts() const override {
257 Timestamp t{};
258 for (const MdSource* s : sources_) {
259 const Timestamp st = s->start_ts();
260 if (st.valid() && (!t.valid() || st < t)) t = st;
261 }
262 return t;
263 }
264 [[nodiscard]] static Timestamp time_of(const EventHeader& h) noexcept {
265 return h.exch_ts.valid() ? h.exch_ts : h.recv_ts;
267 // Order by order when any input is: each venue's books come from their own input.
268 [[nodiscard]] bool order_by_order() const override {
269 for (const MdSource* s : sources_)
270 if (s->order_by_order()) return true;
271 return false;
272 }
273
274 private:
275 static constexpr std::size_t kNone = static_cast<std::size_t>(-1);
276 std::vector<MdSource*> sources_;
277 std::vector<const EventHeader*> heads_;
278 std::size_t last_ = kNone; // the input whose head was yielded last
279};
280
281// MergedSource over sources it owns: open_data() of several specs ("a; b"), one per venue.
282class OwnedMergedSource final : public MdSource {
283 public:
284 explicit OwnedMergedSource(std::vector<std::unique_ptr<MdSource>> sources)
285 : owned_(std::move(sources)), merged_(raw(owned_)) {}
286 const EventHeader* next() override { return merged_.next(); }
287 void reset() override { merged_.reset(); }
288 [[nodiscard]] Timestamp start_ts() const override { return merged_.start_ts(); }
289 [[nodiscard]] bool order_by_order() const override { return merged_.order_by_order(); }
291 private:
292 static std::vector<MdSource*> raw(const std::vector<std::unique_ptr<MdSource>>& v) {
293 std::vector<MdSource*> out;
294 out.reserve(v.size());
295 for (const auto& s : v) out.push_back(s.get());
296 return out;
297 }
298 std::vector<std::unique_ptr<MdSource>> owned_;
299 MergedSource merged_;
300};
301
302} // namespace fastmm::bt
Concatenation of sources that cover consecutive spans of time (one file per day).
Definition data_source.hpp:166
bool order_by_order() const override
Definition data_source.hpp:183
const EventHeader * next() override
Definition data_source.hpp:169
Timestamp start_ts() const override
Definition data_source.hpp:180
void reset() override
Definition data_source.hpp:176
k-way merge of several sources by event time (stable: lower source index first on ties).
Definition data_source.hpp:225
bool order_by_order() const override
Order by order when any input is: each venue's books come from their own input.
Definition data_source.hpp:270
Timestamp start_ts() const override
Earliest start among the inputs (invalid if none reports one).
Definition data_source.hpp:258
static Timestamp time_of(const EventHeader &h) noexcept
Definition data_source.hpp:266
const EventHeader * next() override
Definition data_source.hpp:231
void reset() override
Definition data_source.hpp:250
MergedSource over sources it owns: open_data() of several specs ("a; b"), one per venue.
Definition data_source.hpp:284
void reset() override
Definition data_source.hpp:289
const EventHeader * next() override
Definition data_source.hpp:288
Timestamp start_ts() const override
Definition data_source.hpp:290
bool order_by_order() const override
Definition data_source.hpp:291
Builds messages from a row stream. Provider is bool(Row&) returning false at end.
Definition data_source.hpp:58
void reset() noexcept
Definition data_source.hpp:136
const EventHeader * next(Provider &&provide)
Definition data_source.hpp:63
The events of inner in [t0, t1) of event time (exch_ts, recv_ts when unset), for walk-forward folds.
Definition data_source.hpp:199
TimeSliceSource(MdSource &inner, Timestamp t0, Timestamp t1)
Timestamp start_ts() const override
Definition data_source.hpp:207
const EventHeader * next() override
TimeSliceSource & operator=(const TimeSliceSource &)=delete
bool order_by_order() const override
Definition data_source.hpp:208
Event bus message structs (5.5).
Definition backtest_config.hpp:44
RowType
Definition data_source.hpp:45
constexpr void init_header(M &m, EventType type, InstrumentId inst={}, VenueId venue={}, std::uint32_t len=static_cast< std::uint32_t >(sizeof(M))) noexcept
For fixed-size messages len defaults to sizeof(M); BookDeltaMsg passes size_for().
Definition messages.hpp:76
Side
Definition enums.hpp:12
StrongId< struct VenueTag, std::uint8_t > VenueId
Definition strong_id.hpp:39
Bids then asks follow the fixed part as a flexible array of Level (bid_count + ask_count).
Definition messages.hpp:100
EventHeader hdr
Definition messages.hpp:101
static constexpr std::uint32_t size_for(std::uint32_t bids, std::uint32_t asks) noexcept
Definition messages.hpp:108
Definition messages.hpp:229
Definition messages.hpp:38
std::uint8_t flags
Definition messages.hpp:59
@ kSnapshot
BookDelta carries a full snapshot.
Definition messages.hpp:42
One price level. Shared by book messages and the L2 book.
Definition messages.hpp:31
Definition time.hpp:45
static constexpr Timestamp max() noexcept
Definition time.hpp:56
constexpr bool valid() const noexcept
Definition time.hpp:55
A trade whose venue names the buyer and the seller carries them in the 64 bytes after the message: hd...
Definition messages.hpp:200
Definition data_source.hpp:47
std::uint32_t inst
Definition data_source.hpp:50
Price price
Definition data_source.hpp:52
RowType type
Definition data_source.hpp:49
Qty qty
Definition data_source.hpp:53
Side side
Definition data_source.hpp:51
std::int64_t ts
Definition data_source.hpp:48
std::uint64_t seq
Definition data_source.hpp:54
Time primitives.