FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
session.hpp
Go to the documentation of this file.
1#pragma once
2// run_live(): wires venues, rings, the engine and the journal into the plan 5.1 thread model and
3// runs a session (fastmm::live, src/live/session.cpp). fastmm::cli::live (cli/live.hpp) is the
4// command line around it.
5//
6// fm-net-<i> one per venue: net::Reactor loop (connections, parsing into the venue's md and
7// order rings, draining the venue's outbound ring when the engine wakes it)
8// fm-engine Engine<S, TscClock, LiveTransport, RingFeed>::run() (pinned / spin mode from
9// [engine] cpu / spin_mode)
10// fm-journal JournalFileWriter drain thread (when journaling)
11// log sink Logger::start(): formats and writes log records from every thread's ring
12// main thread control: waits on the control socket and a signal eventfd (50 ms at most),
13// posts Venue::on_timer every second, prints stats, recalibrates the
14// TSC every [engine] tsc_recalibrate_s and publishes it (the engine and the
15// venues pick it up), handles SIGINT/SIGTERM and --duration: kill switch ->
16// cancel_all on every venue over an independent REST connection -> stop, all
17// within ~5 s. It also watches the engine's kill switch: a kill the engine trips
18// itself (risk limit, full ring, every venue killed) runs the same shutdown and
19// exits with kExitKilled when [engine] on_kill = "exit" (the default); with "stay"
20// the session keeps running and logs an ERROR line every 10 s. Venue kills are
21// logged once per venue. An engine whose heartbeat stands still for [engine]
22// stall_ms is given up: cancel_all on every venue, then the process exits
23// (kExitRuntime) without it.
24//
25// [engine] threading = "single" (one venue): no fm-net-0; fm-engine runs the venue's reactor
26// iteration between engine steps (Engine::run_inline), takes each market-data event as the venue
27// commits it (EventSink drain hook -> Engine::drain) and hands its orders to Venue::send_now.
28//
29// The thread set is fixed for the whole session (the logger keeps a ring per thread). The strategy
30// is built by the StrategyRegistry's TransportKind::Live factory for [strategy] name; register it
31// (register_builtin_strategies, a strategy module) before calling run_live, or pass a
32// LiveStrategy (fastmm_live._live runs Python hot strategies that way). run_live installs
33// process-wide SIGINT/SIGTERM handlers and restores the previous ones when it returns.
37
38#include <cstdint>
39#include <functional>
40#include <memory>
41#include <string>
42#include <utility>
43#include <vector>
44
45namespace fastmm {
46class IEngineRunner;
47class MsgRing;
48class ParamSchema;
49struct RunnerDeps;
50} // namespace fastmm
51
52namespace fastmm::live {
53
54// A strategy the caller builds instead of the registry's [strategy] name.
55struct LiveStrategy {
56 std::string name; // journal header, status file and log lines
57 const ParamSchema* params = nullptr; // the journal's parameter table
58 std::string meta; // the journal's strategy metadata (`key=value` lines)
59 // Rings the engine polls besides the venues' (parameter updates); the caller keeps them alive.
60 std::vector<MsgRing*> inputs;
61 // Called with a function that wakes the engine, before the session's threads start, and with an
62 // empty one before the session returns. With spin_mode = "adaptive" an idle engine blocks; a
63 // producer on `inputs` calls the function after each push, or its message waits up to 1 ms.
64 std::function<void(std::function<void()> wake)> set_waker;
65 // Builds the runner on `deps` (deps.backend is a LiveBackend) on the calling thread, after the
66 // venues' reference data has loaded and before any session thread starts. An exception or
67 // nullptr gives kExitConfig.
68 std::function<std::unique_ptr<IEngineRunner>(RunnerDeps& deps)> make;
69 // Called after the engine thread has stopped, before the runner is destroyed.
70 std::function<void(IEngineRunner& runner)> finished;
71 // The control socket's `param`: validates the (name, value) pairs against this strategy's schema
72 // and publishes them onto one of `inputs` (the caller owns the publisher, so its copy of the
73 // parameters stays the only one). Returns the error message, empty on success. Unset: the
74 // session answers `param` with an error.
75 std::function<std::string(const std::vector<std::pair<std::string, std::string>>&, InstrumentId)>
77 // A publisher of the strategy's parameters onto `sink`, its copy starting from the values the
78 // session starts with: [strategy.overrides], [ab] and the control socket's `param` go through
79 // it, and set_params is not used. Unset: none.
80 std::function<std::unique_ptr<ParamPublisher>(ParamSink sink)> publisher;
81};
83struct LiveOptions {
84 std::string config_path;
85 std::int64_t duration_ns = 0; // 0 = until SIGINT/SIGTERM
86 bool dry_run = false;
87 std::string record_raw_dir;
88 std::string journal_path; // overrides [engine] journal_dir
89 bool no_journal = false;
90 std::string status_path; // overrides the default /dev/shm/fastmm-<engine>.status
91 bool no_status = false;
92 // Control socket (live/control_socket.hpp); empty takes <journal_dir>/<engine name>.ctl.
93 std::string control_path;
94 bool no_control = false;
95 // Removes the durable kill state before starting: clears a latched max-loss trip and arms the
96 // whole [risk] max_loss budget again ([engine] kill_file).
97 bool clear_kill = false;
98 // Trade from the store's position even though its newest session booked executions more than
99 // once (live/restart_check.hpp); without it such a start exits with kExitState.
100 bool accept_position = false;
101 // Waits for the instance lock (live/instance_lock.hpp) instead of refusing to start while another
102 // process holds it; [engine] instance_lock is implied. Warm when every trading venue can hold its
103 // private channels back (Venue::defer_private) and replays its executions before quoting, the
104 // session is split-threaded and not attached to a gateway: market data, books and the strategy
105 // run, orders are refused until the first reconciliation, and the kill file, the strategy state,
106 // the store, the status file, the control socket and the private channels wait for the lock.
107 // Otherwise cold: the reference data and account fees are loaded (attached: nothing), and
108 // everything else waits for the lock.
109 bool standby = false;
110 // standby, and once ready send `handoff` to the control socket of the session holding the lock;
111 // give up after [engine] handoff_timeout_ms without the lock (kExitLocked).
112 bool takeover = false;
113 std::string program = "fastmm-live"; // prefix of error messages (log lines keep fastmm-live:)
114 const LiveStrategy* strategy = nullptr; // nullptr: [strategy] name from the registry
115 // Called by the control thread every 50 ms; must not block. A non-empty result stops the session
116 // like SIGTERM (kill switch, cancel_all) with kExitSlowTier and is logged as the cause.
117 std::function<std::string()> watchdog;
118 // Attach to the fastmm-gateway listening here instead of connecting to the venues
119 // (live/gateway.hpp): its instrument table, its rings, no venue keys in this process, and no
120 // cancel_all on shutdown (the gateway cancels when the attachment closes).
121 std::string gateway_path;
122};
124// Process exit codes (listed in fastmm-live --help and docs/how-to/operations/). A failed
125// cancel-all wins over every other outcome: orders may still be resting.
126inline constexpr int kExitOk = 0; // --duration elapsed or SIGINT/SIGTERM, cancel_all ok
127inline constexpr int kExitUsage = 2; // bad command line, missing API keys
128inline constexpr int kExitConfig = 3; // bad config, strategy or parameters
129inline constexpr int kExitVenue = 4; // venue reference data failed
130inline constexpr int kExitRuntime = 5; // cancel_all failed, journal, ring overflow, stalled engine
131inline constexpr int kExitKilled = 6; // engine-tripped kill switch with [engine] on_kill = "exit"
132inline constexpr int kExitSlowTier = 7; // LiveOptions::watchdog (a Python slow tier failed)
133// Another process holds the instance lock, or a takeover failed; nothing was traded.
134inline constexpr int kExitLocked = 8;
135// The state a restart carries over is gone or known to be wrong (live/restart_check.hpp): the epoch
136// file is missing while the store holds sessions, or the store's newest session booked executions
137// twice on a venue that does not report its own position. Nothing was traded.
138inline constexpr int kExitState = 9;
139
140// How often a session that stays up after a kill ([engine] on_kill = "stay") repeats its ERROR.
141inline constexpr std::int64_t kKilledReminderNs = 10'000'000'000;
142
143// Runs one session; returns the process exit code. `cfg` must already have its venue secrets
144// resolved (or cleared for dry-run) and any command-line overrides applied: the journal embeds
145// cfg.effective_toml() and hashes it.
146int run_live(const Config& cfg, const LiveOptions& opts);
147
148// Resolves ${VAR} in every venue string. With `dry_run`, an unset variable in api_key or api_secret
149// clears the key; anything else unset, or a venue without keys outside a dry run, prints an error
150// prefixed with `prog` to stderr and returns false (kExitUsage).
151bool resolve_venue_env(Config& cfg, bool dry_run, const char* prog);
152
153// A venue of `cfg` trades with real keys: it is not public_only and has an api_key (an OUCH login
154// on a venue that takes no API key). Read after resolve_venue_env, which clears them in a dry run.
155[[nodiscard]] bool trades_with_keys(const Config& cfg);
156
157// Restores the SIGINT/SIGTERM handlers run_live replaced; a no-op when none are replaced. For a
158// child forked during a session, whose control thread does not exist.
159void restore_signal_handlers() noexcept;
160
161} // namespace fastmm::live
Definition config.hpp:502
Definition params.hpp:102
Typed configuration (8.7).
Definition session.hpp:54
constexpr int kExitKilled
engine-tripped kill switch with [engine] on_kill = "exit"
Definition session.hpp:133
constexpr int kExitSlowTier
LiveOptions::watchdog (a Python slow tier failed)
Definition session.hpp:134
constexpr int kExitVenue
venue reference data failed
Definition session.hpp:131
constexpr int kExitUsage
bad command line, missing API keys
Definition session.hpp:129
bool trades_with_keys(const Config &cfg)
A venue of cfg trades with real keys: it is not public_only and has an api_key (an OUCH login on a ve...
constexpr int kExitRuntime
cancel_all failed, journal, ring overflow, stalled engine
Definition session.hpp:132
constexpr int kExitState
The state a restart carries over is gone or known to be wrong (live/restart_check....
Definition session.hpp:140
constexpr std::int64_t kKilledReminderNs
How often a session that stays up after a kill ([engine] on_kill = "stay") repeats its ERROR.
Definition session.hpp:143
bool resolve_venue_env(Config &cfg, bool dry_run, const char *prog)
Resolves ${VAR} in every venue string.
constexpr int kExitLocked
Another process holds the instance lock, or a takeover failed; nothing was traded.
Definition session.hpp:136
constexpr int kExitOk
Process exit codes (listed in fastmm-live --help and docs/how-to/operations/).
Definition session.hpp:128
void restore_signal_handlers() noexcept
Restores the SIGINT/SIGTERM handlers run_live replaced; a no-op when none are replaced.
int run_live(const Config &cfg, const LiveOptions &opts)
Runs one session; returns the process exit code.
constexpr int kExitConfig
bad config, strategy or parameters
Definition session.hpp:130
Definition strategy.hpp:23
ParamPublisher: builds ParamUpdate messages for a running engine, off the engine thread (ADR-0013).
Strongly typed identifiers.
Where a built update goes; push returns false when it was not accepted (full).
Definition param_publisher.hpp:49
Everything a factory needs that is backend-independent.
Definition registry.hpp:51
Definition session.hpp:85
std::function< std::string()> watchdog
Called by the control thread every 50 ms; must not block.
Definition session.hpp:119
bool no_control
Definition session.hpp:96
std::string journal_path
overrides [engine] journal_dir
Definition session.hpp:90
bool no_status
Definition session.hpp:93
bool standby
Waits for the instance lock (live/instance_lock.hpp) instead of refusing to start while another proce...
Definition session.hpp:111
std::string config_path
Definition session.hpp:86
std::string program
prefix of error messages (log lines keep fastmm-live:)
Definition session.hpp:115
std::string gateway_path
Attach to the fastmm-gateway listening here instead of connecting to the venues (live/gateway....
Definition session.hpp:123
bool no_journal
Definition session.hpp:91
std::string control_path
Control socket (live/control_socket.hpp); empty takes <journal_dir>/<engine name>....
Definition session.hpp:95
bool accept_position
Trade from the store's position even though its newest session booked executions more than once (live...
Definition session.hpp:102
std::string record_raw_dir
Definition session.hpp:89
bool dry_run
Definition session.hpp:88
const LiveStrategy * strategy
nullptr: [strategy] name from the registry
Definition session.hpp:116
bool takeover
standby, and once ready send handoff to the control socket of the session holding the lock; give up a...
Definition session.hpp:114
std::string status_path
overrides the default /dev/shm/fastmm-<engine>.status
Definition session.hpp:92
bool clear_kill
Removes the durable kill state before starting: clears a latched max-loss trip and arms the whole [ri...
Definition session.hpp:99
std::int64_t duration_ns
0 = until SIGINT/SIGTERM
Definition session.hpp:87
A strategy the caller builds instead of the registry's [strategy] name.
Definition session.hpp:57
std::string meta
the journal's strategy metadata (key=value lines)
Definition session.hpp:60
std::string name
journal header, status file and log lines
Definition session.hpp:58
std::function< std::string(const std::vector< std::pair< std::string, std::string > > &, InstrumentId)> set_params
The control socket's param: validates the (name, value) pairs against this strategy's schema and publ...
Definition session.hpp:78
std::function< std::unique_ptr< IEngineRunner >(RunnerDeps &deps)> make
Builds the runner on deps (deps.backend is a LiveBackend) on the calling thread, after the venues' re...
Definition session.hpp:70
const ParamSchema * params
the journal's parameter table
Definition session.hpp:59
std::function< void(std::function< void()> wake)> set_waker
Called with a function that wakes the engine, before the session's threads start, and with an empty o...
Definition session.hpp:66
std::function< void(IEngineRunner &runner)> finished
Called after the engine thread has stopped, before the runner is destroyed.
Definition session.hpp:72
std::vector< MsgRing * > inputs
Rings the engine polls besides the venues' (parameter updates); the caller keeps them alive.
Definition session.hpp:62
std::function< std::unique_ptr< ParamPublisher >(ParamSink sink)> publisher
A publisher of the strategy's parameters onto sink, its copy starting from the values the session sta...
Definition session.hpp:82