FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
journal_source.hpp
Go to the documentation of this file.
1#pragma once
2// JournalSource: market-data events of an .fmj journal (BookDelta / BookSnapshot / Trade /
3// BookTicker records, in sequence order). Everything else the journal holds (order events,
4// timers, outbound copies) is skipped: the backtest re-derives those.
5//
6// parts: a session recorded with [engine] journal_max_bytes is several files, `x.fmj` then
7// `x.1.fmj`, `x.2.fmj`, ... (JournalFileWriter::part_path), each a complete journal that repeats
8// the prologue. Given `x.fmj`, the source reads the later parts after it, in order, until one is
9// missing, as one stream; their prologues are never events, so nothing repeats. A part of another
10// session (its session_id differs) is refused. The sequence numbers continue across parts; a part
11// whose first does not follow the previous part's last is read anyway, and seq_gaps() / note()
12// say so: a part is missing in between, or the previous one was cut short.
13//
14// strip_own: the journal is a live session's, whose venue feed shows the session's own resting
15// orders; take them out of the depth and top of book (OwnOrderStripper, own_orders.hpp) so the
16// backtest does not see its live twin as someone else's liquidity. A BookTicker whose best bid or
17// ask was only ours is dropped. Public trades are kept, our own fills included: the aggressor
18// existed whether or not our order did, and without it would have traded with the next order at
19// that price, which is what a simulated order there stands for. A backtest's journal from format
20// v5 on has nothing of ours in its market data (our quantity is in its OwnLevels records, and the
21// tickers its simulated venue sent for our orders are flagged kSynthetic; a source reads neither),
22// so strip_own leaves it as it is.
23//
24// remap: the journal numbers its instruments as the recording session did, so two recordings of
25// different instrument sets both count from 0 and, merged, overwrite each other's books. Given the
26// backtest configuration's table, every event's instrument id becomes that of the instrument with
27// the same symbol there (the recording's venue first, else any venue listing the symbol) and its
28// venue that instrument's; an event whose symbol the configuration lacks is dropped, and note()
29// counts them. A configuration that numbers every instrument the journal lists as the journal
30// does changes nothing. The copy holds up to kMaxMsgBytes: a recorded snapshot can be deeper than
31// an EventBuf. Remap applies after strip_own.
33#include "fastmm/backtest/own_orders.hpp"
35#include "fastmm/core/journal.hpp"
36#include "fastmm/sim/recorded_session.hpp"
37
38#include <cstdint>
39#include <memory>
40#include <string>
41#include <string_view>
42#include <vector>
43
44namespace fastmm::bt {
45
46class JournalSource final : public MdSource {
47 public:
48 // Throws std::runtime_error if a file cannot be opened/validated. parts = false reads `path`
49 // alone.
50 // remap: the configuration's instrument table (see above); null leaves the ids as recorded.
51 explicit JournalSource(const std::string& path,
52 bool strip_own = false,
53 bool parts = true,
54 const InstrumentTable* remap = nullptr);
55 const EventHeader* next() override;
56 void reset() override;
57 [[nodiscard]] Timestamp start_ts() const override { return first_ts_; }
58 // The first part: its header, instrument table and configuration are every part's.
59 [[nodiscard]] const JournalReader& reader() const noexcept { return parts_.front(); }
60 // The files read, in order; the first is `path`.
61 [[nodiscard]] const std::vector<std::string>& paths() const noexcept { return paths_; }
62 // Parts whose first sequence number did not follow the previous part's last.
63 [[nodiscard]] std::size_t seq_gaps() const noexcept { return seq_gaps_; }
64 [[nodiscard]] std::size_t md_events() const noexcept { return md_events_; }
65 // Null unless strip_own.
66 [[nodiscard]] const OwnOrderStripper* stripper() const noexcept { return stripper_.get(); }
67 // remap: events dropped so far because the configuration lacks their symbol.
68 [[nodiscard]] std::size_t dropped() const noexcept { return dropped_; }
69 [[nodiscard]] std::string note() const override;
70 // What the parts say about the session (sim/recorded_session.hpp): its states and checkpoints
71 // (journal_state.hpp), the positions reconciled before its first order, its ParamUpdate records
72 // with the first part's parameter table, its balance rows (account rows, kAccount, left out) and
73 // its flows, and its recorded latencies. With remap, their instruments are the configuration's,
74 // and an account's venue that of the first mapped instrument the journal lists on it (a venue
75 // with none keeps its id); a latency of an instrument the configuration lacks is dropped.
76 [[nodiscard]] const sim::RecordedSession* recorded() const override { return &session_; }
77
78 [[nodiscard]] static bool is_market_data(EventType t) noexcept {
82 }
83 // A ticker a backtest's simulated venue sent because our order changed the touch: ours, as the
84 // journal's OwnLevels records are, not the market's.
85 [[nodiscard]] static bool own_ticker(const EventHeader& h) noexcept {
86 return h.type == EventType::BookTicker && (h.flags & EventHeader::kSynthetic) != 0;
87 }
88
89 private:
90 std::vector<JournalReader> parts_;
91 std::vector<std::string> paths_;
92 std::size_t at_ = 0; // the part next() is reading
93 std::size_t seq_gaps_ = 0;
94 std::string gap_; // the first gap, for note()
95 Timestamp first_ts_{};
96 std::size_t md_events_ = 0;
97 std::unique_ptr<OwnOrderStripper> stripper_;
98 std::size_t orders_ = 0;
99 EventBuf buf_;
100 sim::RecordedSession session_;
101 // remap: per journal instrument id, the configured id (kUnmapped: dropped) and its venue.
102 static constexpr std::uint32_t kUnmapped = 0xFFFF'FFFF;
103 bool remap_ = false;
104 std::vector<std::uint32_t> map_;
105 std::vector<VenueId> map_venue_;
106 std::size_t unmapped_ = 0; // journal instruments the configuration lacks
107 std::size_t dropped_ = 0;
108 std::vector<std::uint64_t> rbuf_; // the remapped event, a copy of up to kMaxMsgBytes
109};
110
111// Writes the events of `source` (all, or the first `max_events` when non-zero) to a fresh
112// .fmj with JournalFileWriter (instrument table + header stamped with `seed`); used to
113// produce fixtures. Returns the number of events written.
114std::uint64_t write_md_journal(MdSource& source,
115 const std::string& path,
116 const InstrumentTable& instruments,
117 std::uint64_t seed,
118 std::string_view strategy = "data",
119 std::uint64_t max_events = 0);
120
121} // namespace fastmm::bt
Dense-by-id table built at startup; symbol lookup is a sorted FlatMap keyed by (venue,...
Definition instrument.hpp:147
Definition journal_source.hpp:48
static bool own_ticker(const EventHeader &h) noexcept
A ticker a backtest's simulated venue sent because our order changed the touch: ours,...
Definition journal_source.hpp:87
const JournalReader & reader() const noexcept
The first part: its header, instrument table and configuration are every part's.
Definition journal_source.hpp:61
const EventHeader * next() override
static bool is_market_data(EventType t) noexcept
Definition journal_source.hpp:80
const OwnOrderStripper * stripper() const noexcept
Null unless strip_own.
Definition journal_source.hpp:68
std::size_t dropped() const noexcept
remap: events dropped so far because the configuration lacks their symbol.
Definition journal_source.hpp:70
const std::vector< std::string > & paths() const noexcept
The files read, in order; the first is path.
Definition journal_source.hpp:63
std::string note() const override
const sim::RecordedSession * recorded() const override
What the parts say about the session (sim/recorded_session.hpp): its states and checkpoints (journal_...
Definition journal_source.hpp:78
std::size_t seq_gaps() const noexcept
Parts whose first sequence number did not follow the previous part's last.
Definition journal_source.hpp:65
Timestamp start_ts() const override
Definition journal_source.hpp:59
std::size_t md_events() const noexcept
Definition journal_source.hpp:66
DataSource (8.4): a timestamp-ordered stream of normalized market-data events consumed by the simulat...
Instrument: the single definition of a tradable contract (5.3 / 5.15).
Definition backtest_config.hpp:44
std::uint64_t write_md_journal(MdSource &source, const std::string &path, const InstrumentTable &instruments, std::uint64_t seed, std::string_view strategy="data", std::uint64_t max_events=0)
Writes the events of source (all, or the first max_events when non-zero) to a fresh ....
EventType
Message discriminator carried in EventHeader::type.
Definition enums.hpp:316
@ OptionTicker
mark / implied vols / greeks of one option (OptionTickerMsg)
@ PerpState
mark, index and funding of one derivative (PerpStateMsg)
@ InstrumentRules
A venue's trading rules or trading status of one instrument changed while the session ran (Instrument...
Definition messages.hpp:38
@ kSynthetic
generated locally (reconcile fill, sim), not from the venue
Definition messages.hpp:40
Definition time.hpp:45