FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
backtest_runner.hpp
Go to the documentation of this file.
1#pragma once
2// BacktestRunner (8.4): wires Engine<S, SimClock, SimTransport, InlineFeed> to a SimDriver
3// and collects a BacktestResult. Two entry points share one BacktestSession:
4//
5// run_backtest<MyStrategy>(cfg, source) // template: no registration needed
6// run_backtest(cfg, "basic_mm", source) // registry: apps, Python, sweeps
7//
8// `source == nullptr` selects the synthetic market: with the matching fill model the
9// MarketGenerator is coupled to the venue (strategy orders rest in the same book as the
10// synthetic flow); with the L2 queue model a SyntheticSource stream is replayed exactly like
11// historical data. A non-null source is read from its current position (reset() it first to
12// reuse one).
17#include "fastmm/core/engine_runner.hpp"
18#include "fastmm/sim/recorded_session.hpp"
19#include "fastmm/sim/sim_backend.hpp"
22
23#include <cstddef>
24#include <cstdint>
25#include <functional>
26#include <memory>
27#include <span>
28#include <string_view>
29
30namespace fastmm::bt {
31
32class BacktestSession {
33 public:
34 // `schema`: the strategy's parameters, recorded in cfg.journal_out (may be null).
35 // `strategy_meta`: `key=value` lines recorded in cfg.journal_out (Python strategies).
37 MdSource* source,
38 const ParamSchema* schema = nullptr,
39 std::string_view strategy_meta = {});
41 BacktestSession(const BacktestSession&) = delete;
44 [[nodiscard]] RunnerDeps& deps() noexcept { return deps_; }
45 [[nodiscard]] sim::SimBackend& backend() noexcept { return *backend_; }
46 // Parameter updates delivered at simulated times during run() (not owned; may be null).
47 void set_param_schedule(sim::ParamSchedule* schedule) noexcept { params_ = schedule; }
48 // [ab] and [strategy.overrides]: builds the run's publisher with `publisher`
49 // (StrategyEntry::publisher), so the overrides reach the engine before the first event and the
50 // arms' updates at their times during run(). A configuration with either needs it
51 // (BacktestConfig::publishes_params). Throws std::invalid_argument when the arms or the
52 // overrides do not fit the strategy (ab_test.hpp, param_overrides.hpp).
54 // enable_ab() with the publisher `make_publisher` builds on the sink it is given: a strategy
55 // whose parameters are not a FASTMM_PARAMS struct (a Python strategy's HotParamTable).
56 void enable_ab(const std::function<std::unique_ptr<ParamPublisher>(ParamSink)>& make_publisher);
57 // Code run at simulated times during run() (sim::SimDriver::set_slow_hooks).
58 void set_slow_hooks(const sim::SlowHooks& hooks) noexcept { slow_ = hooks; }
59 // Runs to the end of the data / horizon. `runner` (may be null) supplies engine stats and, with
60 // [strategy] state_file, the strategy's state to write at the end.
61 BacktestResult run(const sim::EngineHooks& hooks,
62 IEngineRunner* runner,
63 std::string_view strategy_name);
64
65 // run() in steps, for a multiverse (multiverse.hpp), whose runs share the recorded events and
66 // the market data forwarded from them: begin(hooks, runner, &next) leaves the source to the
67 // caller, which keeps `next` at the venue time of the next recorded event (Timestamp::max() when
68 // there is none) and for each event its runs share calls advance_before(the event's key) (false:
69 // this run is over), then hands it the event: world_event() (or its halves) for a recorded event
70 // after the shared SimWorld took its half, shared_market_data() for market data at its arrival.
71 // end() runs what is left and returns what run() would have. begin(.., nullptr) + end() is run().
72 void begin(const sim::EngineHooks& hooks, IEngineRunner* runner, const Timestamp* world);
73 bool advance_before(sim::SimKey k);
74 void world_event(const EventHeader& md) noexcept;
75 void world_venue_event(const EventHeader& md) noexcept;
76 void world_feed_event(const EventHeader& md) noexcept;
77 void shared_market_data(const EventHeader& md) noexcept;
78 // The key of this run's own next event or stop (equity bar, markout); never() once it is over.
79 [[nodiscard]] sim::SimKey next_key();
80 // After shared_market_data(): the earliest event the engine's step added (SimDriver::step_key).
81 [[nodiscard]] sim::SimKey step_key();
82 // The clock at the last event the run shared (which it may not have had to take).
83 void reach(Timestamp t) noexcept;
84 // Market data the multiverse did not hand the run, which its engine did not need
85 // (SimDriver::credit_market_data).
86 void credit_market_data(std::uint64_t n) noexcept;
87 // The engine asked to stop: the run takes no further event.
88 [[nodiscard]] bool stopped() const noexcept;
89 BacktestResult end(std::string_view strategy_name);
91 // A run over a journal that is being followed (backtest/follow_source.hpp): a record of the
92 // session it did not have at its start, before the run has reached the record's time.
93 void take_record(const EventHeader& record);
94 // What the run has so far: the fills up to the event it last took and the equity bars it has
95 // passed. A caller that keeps what it needs of them can forget_rows() the first `fills` and
96 // `bars`: a run over weeks of data then holds about one bar's worth. end()'s result covers what
97 // was not forgotten. Fills whose markouts are still to come stay.
98 [[nodiscard]] const FillRows& fill_rows() const noexcept;
99 [[nodiscard]] const EquityRows& equity_rows() const noexcept;
100 // Returns how many fills it forgot.
101 std::size_t forget_rows(std::size_t fills, std::size_t bars);
102 // The order messages the run has sent.
103 [[nodiscard]] std::uint64_t orders_sent() const noexcept;
104
105 private:
106 struct Loop;
107 bool advance(sim::SimKey limit);
108 [[nodiscard]] Timestamp next_stop() const noexcept;
109 std::unique_ptr<Loop> loop_;
110 struct Impl;
111 BacktestConfig cfg_;
112 MdSource* source_;
113 const ParamSchema* schema_;
114 std::unique_ptr<SyntheticSource> synthetic_;
115 std::unique_ptr<sim::MarketGenerator> generator_;
116 std::unique_ptr<sim::SimBackend> backend_;
117 // initial_state = journal: the positions the recorded session started with, and where they and
118 // the strategy's state came from.
119 std::vector<ReconcileMsg> start_positions_;
120 std::string start_note_;
121 // Where the bytes the strategy restores come from, for a version mismatch's message.
122 std::string state_what_ = "the state to restore";
123 // start_at: when trading starts, the venues that reconcile then (bit per venue id) and the
124 // checkpoint's bytes the strategy restores then.
125 Timestamp trade_at_{};
126 std::uint32_t trade_venues_ = 0;
127 std::string staged_state_;
128 std::uint32_t staged_version_ = 0; // its state_version
129 bool staged_empty_ = false; // the checkpoint has no strategy bytes
130 // balances_from_journal: the session's flows of money and account refreshes after the balances
131 // the accounts start from.
132 std::vector<AccountFlowMsg> flows_;
133 // What the run's own transfers move (sim::pool_transfer): the swept pools' base assets.
134 std::vector<sim::TransferScope> scopes_;
135 std::vector<std::pair<VenueId, Timestamp>> refreshes_;
136 // controls_from_journal: the session's operator commands (each as recorded), in time order.
137 std::vector<std::vector<std::uint64_t>> controls_;
138 // params_from_journal: the session's updates on this strategy's schema, and the schedule they go
139 // to when the caller sets none.
140 std::vector<ParamUpdateMsg> journal_params_;
141 [[nodiscard]] bool journal_param(ParamUpdateMsg& m) const noexcept;
142 [[nodiscard]] bool flow_applies(VenueId v, Timestamp t) const;
143 [[nodiscard]] bool refresh_applies(VenueId v, Timestamp t) const;
144 // A recorded Control the run takes as input (controls_from_journal): an operator command
145 // (sim::replayable_control), not the engine's own record, and no planner move of a pool the run
146 // plans itself.
147 [[nodiscard]] bool replays_control(const EventHeader& h) const;
148 void wake_slow_tier();
149 std::vector<int> param_map_; // recorded field index -> this schema's, -1: none
150 // balances_from_journal: each venue's first snapshot, what its account starts from.
151 std::vector<std::pair<VenueId, Timestamp>> account_origin_;
152 bool following_ = false; // the journal is still being written
153 std::unique_ptr<sim::ParamSchedule> own_params_;
154 std::unique_ptr<Impl> impl_;
155 RunnerDeps deps_;
156 sim::ParamSchedule* params_ = nullptr;
157 sim::SlowHooks slow_{};
158 struct AbRun;
159 std::unique_ptr<AbRun> ab_;
160};
161
162template <StrategyLike S>
163BacktestResult run_backtest(const BacktestConfig& cfg, MdSource* source = nullptr) {
164 BacktestSession session(cfg, source, &S::schema());
165 if (cfg.publishes_params()) session.enable_ab(detail::publisher_factory<S>());
166 std::unique_ptr<IEngineRunner> runner = session.backend().template make_runner<S>(session.deps());
167 return session.run(session.backend().hooks, runner.get(), S::name());
168}
169
170// Registry path (registers the built-in strategies first). Throws std::invalid_argument for
171// an unknown strategy or bad parameters.
172BacktestResult run_backtest(const BacktestConfig& cfg,
173 std::string_view strategy,
174 MdSource* source = nullptr);
175
176// Convenience wrapper that owns the config.
177template <StrategyLike S>
178class BacktestRunner {
179 public:
180 explicit BacktestRunner(BacktestConfig cfg) : cfg_(std::move(cfg)) {}
181 [[nodiscard]] BacktestConfig& config() noexcept { return cfg_; }
182 [[nodiscard]] const BacktestConfig& config() const noexcept { return cfg_; }
183 BacktestResult run(MdSource* source = nullptr) { return run_backtest<S>(cfg_, source); }
185 private:
186 BacktestConfig cfg_;
187};
188
189// `cfg` for runs that start from one place: the points of a sweep, the folds of a walk-forward,
190// the arms of an [ab] branch test. The [strategy] state_file is read once into the strategy's
191// initial state and dropped, so every run restores the same bytes and none writes its end state
192// back, where the runs would race on the file and each would start from another's end. Throws
193// std::invalid_argument when the file cannot be read.
195
196// The SyntheticSource a run with `source == nullptr` replays under the L2 queue fill model.
198
199// Logs a warning for each instrument the data gave no events, and for the events that named an
200// instrument id past the table. by_instrument: events per id, its last entry those past the table
201// (sim::SimDriver::by_instrument()).
202void warn_unfed_instruments(const InstrumentTable& instruments,
203 std::span<const std::uint64_t> by_instrument);
205// Resolves `--data` through the data-source registry (data_registry.hpp): "<name>:<args>",
206// or a bare *.fmj / *.csv path. "synthetic" (and "") open to nullptr, which selects the market
207// generator. `instruments` lets a source map its symbols onto instrument ids; it may be null.
208// Throws std::runtime_error for an unknown source, bad options or unreadable files.
209[[nodiscard]] std::unique_ptr<MdSource> open_data(std::string_view spec,
210 const InstrumentTable* instruments = nullptr);
211// Source for [backtest] source / path. `source` is a whole spec ("binance:BTCUSDT:2024-03-27");
212// a bare name plus `path` ("journal" + "x.fmj") is the same thing written as two keys.
213[[nodiscard]] std::unique_ptr<MdSource> open_source(const BacktestConfig& cfg);
214
215} // namespace fastmm::bt
BacktestResult (8.4): structure-of-arrays rows (numpy-friendly: each column is one contiguous vector)...
BacktestConfig: everything a run needs, assembled from the TOML sections [engine] [[instruments]] [st...
Dense-by-id table built at startup; symbol lookup is a sorted FlatMap keyed by (venue,...
Definition instrument.hpp:147
Definition params.hpp:102
Convenience wrapper that owns the config.
Definition backtest_runner.hpp:180
BacktestResult run(MdSource *source=nullptr)
Definition backtest_runner.hpp:185
BacktestConfig & config() noexcept
Definition backtest_runner.hpp:183
Definition backtest_runner.hpp:34
void world_event(const EventHeader &md) noexcept
void reach(Timestamp t) noexcept
The clock at the last event the run shared (which it may not have had to take).
const FillRows & fill_rows() const noexcept
What the run has so far: the fills up to the event it last took and the equity bars it has passed.
void take_record(const EventHeader &record)
A run over a journal that is being followed (backtest/follow_source.hpp): a record of the session it ...
void set_slow_hooks(const sim::SlowHooks &hooks) noexcept
Code run at simulated times during run() (sim::SimDriver::set_slow_hooks).
Definition backtest_runner.hpp:60
bool stopped() const noexcept
The engine asked to stop: the run takes no further event.
void enable_ab(StrategyEntry::PublisherFactory publisher)
[ab] and [strategy.overrides]: builds the run's publisher with publisher (StrategyEntry::publisher),...
std::size_t forget_rows(std::size_t fills, std::size_t bars)
Returns how many fills it forgot.
void begin(const sim::EngineHooks &hooks, IEngineRunner *runner, const Timestamp *world)
run() in steps, for a multiverse (multiverse.hpp), whose runs share the recorded events and the marke...
void shared_market_data(const EventHeader &md) noexcept
sim::SimKey step_key()
After shared_market_data(): the earliest event the engine's step added (SimDriver::step_key).
RunnerDeps & deps() noexcept
Definition backtest_runner.hpp:46
BacktestResult run(const sim::EngineHooks &hooks, IEngineRunner *runner, std::string_view strategy_name)
Runs to the end of the data / horizon.
BacktestSession & operator=(const BacktestSession &)=delete
const EquityRows & equity_rows() const noexcept
bool advance_before(sim::SimKey k)
void world_venue_event(const EventHeader &md) noexcept
BacktestResult end(std::string_view strategy_name)
sim::SimBackend & backend() noexcept
Definition backtest_runner.hpp:47
void world_feed_event(const EventHeader &md) noexcept
sim::SimKey next_key()
The key of this run's own next event or stop (equity bar, markout); never() once it is over.
void set_param_schedule(sim::ParamSchedule *schedule) noexcept
Parameter updates delivered at simulated times during run() (not owned; may be null).
Definition backtest_runner.hpp:49
void credit_market_data(std::uint64_t n) noexcept
Market data the multiverse did not hand the run, which its engine did not need (SimDriver::credit_mar...
std::uint64_t orders_sent() const noexcept
The order messages the run has sent.
Definition synthetic_source.hpp:31
Definition param_schedule.hpp:38
DataSource (8.4): a timestamp-ordered stream of normalized market-data events consumed by the simulat...
Strategy modules (ADR-0012, section 5): one registration function per strategy library.
Definition backtest_config.hpp:44
std::unique_ptr< MdSource > open_data(std::string_view spec, const InstrumentTable *instruments=nullptr)
Resolves --data through the data-source registry (data_registry.hpp): "<name>:<args>",...
void warn_unfed_instruments(const InstrumentTable &instruments, std::span< const std::uint64_t > by_instrument)
Logs a warning for each instrument the data gave no events, and for the events that named an instrume...
BacktestConfig shared_start(BacktestConfig cfg)
cfg for runs that start from one place: the points of a sweep, the folds of a walk-forward,...
SyntheticSourceConfig synthetic_source_config(const BacktestConfig &cfg)
The SyntheticSource a run with source == nullptr replays under the L2 queue fill model.
BacktestResult run_backtest(const BacktestConfig &cfg, MdSource *source=nullptr)
Definition backtest_runner.hpp:165
std::unique_ptr< MdSource > open_source(const BacktestConfig &cfg)
Source for [backtest] source / path.
Strategy registry (8.6, ADR-0012): name -> parameter schema + one factory per transport kind,...
Definition messages.hpp:38
Where a built update goes; push returns false when it was not accepted (full).
Definition param_publisher.hpp:49
New strategy parameter values (ADR-0013): up to kMaxFields (field index, raw value) pairs,...
Definition messages.hpp:795
Control thread injects the venue's view after a reconnect (5.8).
Definition messages.hpp:668
Everything a factory needs that is backend-independent.
Definition registry.hpp:51
std::unique_ptr< ParamPublisher >(*)(ParamSink, const ParamMap &, std::size_t instruments) PublisherFactory
Builds a publisher for this strategy's parameters over sink, its copy seeded with the values the sess...
Definition registry.hpp:74
Definition time.hpp:45
Definition backtest_config.hpp:80
Definition result.hpp:116
Definition result.hpp:54
Definition result.hpp:20
Definition synthetic_source.hpp:20
SyntheticSource: a MarketGenerator run against its own MatchingEngine, published through MdAggregator...