FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
backtest_config.hpp
Go to the documentation of this file.
1#pragma once
2// BacktestConfig: everything a run needs, assembled from the TOML sections
3// [engine] [[instruments]] [strategy] [strategy.params] [risk] [venues.<x>.fees] [sim]
4// [backtest] (8.4, 8.7) or built by hand (examples, tests, Python).
5//
6// [backtest] [sim] (synthetic market)
7// source = "synthetic" | "journal" | "csv" seed, duration_s, start_mid,
8// path = "data.fmj" | "data.csv" depth_update_ms, book_ticker,
9// seed = 1 limit_rate_per_s, market_rate_per_s,
10// duration_s = 60 (synthetic horizon) mid_step_rate_per_s,
11// fill_model = "matching" | "l2_queue" cancel_rate_per_order_s, offset_p,
12// queue_conservatism = 0..1 base_spread_ticks, limit_qty_median_lots,
13// latency_fixed_us, latency_jitter_us, market_qty_median_lots, regimes,
14// latency_ack_us, latency_ack_jitter_us,
15// latency_md_us, latency_md_jitter_us, p_drop volatile_mult, seed_levels, spread_bps,
16// mid_step_bps, mid_step_ticks, depth_bps
17// latency_cancel_us, latency_cancel_jitter_us, order_service_us
18// md_arrival = "venue" | "recorded", reorder_window_ms = 1000
19// balances_from_journal = false, own_orders_in_feed = true, transfer_latency_ms = 0
20// initial_state = "state_file" | "journal" | "none", params_from_journal = false, params_pinned,
21// controls_from_journal = false
22// [backtest.balances] <ASSET> = "<amount>" (and [backtest.venues.<name>.balances])
23// [backtest.positions] <SYMBOL> = "<qty>" | "<qty>@<avg_px>"
24// start_at = <unix s> | "<UTC time>", latency_from_journal = false
25// equity_bar_s = 1, initial_capital = 0
26// markout_horizons_s = "1,10,60"
27// output_dir = "runs/backtest", journal_out = ""
29#include "fastmm/core/engine.hpp"
31#include "fastmm/core/treasury.hpp"
32#include "fastmm/sim/market_generator.hpp"
33#include "fastmm/sim/sim_transport.hpp"
35
36#include <array>
37#include <cstdint>
38#include <string>
39#include <string_view>
40#include <vector>
41
42namespace fastmm::bt {
43
44// The backtest settings a sweep's point can vary besides the strategy's parameters
45// (BacktestConfig::set_setting). The Python BacktestConfig has an attribute of each name.
46inline constexpr std::array<std::string_view, 8> kSweepSettings = {"latency_fixed_us",
47 "latency_jitter_us",
48 "latency_md_us",
49 "latency_md_jitter_us",
50 "p_drop",
51 "queue_conservatism",
52 "maker_fee_bps",
53 "taker_fee_bps"};
54
55// Where the strategy's starting state comes from ([backtest] initial_state).
56enum class InitialState : std::uint8_t {
57 StateFile = 0, // [strategy] state_file, when set
58 Journal = 1, // the data journal's (journal_state.hpp), with the session's positions
59 None = 2, // nothing: the strategy starts fresh
60};
61
62// The [sim] defaults of a configuration file: a liquid crypto pair. New limit orders leave 4 bps
63// around the latent mid and rest 1 bps behind that on average; orders a mid move left behind rest
64// inside it, so the book's spread is 1.7 to 3.4 bps (10th to 90th percentile), 2.7 at the median.
65// Latent mid steps of 0.5 bps, 2 a second calm and 8 volatile, give 0.4 to 0.7 bps of volatility a
66// square-root second.
67inline constexpr double kDefaultSpreadBps = 4.0;
68inline constexpr double kDefaultMidStepBps = 0.5;
69inline constexpr double kDefaultDepthBps = 1.0;
71// One [backtest.positions] row: the engine starts with this position in the instrument.
72struct StartPosition {
81 std::string strategy; // registry name (apps / Python); ignored by run_backtest<S>()
83 sim::SimTransportConfig transport;
84 sim::MarketGeneratorParams generator;
85 std::uint64_t seed = 1; // synthetic market + latency model (engine.rng_seed is separate)
86 Timestamp start{seconds(1'700'000'000).ns}; // synthetic start; data sources use their own
87 Duration duration = seconds(60); // synthetic horizon
89 double initial_capital = 0.0; // reporting only (drawdown %)
90 // [accounting] and the venue names its sources name (Config::venues order). from_config() builds
91 // engine.fx from them for `instruments`; replay builds it again for the journal's table.
92 AccountingSpec accounting;
93 std::vector<std::string> venue_names;
94 // [risk.underlying]: from_config() builds engine.underlying from it for `instruments`; replay
95 // builds it again for the journal's table.
96 UnderlyingSpec underlying;
97 // from_config: Config::warnings plus unknown [backtest] keys, each naming the key and its line.
98 std::vector<std::string> warnings;
99 int generator_seed_levels = 20;
100 std::string source; // "synthetic" | "journal" | "csv" | "" (caller supplies the source)
101 std::string path;
102 std::string output_dir;
103 std::string journal_out; // record the run to this .fmj (empty = no journal)
104 // Where the engine puts its records (core/record_stream.hpp), as fastmm-live hands them to the
105 // store: the caller's ring, drained by the caller, large enough for the run (a full ring drops
106 // records). Null: none.
107 MsgRing* record_ring = nullptr;
108 // Effective configuration embedded in journal_out (Config::effective_toml(); from_config() sets
109 // it, hand-built configs leave it empty). Callers that override fields after from_config()
110 // must refresh or clear it.
111 std::string config_toml;
112 bool measure_wall_clock = true;
113 // The result keeps a row for every order sent (BacktestResult::orders). A sweep's points do not:
114 // their metrics count the orders as they go (OrderStats), and the outbound hash covers them.
115 bool keep_orders = true;
116 // Post-fill markout horizons in simulated time; empty turns markouts off. The run stops the
117 // simulated clock at every fill time + horizon to read the venue mid there, so the shortest
118 // horizon also bounds how often the run loop is entered.
119 std::vector<Duration> markout_horizons = {seconds(1), seconds(10), seconds(60)};
120 // Start each venue's account (transport.accounts) from the first balance snapshot the journal
121 // source recorded for it; a venue it has none for keeps the configured balances.
122 bool balances_from_journal = false;
123 // The pool treasuries ([venues.<primary>.treasury] with enabled): each runs on simulated time
124 // against its pool's simulated accounts (sim/sim_treasury.hpp), without a ledger file. Empty:
125 // none, and the run is what it was without them.
126 std::vector<TreasuryConfig> treasuries;
127 // [backtest] transfer_latency_ms: a simulated transfer is carried out this long after it is sent.
129 // [backtest] transfer_p_fail, transfer_p_unknown, transfer_hang_ms: the simulated venue refuses a
130 // transfer, or loses its answer and carries it out transfer_hang later (sim::SimTransferFaults).
131 double transfer_p_fail = 0.0;
132 double transfer_p_unknown = 0.0;
134 // The strategy's starting state; Journal also starts the engine's positions where the recorded
135 // session had them (sim::SessionStart).
137 // [backtest.positions]: the engine's positions at the start, by instrument. They replace the
138 // journal's (initial_state = "journal") for the instruments listed: a backtest that starts at a
139 // part from the middle of a session, whose records do not repeat the positions, starts where the
140 // session was.
141 std::vector<StartPosition> positions;
142 // [backtest] start_at: the run reads the data from its start (the books and the strategy's view
143 // of the market warm up), but trading starts later: with initial_state = "journal" at the last
144 // checkpoint of the data journal at or before this time, whose state the strategy restores as a
145 // warm standby's take-over does, else at this time. Until then every venue an order can go to
146 // has not reconciled, so the engine refuses orders (NotReconciled); at the start each one
147 // reconciles with the start positions. Invalid: trading starts with the data.
149 // [backtest] latency_from_journal: the simulated venues take a message's latency from the data
150 // journal's own messages around the same time where that is longer than the model's draw
151 // (sim/recorded_latency.hpp); the data source must be a journal.
152 bool latency_from_journal = false;
153 // The data journal's parameter updates reach the strategy at the times the session received
154 // them (sim::RecordedParams), mapped by name and type onto its schema.
155 bool params_from_journal = false;
156 // params_from_journal leaves these parameters at the configured values: a counterfactual run
157 // keeps the session's other updates ([backtest] params_pinned, comma-separated).
158 std::vector<std::string> params_pinned;
159 // The data journal's operator commands (sim::replayable_control) reach the engine at the times
160 // the session received them.
161 bool controls_from_journal = false;
162 // [ab]: an A/B test of the strategy's parameters (strategies/ab_test.hpp); no arms: none.
164 // [strategy.groups] and [strategy.overrides]: parameters per instrument, set at the start
165 // (strategies/param_overrides.hpp).
166 std::map<std::string, std::vector<std::string>> param_groups;
167 std::map<std::string, ParamMap> param_overrides;
168 // The run publishes parameter updates of its own: [ab] or [strategy.overrides]
169 // (BacktestSession::enable_ab).
170 [[nodiscard]] bool publishes_params() const noexcept {
171 return ab.enabled() || !param_overrides.empty();
173 // [ab] assignment = "branch": the arm this run is (an index into ab.arms); fastmm-backtest runs
174 // each one in turn.
175 int ab_arm = -1;
176 // Recorded data reaches the simulated venue in venue-time order (sim/venue_order.hpp), assuming
177 // no event was received more than this after its venue time; zero keeps the recorded order.
179
180 // Throws ConfigError on invalid values.
181 [[nodiscard]] static BacktestConfig from_config(const Config& cfg);
182 // One instrument (venue 0) with the given tick/lot; generator tick/lot follow (examples).
183 [[nodiscard]] static BacktestConfig single_instrument(std::string_view symbol,
184 Price tick,
185 Qty lot);
186
187 // The FX plan for `table` under `accounting` (throws ConfigError when a limit reads the totals
188 // and the table is not covered; otherwise a warning goes to `warnings` and nothing converts).
189 [[nodiscard]] FxPlan fx_plan(const InstrumentTable& table);
190 // The [risk.underlying] plan for `table` (throws ConfigError when the spec does not fit it).
191 [[nodiscard]] UnderlyingPlan underlying_plan(const InstrumentTable& table) const;
192
193 // The synthetic market in basis points of generator.start_mid, turned into ticks of
194 // generator.tick: the spread from touch to touch (base_spread_ticks, half of it a side), the
195 // size of a latent mid step (mid_step_ticks) and the mean distance of a new limit order behind
196 // the touch (depth_ticks). Each comes to at least one tick. from_config() applies the [sim]
197 // defaults below unless the tick keys are given; single_instrument() keeps the one-tick market
198 // of MarketGeneratorParams.
199 void set_market_bps(double spread_bps, double mid_step_bps, double depth_bps);
200
201 // Sets one of kSweepSettings from its decimal value: latency_fixed_us and latency_jitter_us the
202 // order and ack paths of the venues without a [backtest.venues.<name>] entry, latency_md_us and
203 // latency_md_jitter_us their market data, p_drop the share of orders lost, queue_conservatism
204 // the queue model's, maker_fee_bps and taker_fee_bps one schedule for every instrument.
205 // Returns false for any other key; throws std::invalid_argument for a value out of range.
206 bool set_setting(std::string_view key, std::string_view value);
207 // "key=value" strategy parameter override (CLI --param).
208 void set_param(const std::string& key, const std::string& value) { params[key] = value; }
209 // Seeds the synthetic market and the latency model.
210 void set_seed(std::uint64_t s) noexcept {
211 seed = s;
212 transport.seed = s;
213 }
214};
215
216} // namespace fastmm::bt
Definition config.hpp:502
Dense-by-id table built at startup; symbol lookup is a sorted FlatMap keyed by (venue,...
Definition instrument.hpp:147
Typed configuration (8.7).
Instrument: the single definition of a tradable contract (5.3 / 5.15).
Definition backtest_config.hpp:44
InitialState
Where the strategy's starting state comes from ([backtest] initial_state).
Definition backtest_config.hpp:58
@ StateFile
[strategy] state_file, when set
@ None
nothing: the strategy starts fresh
@ Journal
the data journal's (journal_state.hpp), with the session's positions
constexpr double kDefaultMidStepBps
Definition backtest_config.hpp:70
constexpr double kDefaultSpreadBps
The [sim] defaults of a configuration file: a liquid crypto pair.
Definition backtest_config.hpp:69
constexpr double kDefaultDepthBps
Definition backtest_config.hpp:71
constexpr std::array< std::string_view, 8 > kSweepSettings
The backtest settings a sweep's point can vary besides the strategy's parameters (BacktestConfig::set...
Definition backtest_config.hpp:48
constexpr Duration milliseconds(std::int64_t v) noexcept
Definition time.hpp:38
constexpr Duration seconds(std::int64_t v) noexcept
Definition time.hpp:41
std::map< std::string, std::string > ParamMap
Definition params.hpp:119
Strategy parameter schema (8.6, ADR-0012).
Definition config.hpp:329
bool enabled() const noexcept
Definition config.hpp:345
Definition time.hpp:22
std::int64_t ns
Definition time.hpp:23
Definition engine_config.hpp:41
Definition time.hpp:45
Definition backtest_config.hpp:80
double initial_capital
reporting only (drawdown %)
Definition backtest_config.hpp:91
std::vector< StartPosition > positions
[backtest.positions]: the engine's positions at the start, by instrument. They replace the
Definition backtest_config.hpp:143
MsgRing * record_ring
Where the engine puts its records (core/record_stream.hpp), as fastmm-live hands them to the store: t...
Definition backtest_config.hpp:109
bool latency_from_journal
[backtest] latency_from_journal: the simulated venues take a message's latency from the data journal'...
Definition backtest_config.hpp:154
AccountingSpec accounting
[accounting] and the venue names its sources name (Config::venues order).
Definition backtest_config.hpp:94
UnderlyingPlan underlying_plan(const InstrumentTable &table) const
The [risk.underlying] plan for table (throws ConfigError when the spec does not fit it).
std::string path
Definition backtest_config.hpp:103
std::vector< TreasuryConfig > treasuries
The pool treasuries ([venues.
Definition backtest_config.hpp:128
void set_market_bps(double spread_bps, double mid_step_bps, double depth_bps)
The synthetic market in basis points of generator.start_mid, turned into ticks of generator....
std::string strategy
registry name (apps / Python); ignored by run_backtest<S>()
Definition backtest_config.hpp:83
std::string config_toml
Effective configuration embedded in journal_out (Config::effective_toml(); from_config() sets it,...
Definition backtest_config.hpp:113
InstrumentTable instruments
Definition backtest_config.hpp:82
std::string output_dir
Definition backtest_config.hpp:104
std::map< std::string, std::vector< std::string > > param_groups
[strategy.groups] and [strategy.overrides]: parameters per instrument, set at the start (strategies/p...
Definition backtest_config.hpp:168
bool balances_from_journal
Start each venue's account (transport.accounts) from the first balance snapshot the journal source re...
Definition backtest_config.hpp:124
Duration reorder_window
Recorded data reaches the simulated venue in venue-time order (sim/venue_order.hpp),...
Definition backtest_config.hpp:180
static BacktestConfig single_instrument(std::string_view symbol, Price tick, Qty lot)
One instrument (venue 0) with the given tick/lot; generator tick/lot follow (examples).
std::string source
"synthetic" | "journal" | "csv" | "" (caller supplies the source)
Definition backtest_config.hpp:102
bool params_from_journal
The data journal's parameter updates reach the strategy at the times the session received them (sim::...
Definition backtest_config.hpp:157
InitialState initial_state
The strategy's starting state; Journal also starts the engine's positions where the recorded session ...
Definition backtest_config.hpp:138
static BacktestConfig from_config(const Config &cfg)
Throws ConfigError on invalid values.
int ab_arm
[ab] assignment = "branch": the arm this run is (an index into ab.arms); fastmm-backtest runs each on...
Definition backtest_config.hpp:177
bool measure_wall_clock
Definition backtest_config.hpp:114
Timestamp start
Definition backtest_config.hpp:88
bool set_setting(std::string_view key, std::string_view value)
Sets one of kSweepSettings from its decimal value: latency_fixed_us and latency_jitter_us the order a...
std::string journal_out
record the run to this .fmj (empty = no journal)
Definition backtest_config.hpp:105
double transfer_p_unknown
Definition backtest_config.hpp:134
FxPlan fx_plan(const InstrumentTable &table)
The FX plan for table under accounting (throws ConfigError when a limit reads the totals and the tabl...
ParamMap params
Definition backtest_config.hpp:84
int generator_seed_levels
Definition backtest_config.hpp:101
std::map< std::string, ParamMap > param_overrides
Definition backtest_config.hpp:169
sim::SimTransportConfig transport
Definition backtest_config.hpp:85
std::vector< std::string > warnings
from_config: Config::warnings plus unknown [backtest] keys, each naming the key and its line.
Definition backtest_config.hpp:100
void set_seed(std::uint64_t s) noexcept
Seeds the synthetic market and the latency model.
Definition backtest_config.hpp:212
std::uint64_t seed
synthetic market + latency model (engine.rng_seed is separate)
Definition backtest_config.hpp:87
bool publishes_params() const noexcept
The run publishes parameter updates of its own: [ab] or [strategy.overrides] (BacktestSession::enable...
Definition backtest_config.hpp:172
std::vector< std::string > params_pinned
params_from_journal leaves these parameters at the configured values: a counterfactual run keeps the ...
Definition backtest_config.hpp:160
Duration transfer_latency
[backtest] transfer_latency_ms: a simulated transfer is carried out this long after it is sent.
Definition backtest_config.hpp:130
bool keep_orders
The result keeps a row for every order sent (BacktestResult::orders).
Definition backtest_config.hpp:117
Duration transfer_hang
Definition backtest_config.hpp:135
sim::MarketGeneratorParams generator
Definition backtest_config.hpp:86
AbSection ab
[ab]: an A/B test of the strategy's parameters (strategies/ab_test.hpp); no arms: none.
Definition backtest_config.hpp:165
UnderlyingSpec underlying
[risk.underlying]: from_config() builds engine.underlying from it for instruments; replay builds it a...
Definition backtest_config.hpp:98
EngineConfig engine
Definition backtest_config.hpp:81
double transfer_p_fail
[backtest] transfer_p_fail, transfer_p_unknown, transfer_hang_ms: the simulated venue refuses a trans...
Definition backtest_config.hpp:133
Duration duration
synthetic horizon
Definition backtest_config.hpp:89
bool controls_from_journal
The data journal's operator commands (sim::replayable_control) reach the engine at the times the sess...
Definition backtest_config.hpp:163
std::vector< Duration > markout_horizons
Post-fill markout horizons in simulated time; empty turns markouts off.
Definition backtest_config.hpp:121
Duration equity_bar
Definition backtest_config.hpp:90
std::vector< std::string > venue_names
Definition backtest_config.hpp:95
void set_param(const std::string &key, const std::string &value)
"key=value" strategy parameter override (CLI --param).
Definition backtest_config.hpp:210
Timestamp start_at
[backtest] start_at: the run reads the data from its start (the books and the strategy's view of the ...
Definition backtest_config.hpp:150
One [backtest.positions] row: the engine starts with this position in the instrument.
Definition backtest_config.hpp:74
Price avg_px
Definition backtest_config.hpp:77
Qty qty
Definition backtest_config.hpp:76
InstrumentId instrument
Definition backtest_config.hpp:75