FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
backend.hpp
Go to the documentation of this file.
1#pragma once
2// Storage backend interface: what a session's fills, orders, positions, PnL and kill events are
3// handed to, so they can be queried without replaying the journal.
4//
5// engine thread --RecordWriter--> MsgRing --StoreThread--> Backend --> rows
6//
7// The journal stays the byte-exact stream a replay consumes (core/journal.hpp); a backend holds
8// the interpreted record. Backends are selected by name from [storage] backend and built by the
9// registry (store/registry.hpp); "sqlite" ships with FastMM and "none" means no backend at all.
10//
11// What a backend must guarantee (docs/reference/storage.md):
12// * Ordering. Records arrive in the order the engine made them, on one thread, and seq is
13// strictly increasing within a session. Calls between begin() and commit() are one batch.
14// * At most once. A record the ring dropped, or a batch the process died inside of, is gone; a
15// backend must not invent one. Records carry keys (session id + seq, and an exec id on a
16// fill) so re-ingesting the same record is a no-op.
17// * Never block the caller for long. StoreThread runs the backend on its own thread, so a slow
18// commit costs ring space, not engine latency, but a backend that blocks for seconds will
19// overflow the ring and lose records.
20// * Never throw across the interface, and never abort the process. A failure is counted in
21// errors() and described by last_error(); the session keeps trading unless [storage]
22// kill_on_failure is set.
23//
24// Everything here runs off the engine thread and may allocate.
26#include "fastmm/core/engine_runner.hpp"
27#include "fastmm/core/enums.hpp"
31
32#include <cstdint>
33#include <span>
34#include <string>
35#include <string_view>
36#include <vector>
37
38namespace fastmm::store {
39
40// What a backend is built with. `config` is the [storage] section verbatim: a backend reads its
41// own keys from it and the central schema (config/schema.hpp) knows none of them.
42struct BackendOptions {
43 const GenericSection* config = nullptr;
44 std::string engine_name; // [engine] name
45 std::string default_dir; // [engine] journal_dir; where a backend may default its files
46 bool read_only = false; // opened by a query tool, not by a session
47};
49// Written once, before any record.
50struct SessionOpen {
51 std::uint64_t session_id = 0;
52 std::uint16_t session_epoch = 0;
53 std::int64_t started_ns = 0;
54 std::string engine_name;
55 std::string strategy;
56 std::string version; // FASTMM_VERSION_STRING
57 std::string build_info; // compiler, flags, build type
58 std::uint64_t config_hash = 0;
59 std::string config_toml; // effective configuration, secrets omitted
60 std::string journal_path; // first journal part; empty when journaling is off
61 std::string host;
62 std::uint32_t pid = 0;
63 bool dry_run = false;
64 std::int64_t pnl_carry_raw = 0; // net PnL carried in from earlier sessions
65 std::vector<std::string> venues; // [venues.<name>] by VenueId, so a restart finds its own again
66 // The strategy's parameter table in schema order: a ParamRecord's field index names an entry.
67 // `type` is the journal's parameter type (ParamType: 0 int, 1 double, 2 bool, 3 decimal, 4 bps,
68 // 5 ms).
69 struct ParamField {
70 std::string name;
71 std::uint8_t type = 0;
72 };
73 std::vector<ParamField> param_table;
74 // The parameters the session starts with. Every parameter of the table when params_complete;
75 // otherwise the configured ones only ([strategy.params], --param), with no raw value.
76 struct ParamValue {
77 std::string name;
78 std::string text;
79 std::int64_t raw = 0;
80 bool has_raw = false;
81 };
82 std::vector<ParamValue> params;
83 bool params_complete = false;
84 // [ab]: the test's name and its arms in order (ParamUpdateMsg::arm k + 1 names ab_arms[k]), each
85 // with its parameters as "name=value ..."; empty without a test.
86 std::string ab_test;
87 struct AbArm {
88 std::string name;
89 std::string params;
90 };
91 std::vector<AbArm> ab_arms;
92};
94// Written once, after the last record.
95struct SessionClose {
96 std::uint64_t session_id = 0;
97 std::int64_t stopped_ns = 0;
98 int exit_code = 0;
100 bool kill_latched = false;
101 bool journal_complete = true; // the journal was closed cleanly
102 std::uint64_t journal_bytes = 0;
103 std::vector<std::string> journal_paths; // every part, in order
104 RunnerStats stats;
107class Backend {
108 public:
109 Backend() = default;
110 virtual ~Backend() = default;
111 Backend(const Backend&) = delete;
112 Backend& operator=(const Backend&) = delete;
114 [[nodiscard]] virtual std::string_view name() const noexcept = 0;
115 // Opens or creates the store and brings its schema up to date. A failure here stops the
116 // session from starting: an operator who does not want a store sets backend = "none".
117 [[nodiscard]] virtual Result<void, std::string> open(const BackendOptions& opts) = 0;
118 [[nodiscard]] virtual Result<void, std::string> session_open(const SessionOpen& s) = 0;
119 // The instrument table of this session, by dense id.
120 [[nodiscard]] virtual Result<void, std::string> instruments(
121 std::uint64_t session_id, std::span<const Instrument> table) = 0;
123 // One batch. StoreThread calls begin(), then zero or more records, then commit().
124 virtual void begin() = 0;
125 virtual void fill(const FillRecord& r) = 0;
126 virtual void order(const OrderRecord& r) = 0;
127 virtual void position(const PositionRecord& r) = 0;
128 virtual void kill(const KillRecord& r) = 0;
129 // A funding payment. The default drops it: a backend written before funding was booked keeps
130 // building (its positions still carry funding inside realized).
131 virtual void funding(const FundingRecord& /*r*/) {}
132 // A venue's execution replay ended complete. The default drops it: a restart from such a store
133 // judges a session by whether it placed an order on the venue or shut down (Recovery).
134 virtual void replayed(const ReplayedRecord& /*r*/) {}
135 // A strategy parameter update the engine applied. The default drops it.
136 virtual void param(const ParamRecord& /*r*/) {}
137 // An order refused by the pre-trade checks or by its venue. The default drops it.
138 virtual void reject(const RejectRecord& /*r*/) {}
139 // An operator's risk limit change the engine applied. The default drops it.
140 virtual void limits(const LimitsRecord& /*r*/) {}
141 // The mid at or after a fill ([engine] markout_ms).
142 virtual void markout(const MarkoutRecord& /*r*/) {}
143 // A minute of one account's capacity price ([capacity]). The default drops it.
144 virtual void capacity(const CapacityRecord& /*r*/) {}
145 // The names of the strategy's quote context values (FillRecord::order_context). The default
146 // drops them.
147 virtual void context_names(const ContextNamesRecord& /*r*/) {}
148 virtual void commit() = 0;
150 // StoreThread calls it when the ring is empty, outside a batch, with the wall clock: a backend
151 // may do one small piece of housekeeping (the SQLite backend's [storage] retention_days) and
152 // must return within milliseconds, since records wait in the ring meanwhile. The default does
153 // nothing.
154 virtual void idle(std::int64_t /*now_ns*/) {}
155
156 [[nodiscard]] virtual Result<void, std::string> session_close(const SessionClose& s) = 0;
157 virtual void close() = 0;
159 // Any thread: fastmm-live reads them for the status file while the store thread writes.
160 [[nodiscard]] virtual std::uint64_t rows() const noexcept = 0;
161 [[nodiscard]] virtual std::uint64_t errors() const noexcept = 0;
162 [[nodiscard]] virtual std::string last_error() const = 0;
165} // namespace fastmm::store
Definition result.hpp:30
Definition backend.hpp:109
virtual void reject(const RejectRecord &)
An order refused by the pre-trade checks or by its venue. The default drops it.
Definition backend.hpp:140
virtual void idle(std::int64_t)
StoreThread calls it when the ring is empty, outside a batch, with the wall clock: a backend may do o...
Definition backend.hpp:156
virtual void begin()=0
One batch. StoreThread calls begin(), then zero or more records, then commit().
virtual void commit()=0
virtual ~Backend()=default
virtual void close()=0
Backend & operator=(const Backend &)=delete
virtual Result< void, std::string > session_close(const SessionClose &s)=0
virtual void markout(const MarkoutRecord &)
The mid at or after a fill ([engine] markout_ms).
Definition backend.hpp:144
virtual Result< void, std::string > open(const BackendOptions &opts)=0
Opens or creates the store and brings its schema up to date.
virtual void position(const PositionRecord &r)=0
virtual void param(const ParamRecord &)
A strategy parameter update the engine applied. The default drops it.
Definition backend.hpp:138
virtual std::uint64_t errors() const noexcept=0
virtual void order(const OrderRecord &r)=0
virtual void replayed(const ReplayedRecord &)
A venue's execution replay ended complete.
Definition backend.hpp:136
virtual Result< void, std::string > instruments(std::uint64_t session_id, std::span< const Instrument > table)=0
The instrument table of this session, by dense id.
virtual void funding(const FundingRecord &)
A funding payment.
Definition backend.hpp:133
virtual void limits(const LimitsRecord &)
An operator's risk limit change the engine applied. The default drops it.
Definition backend.hpp:142
virtual std::string last_error() const =0
virtual void kill(const KillRecord &r)=0
virtual std::string_view name() const noexcept=0
virtual void context_names(const ContextNamesRecord &)
The names of the strategy's quote context values (FillRecord::order_context).
Definition backend.hpp:149
virtual void capacity(const CapacityRecord &)
A minute of one account's capacity price ([capacity]). The default drops it.
Definition backend.hpp:146
virtual Result< void, std::string > session_open(const SessionOpen &s)=0
virtual void fill(const FillRecord &r)=0
virtual std::uint64_t rows() const noexcept=0
Any thread: fastmm-live reads them for the status file while the store thread writes.
Typed configuration (8.7).
Minimal expected<T, E>: the hot path never throws, it returns Result.
All engine enumerations.
Instrument: the single definition of a tradable contract (5.3 / 5.15).
Definition backend.hpp:40
KillReason
Why a kill switch (global or one venue's) was tripped.
Definition enums.hpp:603
Record stream: the engine's second outbound queue, next to the journal.
A minute of one account's capacity price ([capacity], core/capacity_price.hpp): the actions priced,...
Definition record_stream.hpp:396
The names the strategy gave the values of its quote context (StrategyContext:: quote_context_names),...
Definition record_stream.hpp:419
One execution.
Definition record_stream.hpp:126
A funding payment the engine booked (FundingMsg): amount in the instrument's settlement currency,...
Definition record_stream.hpp:204
Definition config.hpp:487
Definition instrument.hpp:29
A kill switch trip. hdr.flags & kVenue marks a per-venue trip (hdr.venue names it).
Definition record_stream.hpp:218
An operator's limits command the engine applied (ControlCommand::SetLimits or SetUnderlyingLimit): th...
Definition record_stream.hpp:280
The instrument's mid horizon_ms after one of its fills, 0 at the fill ([engine] markout_ms).
Definition record_stream.hpp:383
The OMS record after a transition.
Definition record_stream.hpp:181
A strategy parameter update the engine applied (ParamUpdateMsg): after the header,...
Definition record_stream.hpp:247
One instrument's position and the portfolio totals at the same instant.
Definition record_stream.hpp:188
One order refused: by the pre-trade checks (the engine's) or by its venue (an OrderReject),...
Definition record_stream.hpp:343
A venue's execution replay ended complete (a reconciliation began with ReconcileMsg::kExecutionsExact...
Definition record_stream.hpp:238
What a backend is built with.
Definition backend.hpp:44
const GenericSection * config
Definition backend.hpp:45
std::string default_dir
[engine] journal_dir; where a backend may default its files
Definition backend.hpp:47
bool read_only
opened by a query tool, not by a session
Definition backend.hpp:48
std::string engine_name
[engine] name
Definition backend.hpp:46
Written once, after the last record.
Definition backend.hpp:97
RunnerStats stats
Definition backend.hpp:106
std::uint64_t session_id
Definition backend.hpp:98
std::vector< std::string > journal_paths
every part, in order
Definition backend.hpp:105
int exit_code
Definition backend.hpp:100
KillReason kill_reason
Definition backend.hpp:101
bool journal_complete
the journal was closed cleanly
Definition backend.hpp:103
std::int64_t stopped_ns
Definition backend.hpp:99
std::uint64_t journal_bytes
Definition backend.hpp:104
bool kill_latched
Definition backend.hpp:102
Definition backend.hpp:89
std::string name
Definition backend.hpp:90
std::string params
Definition backend.hpp:91
The strategy's parameter table in schema order: a ParamRecord's field index names an entry.
Definition backend.hpp:71
std::string name
Definition backend.hpp:72
std::uint8_t type
Definition backend.hpp:73
The parameters the session starts with.
Definition backend.hpp:78
std::string text
Definition backend.hpp:80
std::int64_t raw
Definition backend.hpp:81
bool has_raw
Definition backend.hpp:82
std::string name
Definition backend.hpp:79
Written once, before any record.
Definition backend.hpp:52
std::string host
Definition backend.hpp:63
std::string ab_test
[ab]: the test's name and its arms in order (ParamUpdateMsg::arm k + 1 names ab_arms[k]),...
Definition backend.hpp:88
std::vector< ParamField > param_table
Definition backend.hpp:75
std::string journal_path
first journal part; empty when journaling is off
Definition backend.hpp:62
std::uint64_t session_id
Definition backend.hpp:53
std::vector< std::string > venues
[venues.
Definition backend.hpp:67
std::string build_info
compiler, flags, build type
Definition backend.hpp:59
std::vector< ParamValue > params
Definition backend.hpp:84
bool params_complete
Definition backend.hpp:85
std::uint16_t session_epoch
Definition backend.hpp:54
std::uint32_t pid
Definition backend.hpp:64
std::string config_toml
effective configuration, secrets omitted
Definition backend.hpp:61
std::string version
FASTMM_VERSION_STRING.
Definition backend.hpp:58
std::vector< AbArm > ab_arms
Definition backend.hpp:93
std::int64_t pnl_carry_raw
net PnL carried in from earlier sessions
Definition backend.hpp:66
std::int64_t started_ns
Definition backend.hpp:55
std::string strategy
Definition backend.hpp:57
std::uint64_t config_hash
Definition backend.hpp:60
std::string engine_name
Definition backend.hpp:56
bool dry_run
Definition backend.hpp:65