FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
hooks.hpp
Go to the documentation of this file.
1#pragma once
2// Strategy hooks (ADR-0012): the hook table, the compile-time checker and the Fill view.
3//
4// A strategy is a plain class. Its hooks are ordinary public member functions, all optional:
5//
6// on_start(ctx) on_stop(ctx) on_book(ctx, id, book) on_book_ticker(ctx, id, m)
7// on_trade(ctx, id, m) on_option_ticker(ctx, id, m) on_fill(ctx, fill)
8// on_order_update(ctx, u) on_timer(ctx, timer_id, tag) on_connection(ctx, m)
9// on_quoting(ctx, enabled) on_params(ctx) on_balance(ctx, m) on_perp_state(ctx, id, m)
10// on_risk_reject(ctx, r) on_batch_end(ctx) on_instrument_rules(ctx, id, m)
11//
12// The engine checks every hook name when it is instantiated. If the strategy has a member with a
13// hook's name (function, template, data member, static, inherited or private) and the engine's
14// call does not compile, the build stops with one error per hook:
15//
16// fastmm: on_trade has the wrong signature or is not public; expected
17// void on_trade(auto& ctx, InstrumentId id, const TradeMsg& m)
18//
19// A few likely misspellings (on_fills, on_tick, onBook, ...) produce a deprecation warning instead,
20// because a private helper may use such a name; `static constexpr bool
21// fastmm_allow_near_miss_names = true;` in the strategy silences it. Strategy headers can run the
22// same check early with stand-in context and book types:
23//
24// static_assert(fastmm::verify_strategy<MyMM>());
25//
26// Limits:
27// * a `final` class loses the name probe; only the call check remains, so a wrong signature is
28// silently not called;
29// * a hook that is ambiguous across two bases is reported as a wrong signature;
30// * a hook with a deduced (`auto`) return type must not be checked with verify_strategy: the
31// stand-in types instantiate its body;
32// * private hooks are rejected, also when the class befriends the engine;
33// * implicit argument conversions are accepted (on_timer(auto&, TimerId, int) compiles);
34// * near-miss warnings are emitted inside this header, so a build that includes FastMM as a
35// system header does not show them.
36#include "fastmm/core/enums.hpp"
39#include "fastmm/core/oms.hpp"
41#include "fastmm/core/timer_wheel.hpp"
42
43#include <array>
44#include <concepts>
45#include <cstddef>
46#include <cstdint>
47#include <string_view>
48#include <type_traits>
49
50namespace fastmm {
51
52// One execution as a strategy sees it (on_fill). The engine builds it on its stack after the
53// position and fees are updated. The pointers are valid only during the call; do not store them.
54struct Fill {
55 InstrumentId instrument; // the order's instrument, else the fill message's
56 Side side{}; // the order's side, else the fill message's
57 Price price; // this execution
59 Qty position_delta; // signed change of the position; differs from qty when the commission is
60 // charged in the base asset
61 Notional fee; // quote currency, as booked
62 bool fee_converted = true; // false: commission in a third asset, not booked (counted in stats)
64 bool known = false; // the id matched an order, open or recently terminal (`update->order`)
65 bool late = false; // the order was already terminal when the fill arrived
66 bool order_done = false; // the order reached a terminal state with this fill
67 const OmsUpdate* update = nullptr; // non-null when known
68 const OrderFillMsg* msg = nullptr; // always set by the engine
69};
71// A new order or replace the engine's own risk check refused (RiskEngine, [risk]): nothing was
72// sent and no order exists for it. Delivered to on_risk_reject once the hook that asked (or
73// set_quotes from it) has returned, never from inside the call that was refused.
74struct RiskReject {
79 bool replace; // a replace of `order`; else a new order and `order` is invalid
80 std::uint32_t user_tag; // NewOrderRequest::user_tag; a quote's is QuoteManager::make_tag
85};
87// The hook table. X(Enum, name, word, (parameters), (arguments), "expected signature"). The
88// parameters name the engine's call; `Ctx` and `Book` are the engine's context and book types.
89#define FASTMM_STRATEGY_HOOKS(X) \
90 X(Start, on_start, "start", (Ctx & ctx), (ctx), "void on_start(auto& ctx)") \
91 X(Stop, on_stop, "stop", (Ctx & ctx), (ctx), "void on_stop(auto& ctx)") \
92 X(Book, \
93 on_book, \
94 "book", \
95 (Ctx & ctx, InstrumentId id, const Book& book), \
96 (ctx, id, book), \
97 "void on_book(auto& ctx, InstrumentId id, const auto& book)") \
98 X(BookTicker, \
99 on_book_ticker, \
100 "book_ticker", \
101 (Ctx & ctx, InstrumentId id, const BookTickerMsg& m), \
102 (ctx, id, m), \
103 "void on_book_ticker(auto& ctx, InstrumentId id, const BookTickerMsg& m)") \
104 X(Trade, \
105 on_trade, \
106 "trade", \
107 (Ctx & ctx, InstrumentId id, const TradeMsg& m), \
108 (ctx, id, m), \
109 "void on_trade(auto& ctx, InstrumentId id, const TradeMsg& m)") \
110 X(OptionTicker, \
111 on_option_ticker, \
112 "option_ticker", \
113 (Ctx & ctx, InstrumentId id, const OptionTickerMsg& m), \
114 (ctx, id, m), \
115 "void on_option_ticker(auto& ctx, InstrumentId id, const OptionTickerMsg& m)") \
116 X(Fill, \
117 on_fill, \
118 "fill", \
119 (Ctx & ctx, const Fill& fill), \
120 (ctx, fill), \
121 "void on_fill(auto& ctx, const Fill& fill)") \
122 X(OrderUpdate, \
123 on_order_update, \
124 "order_update", \
125 (Ctx & ctx, const OmsUpdate& u), \
126 (ctx, u), \
127 "void on_order_update(auto& ctx, const OmsUpdate& u)") \
128 X(Timer, \
129 on_timer, \
130 "timer", \
131 (Ctx & ctx, TimerId id, std::uint64_t tag), \
132 (ctx, id, tag), \
133 "void on_timer(auto& ctx, TimerId id, std::uint64_t tag)") \
134 X(Connection, \
135 on_connection, \
136 "connection", \
137 (Ctx & ctx, const ConnectionStateMsg& m), \
138 (ctx, m), \
139 "void on_connection(auto& ctx, const ConnectionStateMsg& m)") \
140 X(Quoting, \
141 on_quoting, \
142 "quoting", \
143 (Ctx & ctx, bool enabled), \
144 (ctx, enabled), \
145 "void on_quoting(auto& ctx, bool enabled)") \
146 X(Params, on_params, "params", (Ctx & ctx), (ctx), "void on_params(auto& ctx)") \
147 X(Balance, \
148 on_balance, \
149 "balance", \
150 (Ctx & ctx, const BalanceMsg& m), \
151 (ctx, m), \
152 "void on_balance(auto& ctx, const BalanceMsg& m)") \
153 X(PerpState, \
154 on_perp_state, \
155 "perp_state", \
156 (Ctx & ctx, InstrumentId id, const PerpStateMsg& m), \
157 (ctx, id, m), \
158 "void on_perp_state(auto& ctx, InstrumentId id, const PerpStateMsg& m)") \
159 X(RiskReject, \
160 on_risk_reject, \
161 "risk_reject", \
162 (Ctx & ctx, const RiskReject& r), \
163 (ctx, r), \
164 "void on_risk_reject(auto& ctx, const RiskReject& r)") \
165 X(BatchEnd, on_batch_end, "batch_end", (Ctx & ctx), (ctx), "void on_batch_end(auto& ctx)") \
166 X(InstrumentRules, \
167 on_instrument_rules, \
168 "instrument_rules", \
169 (Ctx & ctx, InstrumentId id, const InstrumentRulesMsg& m), \
170 (ctx, id, m), \
171 "void on_instrument_rules(auto& ctx, InstrumentId id, const InstrumentRulesMsg& m)")
172
173// Optional state the engine keeps across sessions ([strategy] state_file): `std::string_view
174// state()` returns the bytes to save (valid until the strategy's next hook; the engine copies them
175// at once) and `bool restore(std::string_view)` takes the bytes saved before, false when they are
176// not this strategy's (it then starts fresh). The engine calls restore once, after on_start and
177// before the first event (and again at a warm standby's take-over, or a backtest's start_at), and
178// state() every state_interval_s, at the end, at every [engine] checkpoint_s for the journal, and
179// never from inside another hook. The bytes are the strategy's own format. With a journal, the
180// bytes handed to restore() and the checkpoints are journaled (StrategyStateMsg), so a replay
181// restores them too and a backtest can start from any checkpoint.
182template <class S>
183concept KeepsState = requires(S& s, std::string_view bytes) {
184 { s.state() } -> std::convertible_to<std::string_view>;
185 { s.restore(bytes) } -> std::same_as<bool>;
186};
187
188// The layout of the bytes state() returns: `static constexpr std::uint32_t state_version`, or a
189// `state_version()` member function; 0 when the strategy declares none. The state file and every
190// checkpoint record it, and a backtest, a replay or a live session refuses bytes of another
191// version.
192template <class S>
193[[nodiscard]] constexpr std::uint32_t state_version_of(S& s) noexcept {
194 if constexpr (requires {
195 { s.state_version() } -> std::convertible_to<std::uint32_t>;
196 }) {
197 return static_cast<std::uint32_t>(s.state_version());
198 } else if constexpr (requires {
199 { S::state_version } -> std::convertible_to<std::uint32_t>;
200 }) {
201 return static_cast<std::uint32_t>(S::state_version);
202 } else {
203 return 0;
204 }
205}
206
207// Y(misspelling, hook): names that produce a "did you mean" warning.
208#define FASTMM_STRATEGY_HOOK_NEAR_MISSES(Y) \
209 Y(on_fills, on_fill) \
210 Y(on_reject, on_risk_reject) \
211 Y(on_risk_rejected, on_risk_reject) \
212 Y(on_execution, on_fill) \
213 Y(on_trades, on_trade) \
214 Y(on_order_book, on_book) \
215 Y(on_orderbook, on_book) \
216 Y(on_book_update, on_book) \
217 Y(on_depth, on_book) \
218 Y(on_tick, on_book) \
219 Y(on_bbo, on_book_ticker) \
220 Y(on_ticker, on_book_ticker) \
221 Y(on_options_ticker, on_option_ticker) \
222 Y(on_order, on_order_update) \
223 Y(on_order_event, on_order_update) \
224 Y(on_timer_fired, on_timer) \
225 Y(on_connection_state, on_connection) \
226 Y(on_disconnect, on_connection) \
227 Y(on_init, on_start) \
228 Y(on_shutdown, on_stop) \
229 Y(on_quote, on_quoting) \
230 Y(on_param, on_params) \
231 Y(on_parameters, on_params) \
232 Y(on_balances, on_balance) \
233 Y(on_perp, on_perp_state) \
234 Y(on_funding, on_perp_state) \
235 Y(on_mark, on_perp_state) \
236 Y(onBook, on_book) \
237 Y(OnBook, on_book) \
238 Y(onTrade, on_trade) \
239 Y(onFill, on_fill)
240
241enum class Hook : std::uint8_t {
242#define FASTMM_HOOK_ENUM(E, name, word, params, args, sig) E,
244#undef FASTMM_HOOK_ENUM
245 Count
246};
247
248// Absent: no member with the hook's name. Ok: the engine calls it. Mismatch: a member with the
249// name exists but the call does not compile (a build error through verify_strategy).
250enum class HookStatus : std::uint8_t { Absent, Ok, Mismatch };
251
252struct HookInfo {
253 Hook hook;
254 std::string_view name; // "on_trade"
255 std::string_view word; // "trade" (start-up log)
256 std::string_view signature; // "void on_trade(auto& ctx, InstrumentId id, const TradeMsg& m)"
259inline constexpr std::array<HookInfo, static_cast<std::size_t>(Hook::Count)> kHooks{{
260#define FASTMM_HOOK_INFO(E, name, word, params, args, sig) {Hook::E, #name, word, sig},
262#undef FASTMM_HOOK_INFO
263}};
264
265namespace detail::hooks {
266
267#define FASTMM_HOOK_UNPAREN(...) __VA_ARGS__
268
269// Name probe: lookup of `name` in name_probe<S> is ambiguous exactly when S has any member called
270// `name` (function, template, data, static, inherited, private); an ambiguous lookup is a
271// substitution failure, so the requires-expression is false. The conjunction keeps final and
272// non-class types away from the derivation.
273template <class S>
274concept probeable = std::is_class_v<S> && !std::is_final_v<S>;
275
276#define FASTMM_HOOK_PROBE(name) \
277 struct probe_##name { \
278 void name(); \
279 }; \
280 template <class S> \
281 struct name_probe_##name : S, probe_##name {}; \
282 template <class S> \
283 concept declares_##name = probeable<S> && (!requires { &name_probe_##name<S>::name; });
284
285#define FASTMM_HOOK_CALL(E, name, word, params, args, sig) \
286 FASTMM_HOOK_PROBE(name) \
287 template <class S, class Ctx, class Book> \
288 concept calls_##name = requires(S& s, FASTMM_HOOK_UNPAREN params) { \
289 { s.name args } -> std::same_as<void>; \
290 };
292#undef FASTMM_HOOK_CALL
293
294#define FASTMM_HOOK_NEAR_MISS(name, hook) \
295 FASTMM_HOOK_PROBE(name) \
296 template <bool Found> \
297 struct near_miss_##name { \
298 static constexpr bool value = false; \
299 }; \
300 template <> \
301 struct near_miss_##name<true> { \
302 [[deprecated("fastmm: " #name " is not a hook; did you mean " #hook "?")]] \
303 static constexpr bool value = true; \
304 };
306#undef FASTMM_HOOK_NEAR_MISS
307#undef FASTMM_HOOK_PROBE
308
309template <class S>
310concept allows_near_miss_names = requires { requires S::fastmm_allow_near_miss_names; };
311
312// Stand-ins for verify_strategy<S>() in a strategy header, where the engine types are unknown.
313struct StandInContext {};
314struct StandInBook {};
315
316} // namespace detail::hooks
317
318template <class S, class Ctx, class Book>
319[[nodiscard]] constexpr HookStatus hook_status(Hook h) noexcept {
320 switch (h) {
321#define FASTMM_HOOK_STATUS(E, name, word, params, args, sig) \
322 case Hook::E: \
323 if (detail::hooks::calls_##name<S, Ctx, Book>) return HookStatus::Ok; \
324 return detail::hooks::declares_##name<S> ? HookStatus::Mismatch : HookStatus::Absent;
326#undef FASTMM_HOOK_STATUS
327 case Hook::Count:
328 break;
329 }
330 return HookStatus::Absent;
331}
332
333// True when the engine calls S's hook `h` (the engine dispatches on this at compile time).
334template <class S, class Ctx, class Book>
335[[nodiscard]] constexpr bool implements_hook(Hook h) noexcept {
336 return hook_status<S, Ctx, Book>(h) == HookStatus::Ok;
338
339// Compile-time check of every hook of S; always returns true (failures are static_asserts), so it
340// can be written as `static_assert(fastmm::verify_strategy<MyMM>());`.
341template <class S,
342 class Ctx = detail::hooks::StandInContext,
343 class Book = detail::hooks::StandInBook>
344[[nodiscard]] constexpr bool verify_strategy() noexcept {
345 // The local names make clang's "due to requirement '...'" line readable.
346#define FASTMM_HOOK_ASSERT(E, name, word, params, args, sig) \
347 const bool name##_declared = detail::hooks::declares_##name<S>; \
348 const bool name##_signature_matches = detail::hooks::calls_##name<S, Ctx, Book>; \
349 static_assert(!name##_declared || name##_signature_matches, \
350 "fastmm: " #name " has the wrong signature or is not public; expected " sig);
352#undef FASTMM_HOOK_ASSERT
353 const bool near_miss_names_allowed = detail::hooks::allows_near_miss_names<S>;
354#define FASTMM_HOOK_WARN(name, hook) \
355 static_cast<void>(detail::hooks::near_miss_##name < !near_miss_names_allowed && \
356 detail::hooks::declares_##name < S >> ::value);
358#undef FASTMM_HOOK_WARN
359 constexpr bool has_state = requires(S& s) { s.state(); };
360 constexpr bool has_restore = requires(S& s, std::string_view b) { s.restore(b); };
361 static_assert(has_state == has_restore,
362 "fastmm: state() and restore() go together; expected std::string_view state() and "
363 "bool restore(std::string_view)");
364 static_assert(!has_state || KeepsState<S>,
365 "fastmm: expected std::string_view state() and bool restore(std::string_view)");
366 return true;
367}
368
369namespace detail::hooks {
370struct HookSetText {
371 std::array<char, 160> chars{};
372 std::size_t size = 0;
373};
374template <class S, class Ctx, class Book>
375inline constexpr HookSetText hook_set_text = [] {
376 HookSetText t;
377 for (const HookInfo& h : kHooks) {
378 if (!implements_hook<S, Ctx, Book>(h.hook)) continue;
379 if (t.size != 0) t.chars[t.size++] = ' ';
380 for (const char c : h.word) t.chars[t.size++] = c;
381 }
382 return t;
383}();
384} // namespace detail::hooks
385
386// The implemented hooks as words in table order ("start book fill timer connection quoting").
387template <class S, class Ctx, class Book>
388[[nodiscard]] constexpr std::string_view implemented_hooks() noexcept {
389 const detail::hooks::HookSetText& t = detail::hooks::hook_set_text<S, Ctx, Book>;
390 return std::string_view(t.chars.data(), t.size);
391}
392
393} // namespace fastmm
All engine enumerations.
Fixed<Tag>: int64 fixed point with a global 1e-8 scale (ADR-0001).
#define FASTMM_HOOK_STATUS(E, name, word, params, args, sig)
#define FASTMM_STRATEGY_HOOK_NEAR_MISSES(Y)
Y(misspelling, hook): names that produce a "did you mean" warning.
Definition hooks.hpp:210
#define FASTMM_HOOK_ASSERT(E, name, word, params, args, sig)
#define FASTMM_HOOK_NEAR_MISS(name, hook)
#define FASTMM_HOOK_WARN(name, hook)
#define FASTMM_HOOK_CALL(E, name, word, params, args, sig)
Definition hooks.hpp:287
#define FASTMM_HOOK_INFO(E, name, word, params, args, sig)
Event bus message structs (5.5).
Definition strategy.hpp:23
OrderType
Definition enums.hpp:23
constexpr bool implements_hook(Hook h) noexcept
True when the engine calls S's hook h (the engine dispatches on this at compile time).
Definition hooks.hpp:337
RejectReason
Ordered exactly like RiskEngine::check_new evaluates them (5.7), followed by OMS / transport / venue ...
Definition enums.hpp:123
Side
Definition enums.hpp:12
HookStatus
Absent: no member with the hook's name.
Definition hooks.hpp:252
StrongId< struct InstrumentTag, std::uint32_t > InstrumentId
Dense index into the engine's instrument table.
Definition strong_id.hpp:38
constexpr HookStatus hook_status(Hook h) noexcept
Definition hooks.hpp:321
Liquidity
Definition enums.hpp:483
constexpr std::string_view implemented_hooks() noexcept
The implemented hooks as words in table order ("start book fill timer connection quoting").
Definition hooks.hpp:390
constexpr std::array< HookInfo, static_cast< std::size_t >(Hook::Count)> kHooks
Definition hooks.hpp:261
Hook
Definition hooks.hpp:243
FASTMM_HOOK_ENUM(E, name, word, params, args, sig)
constexpr bool verify_strategy() noexcept
Compile-time check of every hook of S; always returns true (failures are static_asserts),...
Definition hooks.hpp:346
constexpr std::uint32_t state_version_of(S &s) noexcept
The layout of the bytes state() returns: static constexpr std::uint32_t state_version,...
Definition hooks.hpp:195
Order management (5.8): a Pool<Order> + OpenHashMap<ClientOrderId, Handle> + a ring of recently termi...
Strongly typed identifiers.
InstrumentId instrument
the order's instrument, else the fill message's
Definition hooks.hpp:57
Side side
the order's side, else the fill message's
Definition hooks.hpp:58
Liquidity liquidity
Definition hooks.hpp:65
Qty position_delta
signed change of the position; differs from qty when the commission is charged in the base asset
Definition hooks.hpp:61
Qty qty
Definition hooks.hpp:60
bool known
the id matched an order, open or recently terminal (update->order)
Definition hooks.hpp:66
bool late
the order was already terminal when the fill arrived
Definition hooks.hpp:67
Notional fee
quote currency, as booked
Definition hooks.hpp:63
const OmsUpdate * update
non-null when known
Definition hooks.hpp:69
const OrderFillMsg * msg
always set by the engine
Definition hooks.hpp:70
Price price
this execution
Definition hooks.hpp:59
bool fee_converted
false: commission in a third asset, not booked (counted in stats)
Definition hooks.hpp:64
bool order_done
the order reached a terminal state with this fill
Definition hooks.hpp:68
Definition hooks.hpp:254
Hook hook
Definition hooks.hpp:255
std::string_view name
"on_trade"
Definition hooks.hpp:256
std::string_view signature
"void on_trade(auto\& ctx, InstrumentId id, const TradeMsg\& m)"
Definition hooks.hpp:258
std::string_view word
"trade" (start-up log)
Definition hooks.hpp:257
Definition oms.hpp:83
Definition messages.hpp:312
A new order or replace the engine's own risk check refused (RiskEngine, [risk]): nothing was sent and...
Definition hooks.hpp:76
Side side
Definition hooks.hpp:78
Timestamp time
Definition hooks.hpp:86
ClientOrderId order
Definition hooks.hpp:85
RejectReason reason
Definition hooks.hpp:80
Qty qty
Definition hooks.hpp:84
std::uint32_t user_tag
NewOrderRequest::user_tag; a quote's is QuoteManager::make_tag.
Definition hooks.hpp:82
OrderType type
Definition hooks.hpp:79
bool replace
a replace of order; else a new order and order is invalid
Definition hooks.hpp:81
Price price
Definition hooks.hpp:83
InstrumentId instrument
Definition hooks.hpp:77
Definition time.hpp:45