FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
strategy_context.hpp
Go to the documentation of this file.
1#pragma once
2// StrategyContext: the API a strategy sees (ADR-0012, section 2). A thin, non-owning facade over
3// the Engine, so strategies never include engine.hpp and cannot reach into internals. Every
4// order-API call marks the strategy's decision time for the serialize latency interval.
5#include "fastmm/core/account_pool.hpp"
6#include "fastmm/core/balance_book.hpp"
9#include "fastmm/core/config_macros.hpp"
10#include "fastmm/core/enums.hpp"
11#include "fastmm/core/fees.hpp"
12#include "fastmm/core/fill_cluster.hpp"
14#include "fastmm/core/hazard.hpp"
16#include "fastmm/core/oms.hpp"
17#include "fastmm/core/order.hpp"
18#include "fastmm/core/order_budget.hpp"
19#include "fastmm/core/perp_book.hpp"
20#include "fastmm/core/pool_homes.hpp"
25#include "fastmm/core/rng.hpp"
27#include "fastmm/core/time.hpp"
29
30#include <cstdint>
31#include <initializer_list>
32#include <optional>
33#include <span>
34#include <string_view>
35
36namespace fastmm {
37
38template <class Engine>
39class StrategyContext {
40 public:
41 using Book = typename Engine::Book;
42
43 explicit StrategyContext(Engine* e) noexcept : e_(e) {}
44
45 // ---- time and reference data --------------------------------------------------------------
46
47 [[nodiscard]] Timestamp now() const noexcept { return e_->now(); }
48 [[nodiscard]] const Instrument& instrument(InstrumentId id) const noexcept {
49 return e_->instrument(id);
50 }
51 [[nodiscard]] const InstrumentTable& instruments() const noexcept { return e_->instruments(); }
52 [[nodiscard]] bool contains(InstrumentId id) const noexcept {
53 return e_->instruments().contains(id);
54 }
55
56 // ---- market data --------------------------------------------------------------------------
57
58 [[nodiscard]] const Book& book(InstrumentId id) const noexcept { return e_->book(id); }
59
60 // Our resting quantity that the venue's feed shows at (id, side, px): the book and the tickers of
61 // a live venue include our own orders. As of the book's last update, or of venue time `at` (a
62 // BookTicker's exch_ts). An order counts from its ack's venue time to its end's, less its fills,
63 // so a depth update stamped before our cancel still includes it. Zero in the simulator, whose
64 // feed does not contain our orders.
65 [[nodiscard]] Qty own_qty(InstrumentId id, Side side, Price px) const noexcept {
66 return e_->own_qty(id, side, px);
67 }
68 [[nodiscard]] Qty own_qty(InstrumentId id, Side side, Price px, Timestamp at) const noexcept {
69 return e_->own_qty(id, side, px, at);
70 }
71 // The book's best level on one side with own_qty taken out; a level that was only ours is
72 // skipped. Level{} when none is left.
73 [[nodiscard]] Level best_ex_self(InstrumentId id, Side side) const noexcept {
74 return e_->best_ex_self(id, side);
75 }
76
77 // ---- portfolio ----------------------------------------------------------------------------
79 [[nodiscard]] const Position& position(InstrumentId id) const noexcept {
80 return e_->position(id);
81 }
82 // PnL totals over every instrument (a loop over all positions; not for every event).
83 [[nodiscard]] Portfolio portfolio() const noexcept { return e_->positions().portfolio(); }
84
85 // ---- quoting: the QuoteManager diffs the desired ladder against working orders --------------
86
87 // Returns false when the quotes were ignored: quoting is disabled (control pull, kill switch,
88 // reconciliation; on_quoting reports the changes) or the instrument is not in the table.
89 bool set_quotes(InstrumentId id, const DesiredQuotes& q) noexcept {
90 e_->mark_decision();
91 return e_->set_quotes(id, q);
92 }
93 void pull_quotes(InstrumentId id) noexcept {
94 e_->mark_decision();
95 e_->pull_quotes(id);
96 }
97
98 // ---- what the strategy watches
99 // ----------------------------------------------------------------- The engine calls the
100 // market-data hooks only for what the strategy watches, and needs no more: a multiverse hands an
101 // engine only the messages it needs (backtest/multiverse.hpp). Alone or there, a backtest gives
102 // the same result; declaring less only makes a sweep faster.
103 //
104 // watch(id, false): on_book, on_book_ticker, on_trade and on_option_ticker are not called for
105 // `id` until watch(id, true); ctx.book(id) stays current. Every instrument is watched at start.
106 void watch(InstrumentId id, bool on) noexcept { e_->watch(id, on); }
107 // on_book of `id` is called only once its mid is at or beyond `lo` or `hi`, or the book is not
108 // valid: a strategy that would return at once inside (lo, hi) says so. quiet_book(id): every
109 // update again.
110 void quiet_book(InstrumentId id, Price lo, Price hi) noexcept { e_->quiet_book(id, lo, hi); }
111 void quiet_book(InstrumentId id) noexcept { e_->quiet_book(id); }
112 // Why the strategy asks what it asks on a side, for the operator: a short reason
113 // ("inventory_cap", "model_off"; empty clears it, at most 23 bytes kept) and the budget it gave
114 // the side in the settlement currency. The status file shows it next to what the engine finds
115 // in the way (core/quote_diag.hpp); the store records each change. No allocation.
116 void note_quote(InstrumentId id,
117 Side side,
118 std::string_view reason,
119 Notional budget = {}) noexcept {
120 e_->note_quote(id, side, reason, budget);
121 }
122 // A number the strategy publishes by name, for the status file (a budget split, a model's
123 // state): the first 32 names are kept, a name at most 23 bytes. No allocation.
124 void metric(std::string_view name, double value) noexcept { e_->metric(name, value); }
125 // What the strategy knows about its quotes on a side, for the record of their fills: up to
126 // kQuoteContextSize numbers (its fair value, the quote's distance from it, a signal), NaN for a
127 // slot not given. The side keeps them until the next call. Each order sent or moved on the side
128 // takes a copy, and the store keeps, with every fill, the copy its order took when it last went
129 // out and the side's values when the fill arrived (fastmm-pnl fill-context). Call it before
130 // set_quotes or send for the orders it explains. No allocation.
131 //
132 // ctx.quote_context(id, Side::Buy, {fair.to_double(), bid_distance_bps});
133 void quote_context(InstrumentId id, Side side, std::initializer_list<double> values) noexcept {
134 e_->quote_context(id, side, std::span<const double>(values.begin(), values.size()));
135 }
136 void quote_context(InstrumentId id, Side side, std::span<const double> values) noexcept {
137 e_->quote_context(id, side, values);
138 }
139 // Both sides at once.
140 void quote_context(InstrumentId id, std::initializer_list<double> values) noexcept {
141 const std::span<const double> v(values.begin(), values.size());
142 e_->quote_context(id, Side::Buy, v);
143 e_->quote_context(id, Side::Sell, v);
144 }
145 // The side's values as they stand.
146 [[nodiscard]] const QuoteContext& quote_context(InstrumentId id, Side side) const noexcept {
147 return e_->quote_context(id, side);
148 }
149 // Names for the values, in slot order (at most 23 bytes each), for the store and the tools that
150 // show them; call once, from on_start. No allocation.
151 void quote_context_names(std::initializer_list<std::string_view> names) noexcept {
152 e_->quote_context_names(std::span<const std::string_view>(names.begin(), names.size()));
154 void quote_context_names(std::span<const std::string_view> names) noexcept {
155 e_->quote_context_names(names);
156 }
157 void pull_all_quotes() noexcept {
158 e_->mark_decision();
159 e_->pull_all_quotes();
160 }
161 // The open order in a quote slot (level 0 is closest to the mid), or nullptr.
162 [[nodiscard]] const Order* working_quote(InstrumentId id,
163 Side side,
164 std::uint32_t level = 0) const noexcept {
165 if (!contains(id) || level >= kMaxQuoteLevels) return nullptr;
166 const Handle<Order> h = e_->quote_manager().slot_handle(id, side, level);
167 const Oms& oms = e_->oms();
168 return h.valid() && oms.is_live(h) ? &oms.get(h) : nullptr;
170
171 // ---- direct orders (risk-checked, journaled) ------------------------------------------------
172
173 // RejectReason::InvalidTag: user_tag lies in the QuoteManager's tag range.
174 [[nodiscard]] Result<ClientOrderId, RejectReason> send(const NewOrderRequest& req) noexcept {
175 e_->mark_decision();
176 if (FASTMM_UNLIKELY(QuoteManager::is_quote_tag(req.user_tag))) {
178 }
179 return e_->send_order(req);
181 [[nodiscard]] Result<void, RejectReason> cancel(ClientOrderId id) noexcept {
182 e_->mark_decision();
183 return e_->cancel_order(id);
184 }
185 [[nodiscard]] Result<void, RejectReason> replace(ClientOrderId id, Price px, Qty qty) noexcept {
186 e_->mark_decision();
187 return e_->replace_order(id, px, qty);
188 }
189 // An open order by id, or nullptr once it is terminal. Valid until the next context call.
190 [[nodiscard]] const Order* order(ClientOrderId id) const noexcept {
191 const Oms& oms = e_->oms();
192 const Handle<Order> h = oms.find(id);
193 return h.valid() ? &oms.get(h) : nullptr;
194 }
195 // Estimated quantity resting ahead of an open order at its price: the l2_queue fill model's
196 // queue model on the market data the strategy sees, with [engine] queue_conservatism, from the
197 // order's ack. nullopt while it is not acknowledged or once it is terminal. The engine tracks
198 // queues from the first call on (call it in on_start to cover every order from its ack); an
199 // order already resting at the first call starts at the back of its level as the book shows it.
200 [[nodiscard]] std::optional<Qty> queue_ahead(ClientOrderId id) const noexcept {
201 return e_->queue_ahead(id);
202 }
203 // Send and ack times of an open order, or nullptr (OmsUpdate::times has them in on_order_update
204 // and, through Fill::update, in on_fill).
205 [[nodiscard]] const OrderTimes* order_times(ClientOrderId id) const noexcept {
206 const Oms& oms = e_->oms();
207 const Handle<Order> h = oms.find(id);
208 return h.valid() ? &oms.times(h) : nullptr;
210 // Unfilled quantity of our open orders (quotes included) on one side.
211 [[nodiscard]] Qty open_qty(InstrumentId id, Side side) const noexcept {
212 return e_->oms().open_qty(id, side);
213 }
214 [[nodiscard]] const Oms& oms() const noexcept { return e_->oms(); }
216 // ---- timers: journaled when they fire, so replay reproduces them ---------------------------
217
218 [[nodiscard]] TimerId every(Duration period, std::uint64_t tag = 0) noexcept {
219 return e_->add_timer(period, true, tag);
220 }
221 [[nodiscard]] TimerId once(Duration delay, std::uint64_t tag = 0) noexcept {
222 return e_->add_timer(delay, false, tag);
223 }
224 bool cancel_timer(TimerId id) noexcept { return e_->cancel_timer(id); }
226 // ---- control --------------------------------------------------------------------------------
227
228 [[nodiscard]] bool quoting_enabled() const noexcept { return e_->quoting_enabled(); }
229 // A venue's orders and position are being reconciled, or have not been yet since the session
230 // started (a live session waits for every venue that replays executions; new orders are refused
231 // with NotReconciled until then). Positions may be missing fills while this holds.
232 [[nodiscard]] bool reconciling() const noexcept { return e_->reconciling(); }
233 [[nodiscard]] bool killed() const noexcept { return e_->risk().killed(); }
234 // Reduce-only mode holds the instrument (fastmm-ctl reduce-only, [risk] reduce_only): an order
235 // or replace that would leave its position no nearer zero is refused with
236 // RejectReason::ReduceOnly. A strategy that reads it quotes only the side that reduces.
237 [[nodiscard]] bool reduce_only(InstrumentId id) const noexcept { return e_->reduce_only(id); }
238 // One venue's kill switch: new orders to it are refused and set_quotes ignores its instruments.
239 [[nodiscard]] bool venue_killed(VenueId v) const noexcept { return e_->risk().venue_killed(v); }
240 // The venue's [venues.<name>], for log lines ("venue <id>" when the session names none).
241 [[nodiscard]] std::string_view venue_name(VenueId v) const noexcept { return e_->venue_name(v); }
242 void request_stop() noexcept { e_->stop(); }
243 // Asks for one on_batch_end call once the engine has handled every event that is waiting now
244 // (the feed is empty or the step's max_events_per_step is used up). Work a burst of events would
245 // each trigger (a requote after every balance report) is done once, after the burst. Repeated
246 // requests before the call make one call.
247 void request_batch_end() noexcept { e_->request_batch_end(); }
248 // Asks for a checkpoint in the journal once the events waiting now are handled: state(), the
249 // positions and the open orders, as [engine] checkpoint_s writes. A backtest or a replay can
250 // start from it. No allocation; nothing without a journal.
251 void request_checkpoint() noexcept { e_->request_checkpoint(); }
252 // Trips the global kill switch: quoting stops, quotes are pulled and every working order is
253 // cancelled. The adapter for Python hot hooks uses KillReason::StrategyError.
254 void trip_kill(KillReason reason) noexcept { e_->trip_kill(reason); }
255
256 // ---- venue state: fees, risk headroom, venue health -------------------------------------------
258 // Maker and taker rates of the instrument, in cbps of the notional (positive: a fee). The
259 // configuration's ([[instruments]] maker_bps / taker_bps, else [venues.<x>.fees]), or the
260 // account's own where the connector fetched them (fetch_fees). A backtest charges these.
261 [[nodiscard]] const FeeRates& fees(InstrumentId id) const noexcept { return e_->fees(id); }
262 // What each [risk] limit still admits on the instrument now: the next check uses the same
263 // inputs, so an order of exactly a room passes that limit. RiskHeadroom::kUnlimited (or the
264 // type's max()) where the limit is off.
265 [[nodiscard]] RiskHeadroom risk_headroom(InstrumentId id) const noexcept {
266 return e_->risk_headroom(id);
267 }
268 // Feed lag and order round trip of a venue (core/venue_health.hpp), and whether the feed-lag
269 // gate ([risk] max_feed_lag_ms) holds it now.
270 [[nodiscard]] VenueHealthView venue_health(VenueId v) const noexcept {
271 return e_->venue_health(v);
272 }
273 // The fill-cluster guard ([risk] fill_cluster_names, core/fill_cluster.hpp): which sides it holds
274 // now, until when, and how often it has engaged. While a side is held, set_quotes places nothing
275 // on it; the engine puts the last quotes back when the hold ends.
276 [[nodiscard]] FillClusterView fill_cluster() const noexcept { return e_->fill_cluster(); }
277 // The hazard groups ([[risk.hazard]], core/hazard.hpp), numbered in the order of the
278 // configuration. hazard_group: the group an instrument is a member of, Hazard::kNoGroup for
279 // none. hazard: a group's score, held sides and counts. hazard_add: evidence for one side of a
280 // group, in the units of its threshold; a negative amount takes evidence back. Evidence that
281 // takes the score to the threshold pulls the side before the call returns, and set_quotes places
282 // nothing on it until the hold ends.
283 [[nodiscard]] std::uint32_t hazard_groups() const noexcept { return e_->hazard_groups(); }
284 [[nodiscard]] std::uint32_t hazard_group(InstrumentId id) const noexcept {
285 return e_->hazard_group(id);
287 [[nodiscard]] HazardView hazard(std::uint32_t group) const noexcept { return e_->hazard(group); }
288 void hazard_add(std::uint32_t group, Side side, double amount) noexcept {
289 e_->hazard_add(group, side, amount);
290 }
291 // What the [risk] rate limit and the venue's own limits still admit (core/order_budget.hpp):
292 // the local token bucket, and the venue's order counts and request weight by window as its
293 // connector last published them (live only; venue_known is false elsewhere).
294 [[nodiscard]] OrderBudget order_budget(VenueId v) const noexcept { return e_->order_budget(v); }
295 // What an order slot on account `v` costs now ([capacity], core/capacity_price.hpp): a new order
296 // or a move is sent when its value covers `price`. `on` is false without [capacity].
297 [[nodiscard]] CapacityQuote capacity(VenueId v) const noexcept { return e_->capacity(v); }
298
299 // ---- balances (core/balance_book.hpp) ---------------------------------------------------------
301 // One asset of a venue's account: the venue's last report (on_balance) less what this engine's
302 // orders hold and its fills moved since. Balance::known is false until the venue reports it, and
303 // for an asset no instrument of the venue names.
304 [[nodiscard]] Balance balance(VenueId v, std::string_view asset) const noexcept {
305 return e_->balance(v, asset);
307 // The venue's margin: its account-wide margin where it reports one, else the settlement asset of
308 // its first derivative.
309 [[nodiscard]] Margin margin(VenueId v) const noexcept { return e_->margin(v); }
310 // A venue has reported balances (before that, balance() is unknown everywhere).
311 [[nodiscard]] bool balances_live() const noexcept { return e_->balances_live(); }
312 // Largest quantity of `id` on `side` at `px` the balance covers (a spot buy's quote with the
313 // taker fee, a spot sell's base, a derivative's initial margin), rounded down to the lot.
314 // Qty::max() while the venue has not reported the balance that side draws on.
315 [[nodiscard]] Qty balance_room(InstrumentId id, Side side, Price px) const noexcept {
316 return e_->balance_room(id, side, px);
317 }
318 // ... on one account of the instrument's pool (its own venue when `account` is not one).
319 [[nodiscard]] Qty balance_room(InstrumentId id,
320 Side side,
321 Price px,
322 VenueId account) const noexcept {
323 return e_->balance_room(id, side, px, account);
325
326 // ---- account pools (core/account_pool.hpp) ---------------------------------------------------
328 // The accounts that take orders for a venue's instruments ([venues.<x>] pool_of), the primary
329 // first; just the venue itself without a pool. Each has its own balance(), margin() and
330 // order_budget(); an order goes to the one NewOrderRequest::account names, else to the usable
331 // member whose balance covers it with the most order window left, and Order::venue keeps it.
332 [[nodiscard]] PoolMembers pool(VenueId primary) const noexcept { return e_->pool(primary); }
333 // The venue whose instruments `v` takes orders for: its primary, or `v` itself.
334 [[nodiscard]] VenueId pool_primary(VenueId v) const noexcept { return e_->pool_primary(v); }
335 // The automatic routing would send to `v` now: its order link is live and its kill switch is
336 // not engaged (its balance and window are the order's to decide).
337 [[nodiscard]] bool account_usable(VenueId v) const noexcept { return e_->account_usable(v); }
338
339 // ---- homes (core/pool_homes.hpp, [venues.<primary>.pool]) ----------------------------------
340
341 // The account the instrument's position lives on; invalid when its pool has no
342 // [venues.<primary>.pool] table, or before it has a home.
343 [[nodiscard]] VenueId home(InstrumentId id) const noexcept { return e_->home(id); }
344 // The pool's placement: Placement::Home sends adding orders to the home and reducing orders to
345 // the accounts holding the instrument; Placement::Balance (the default) routes by balance and
346 // window, and the homes are only kept.
347 [[nodiscard]] Placement placement(VenueId primary) const noexcept {
348 return e_->placement(primary);
349 }
350 // What one account of the pool holds of the instrument: a spot instrument's base balance there,
351 // a derivative's position on that account. Without a pool, the position.
352 [[nodiscard]] Qty holding(InstrumentId id, VenueId account) const noexcept {
353 return e_->holding(id, account);
355 // Accounts other than the home that hold a tradable amount of the instrument.
356 [[nodiscard]] std::uint32_t pieces(InstrumentId id) const noexcept { return e_->pieces(id); }
357 // The pool sweeps now ([venues.<primary>.pool] sweep, core/transfer_lane.hpp): its pieces go
358 // home by internal transfer and its spot sells go to the home, so selling each account's part
359 // separately gains nothing. False in a dry run, while its breaker is open and once the day's
360 // transfers are used.
361 [[nodiscard]] bool sweeping(VenueId primary) const noexcept { return e_->sweeping(primary); }
362 // Moves the instrument's home to `account` (journaled). With placement = "home" its adding
363 // orders on other accounts are cancelled; the quotes go to the new home at the next requote.
364 // False when its pool keeps no homes or `account` is not of the pool.
365 bool set_home(InstrumentId id, VenueId account) noexcept {
366 e_->mark_decision();
367 return e_->set_home(id, account);
368 }
369
370 // The quote the instrument's bids want resting (a spot instrument's quote asset, a
371 // derivative's settlement asset; 0: none). A pool treasury with targets = "demand" funds each
372 // account for the needs of the instruments whose home it is. Declare it when the sizes change.
373 void set_funding_need(InstrumentId id, Notional quote) noexcept {
374 e_->set_funding_need(id, quote);
375 }
376 [[nodiscard]] Notional funding_need(InstrumentId id) const noexcept {
377 return e_->funding_need(id);
379
380 // ---- perpetuals (core/perp_book.hpp)
381 // -----------------------------------------------------------
382
383 // The venue's mark and index price of a derivative (on_perp_state), with the time each arrived.
384 // `stale`: older than [accounting] stale_mark_ms, or never reported; usable() is neither.
385 [[nodiscard]] RefPrice mark(InstrumentId id) const noexcept { return e_->mark(id); }
386 [[nodiscard]] RefPrice index(InstrumentId id) const noexcept { return e_->index(id); }
387 // The venue's funding of a perpetual: the rate it will apply at `next`, per `interval`, and
388 // over(d), the rate over a holding time d. `stale` against [accounting] stale_funding_ms.
389 [[nodiscard]] FundingView funding(InstrumentId id) const noexcept { return e_->funding(id); }
390 // Every field as last reported, open interest included, without the staleness applied.
391 [[nodiscard]] const PerpRow& perp_state(InstrumentId id) const noexcept {
392 return e_->perps().row(id);
393 }
394
395 // ---- randomness: seeded from EngineConfig::rng_seed, replay-deterministic --------------------
396
397 [[nodiscard]] Xoshiro256ss& rng() noexcept { return e_->rng(); }
398
399 private:
400 Engine* e_;
401};
402
403} // namespace fastmm
The capacity price ([capacity]): every action that uses an order slot is a purchase.
Dense-by-id table built at startup; symbol lookup is a sorted FlatMap keyed by (venue,...
Definition instrument.hpp:147
Definition oms.hpp:159
const OrderTimes & times(Handle< Order > h) const noexcept
Send and ack times of an open order.
Definition oms.hpp:631
bool is_live(Handle< Order > h) const noexcept
Definition oms.hpp:629
Handle< Order > find(ClientOrderId id) const noexcept
Definition oms.hpp:644
const Order & get(Handle< Order > h) const noexcept
Definition oms.hpp:627
static constexpr bool is_quote_tag(std::uint32_t tag) noexcept
Definition quote_manager.hpp:266
Definition result.hpp:30
Definition strategy_context.hpp:41
void request_stop() noexcept
Definition strategy_context.hpp:235
RiskHeadroom risk_headroom(InstrumentId id) const noexcept
What each [risk] limit still admits on the instrument now: the next check uses the same inputs,...
Definition strategy_context.hpp:257
void hazard_add(std::uint32_t group, Side side, double amount) noexcept
Definition strategy_context.hpp:280
void quote_context(InstrumentId id, Side side, std::initializer_list< double > values) noexcept
What the strategy knows about its quotes on a side, for the record of their fills: up to kQuoteContex...
Definition strategy_context.hpp:129
Placement placement(VenueId primary) const noexcept
The pool's placement: Placement::Home sends adding orders to the home and reducing orders to the acco...
Definition strategy_context.hpp:336
TimerId every(Duration period, std::uint64_t tag=0) noexcept
Definition strategy_context.hpp:212
void pull_quotes(InstrumentId id) noexcept
Definition strategy_context.hpp:91
const Position & position(InstrumentId id) const noexcept
Definition strategy_context.hpp:78
void quote_context_names(std::initializer_list< std::string_view > names) noexcept
Names for the values, in slot order (at most 23 bytes each), for the store and the tools that show th...
Definition strategy_context.hpp:147
Xoshiro256ss & rng() noexcept
Definition strategy_context.hpp:383
bool killed() const noexcept
Definition strategy_context.hpp:226
Level best_ex_self(InstrumentId id, Side side) const noexcept
The book's best level on one side with own_qty taken out; a level that was only ours is skipped.
Definition strategy_context.hpp:73
std::uint32_t hazard_group(InstrumentId id) const noexcept
Definition strategy_context.hpp:276
const FeeRates & fees(InstrumentId id) const noexcept
Maker and taker rates of the instrument, in cbps of the notional (positive: a fee).
Definition strategy_context.hpp:253
Qty own_qty(InstrumentId id, Side side, Price px) const noexcept
Our resting quantity that the venue's feed shows at (id, side, px): the book and the tickers of a liv...
Definition strategy_context.hpp:65
Qty balance_room(InstrumentId id, Side side, Price px) const noexcept
Largest quantity of id on side at px the balance covers (a spot buy's quote with the taker fee,...
Definition strategy_context.hpp:306
bool balances_live() const noexcept
A venue has reported balances (before that, balance() is unknown everywhere).
Definition strategy_context.hpp:302
Result< ClientOrderId, RejectReason > send(const NewOrderRequest &req) noexcept
RejectReason::InvalidTag: user_tag lies in the QuoteManager's tag range.
Definition strategy_context.hpp:169
void set_funding_need(InstrumentId id, Notional quote) noexcept
The quote the instrument's bids want resting (a spot instrument's quote asset, a derivative's settlem...
Definition strategy_context.hpp:362
const Order * order(ClientOrderId id) const noexcept
An open order by id, or nullptr once it is terminal. Valid until the next context call.
Definition strategy_context.hpp:185
bool set_home(InstrumentId id, VenueId account) noexcept
Moves the instrument's home to account (journaled).
Definition strategy_context.hpp:354
Balance balance(VenueId v, std::string_view asset) const noexcept
One asset of a venue's account: the venue's last report (on_balance) less what this engine's orders h...
Definition strategy_context.hpp:295
bool sweeping(VenueId primary) const noexcept
The pool sweeps now ([venues.
Definition strategy_context.hpp:350
VenueId pool_primary(VenueId v) const noexcept
The venue whose instruments v takes orders for: its primary, or v itself.
Definition strategy_context.hpp:324
Notional funding_need(InstrumentId id) const noexcept
Definition strategy_context.hpp:365
bool reduce_only(InstrumentId id) const noexcept
Reduce-only mode holds the instrument (fastmm-ctl reduce-only, [risk] reduce_only): an order or repla...
Definition strategy_context.hpp:230
CapacityQuote capacity(VenueId v) const noexcept
What an order slot on account v costs now ([capacity], core/capacity_price.hpp): a new order or a mov...
Definition strategy_context.hpp:289
typename Engine::Book Book
Definition strategy_context.hpp:43
Result< void, RejectReason > replace(ClientOrderId id, Price px, Qty qty) noexcept
Definition strategy_context.hpp:180
void note_quote(InstrumentId id, Side side, std::string_view reason, Notional budget={}) noexcept
Why the strategy asks what it asks on a side, for the operator: a short reason ("inventory_cap",...
Definition strategy_context.hpp:112
std::optional< Qty > queue_ahead(ClientOrderId id) const noexcept
Estimated quantity resting ahead of an open order at its price: the l2_queue fill model's queue model...
Definition strategy_context.hpp:195
const Order * working_quote(InstrumentId id, Side side, std::uint32_t level=0) const noexcept
The open order in a quote slot (level 0 is closest to the mid), or nullptr.
Definition strategy_context.hpp:158
std::uint32_t hazard_groups() const noexcept
The hazard groups ([[risk.hazard]], core/hazard.hpp), numbered in the order of the configuration.
Definition strategy_context.hpp:275
OrderBudget order_budget(VenueId v) const noexcept
What the [risk] rate limit and the venue's own limits still admit (core/order_budget....
Definition strategy_context.hpp:286
bool account_usable(VenueId v) const noexcept
The automatic routing would send to v now: its order link is live and its kill switch is not engaged ...
Definition strategy_context.hpp:327
Qty open_qty(InstrumentId id, Side side) const noexcept
Unfilled quantity of our open orders (quotes included) on one side.
Definition strategy_context.hpp:206
std::uint32_t pieces(InstrumentId id) const noexcept
Accounts other than the home that hold a tradable amount of the instrument.
Definition strategy_context.hpp:345
bool set_quotes(InstrumentId id, const DesiredQuotes &q) noexcept
Returns false when the quotes were ignored: quoting is disabled (control pull, kill switch,...
Definition strategy_context.hpp:87
void pull_all_quotes() noexcept
Definition strategy_context.hpp:153
bool contains(InstrumentId id) const noexcept
Definition strategy_context.hpp:53
const Book & book(InstrumentId id) const noexcept
Definition strategy_context.hpp:58
bool quoting_enabled() const noexcept
Definition strategy_context.hpp:221
const InstrumentTable & instruments() const noexcept
Definition strategy_context.hpp:52
Portfolio portfolio() const noexcept
PnL totals over every instrument (a loop over all positions; not for every event).
Definition strategy_context.hpp:82
VenueHealthView venue_health(VenueId v) const noexcept
Feed lag and order round trip of a venue (core/venue_health.hpp), and whether the feed-lag gate ([ris...
Definition strategy_context.hpp:262
void request_checkpoint() noexcept
Asks for a checkpoint in the journal once the events waiting now are handled: state(),...
Definition strategy_context.hpp:244
FundingView funding(InstrumentId id) const noexcept
The venue's funding of a perpetual: the rate it will apply at next, per interval, and over(d),...
Definition strategy_context.hpp:376
PoolMembers pool(VenueId primary) const noexcept
The accounts that take orders for a venue's instruments ([venues.
Definition strategy_context.hpp:322
VenueId home(InstrumentId id) const noexcept
The account the instrument's position lives on; invalid when its pool has no [venues.
Definition strategy_context.hpp:332
bool venue_killed(VenueId v) const noexcept
One venue's kill switch: new orders to it are refused and set_quotes ignores its instruments.
Definition strategy_context.hpp:232
std::string_view venue_name(VenueId v) const noexcept
The venue's [venues.<name>], for log lines ("venue <id>" when the session names none).
Definition strategy_context.hpp:234
void metric(std::string_view name, double value) noexcept
A number the strategy publishes by name, for the status file (a budget split, a model's state): the f...
Definition strategy_context.hpp:120
void quiet_book(InstrumentId id, Price lo, Price hi) noexcept
on_book of id is called only once its mid is at or beyond lo or hi, or the book is not valid: a strat...
Definition strategy_context.hpp:106
FillClusterView fill_cluster() const noexcept
The fill-cluster guard ([risk] fill_cluster_names, core/fill_cluster.hpp): which sides it holds now,...
Definition strategy_context.hpp:268
Qty own_qty(InstrumentId id, Side side, Price px, Timestamp at) const noexcept
Definition strategy_context.hpp:68
RefPrice index(InstrumentId id) const noexcept
Definition strategy_context.hpp:373
Qty holding(InstrumentId id, VenueId account) const noexcept
What one account of the pool holds of the instrument: a spot instrument's base balance there,...
Definition strategy_context.hpp:341
const Instrument & instrument(InstrumentId id) const noexcept
Definition strategy_context.hpp:49
void trip_kill(KillReason reason) noexcept
Trips the global kill switch: quoting stops, quotes are pulled and every working order is cancelled.
Definition strategy_context.hpp:247
Timestamp now() const noexcept
Definition strategy_context.hpp:48
void quote_context(InstrumentId id, std::initializer_list< double > values) noexcept
Both sides at once.
Definition strategy_context.hpp:136
HazardView hazard(std::uint32_t group) const noexcept
Definition strategy_context.hpp:279
void request_batch_end() noexcept
Asks for one on_batch_end call once the engine has handled every event that is waiting now (the feed ...
Definition strategy_context.hpp:240
bool reconciling() const noexcept
A venue's orders and position are being reconciled, or have not been yet since the session started (a...
Definition strategy_context.hpp:225
RefPrice mark(InstrumentId id) const noexcept
The venue's mark and index price of a derivative (on_perp_state), with the time each arrived.
Definition strategy_context.hpp:372
const OrderTimes * order_times(ClientOrderId id) const noexcept
Send and ack times of an open order, or nullptr (OmsUpdate::times has them in on_order_update and,...
Definition strategy_context.hpp:200
TimerId once(Duration delay, std::uint64_t tag=0) noexcept
Definition strategy_context.hpp:215
void watch(InstrumentId id, bool on) noexcept
market-data hooks only for what the strategy watches, and needs no more: a multiverse hands an engine...
Definition strategy_context.hpp:102
const PerpRow & perp_state(InstrumentId id) const noexcept
Every field as last reported, open interest included, without the staleness applied.
Definition strategy_context.hpp:378
const Oms & oms() const noexcept
Definition strategy_context.hpp:209
bool cancel_timer(TimerId id) noexcept
Definition strategy_context.hpp:218
Margin margin(VenueId v) const noexcept
The venue's margin: its account-wide margin where it reports one, else the settlement asset of its fi...
Definition strategy_context.hpp:300
Result< void, RejectReason > cancel(ClientOrderId id) noexcept
Definition strategy_context.hpp:176
Minimal expected<T, E>: the hot path never throws, it returns Result.
All engine enumerations.
Fee rates per instrument, in centi-basis-points (integer) of the fill notional.
Fixed<Tag>: int64 fixed point with a global 1e-8 scale (ADR-0001).
Instrument: the single definition of a tradable contract (5.3 / 5.15).
L2Book<kMaxDepth>: price-aggregated book for crypto feeds (5.4).
Definition strategy.hpp:23
KillReason
Why a kill switch (global or one venue's) was tripped.
Definition enums.hpp:603
@ Balance
the account's holding of one asset on one venue (BalanceMsg)
@ InvalidTag
a direct order used a user_tag in the QuoteManager's range
Side
Definition enums.hpp:12
Fixed< struct QtyTag > Qty
Definition fixed_point.hpp:333
constexpr Unexpected< std::decay_t< E > > fail(E &&e) noexcept
Definition result.hpp:25
StrongId< struct InstrumentTag, std::uint32_t > InstrumentId
Dense index into the engine's instrument table.
Definition strong_id.hpp:38
Fixed< struct PriceTag > Price
Definition fixed_point.hpp:332
constexpr std::size_t kMaxQuoteLevels
Definition quote_manager.hpp:81
StrongId< struct VenueTag, std::uint8_t > VenueId
Definition strong_id.hpp:39
Order management (5.8): a Pool<Order> + OpenHashMap<ClientOrderId, Handle> + a ring of recently termi...
Order: the OMS's 128-byte record for one order across its lifetime.
Position tracking, average-cost method (5.8).
QuoteManager (5.6): diffs the strategy's DesiredQuotes against the orders resting at the venue and em...
RiskLimits: the pre-trade limits a session runs with ([risk] in the configuration),...
xoshiro256** - the engine's only source of randomness; seeded from config and written to the journal ...
Strongly typed identifiers.
What an action costs on one account now (ctx.capacity).
Definition capacity_price.hpp:109
Definition quote_manager.hpp:83
Definition time.hpp:22
One maker/taker pair. 1 cbps == 0.01 bps == 1e-6 of the notional.
Definition fees.hpp:26
Definition strong_id.hpp:54
constexpr bool valid() const noexcept
Definition strong_id.hpp:58
Definition instrument.hpp:29
One price level. Shared by book messages and the L2 book.
Definition messages.hpp:31
Definition order.hpp:105
When the order's working leg (the order, or its latest replacement once acknowledged) was sent and ac...
Definition order.hpp:60
Definition order.hpp:16
PnL totals over every instrument (StrategyContext::portfolio()), in the reporting currency when the t...
Definition position.hpp:71
Definition position.hpp:20
Definition order.hpp:72
How much more each limit admits for one instrument now: the largest order (or number of orders) that ...
Definition risk_limits.hpp:75
Definition time.hpp:45
What StrategyContext::venue_health returns. Durations are zero until the first sample.
Definition venue_health.hpp:29
Time primitives.
VenueHealth: per venue, how late its market data arrives and how long our orders take to be acknowled...