FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
hedge_executor.hpp
Go to the documentation of this file.
1#pragma once
2// HedgeExecutor: keeps a strategy's exposure hedged with taker orders, or with post-only orders at
3// the hedge's touch (docs/how-to/strategies/hedge-executor.md). A strategy owns one, configures it
4// in on_start and forwards its hooks.
5//
6// Exposure and residual, in base units (linear contracts: quantity * contract multiplier):
7//
8// residual = sum of source positions + sum of hedge positions - target
9//
10// The sources are the instruments whose position is the exposure (a maker's quote instrument);
11// the target is what the strategy wants to hold net (0 by default). The hedges are instruments
12// that can take the other side, in preference order, each with its own price tolerance.
13//
14// Sizing comes from positions only, never from a count of fills: a restart, a replayed or
15// duplicated fill and an order whose outcome arrives late all end in the same place.
16//
17// One order in flight at a time, across every hedge instrument and the de-risk orders: the
18// residual is one number, and two orders sized from it on two venues would both fill. While an
19// order is open on any hedge instrument (a previous session's included, once reconciliation
20// adopts it), nothing else goes out; its end sends the next one. No order goes out while a venue
21// reconciles (StrategyContext::reconciling): a position may still lack a replayed execution.
22//
23// A hedge is an IOC limit on the first usable hedge instrument, priced its tolerance through the
24// touch, of -residual in its contracts rounded down to the lot and capped at the instrument's
25// max_qty (the remainder follows when it ends). None goes out when that rounds under the lot,
26// min_qty or min_notional: the remainder waits for more exposure rather than being refused.
27//
28// The order is then cut to what [risk] admits now (StrategyContext::risk_headroom): max_order_qty,
29// max_order_notional at the order's price, and on its side the room of max_position and of
30// [risk.underlying] max_net. A hedge larger than one of them goes out in pieces, each after the
31// one before it ends, instead of being refused whole every time. When the limits admit nothing the
32// instrument's minimums allow (the position room is used up), the order goes out whole: the engine
33// refuses it and that is a failure of the instrument, as before. The exposure caps
34// (max_gross_notional, max_net_notional) size it the same way, through the room the engine gives
35// for one order in the instrument's own currency (RiskHeadroom::exposure_buy_notional).
36//
37// A hedge instrument is usable when its venue's order channel is up, its venue is not killed, its
38// book is valid, not older than Config::stale and not held by the feed-lag gate, and it is not
39// benched. The first usable one takes the hedge; when its balance or margin cannot cover the order
40// (StrategyContext::balance_room), the next usable one that can does. When none can, the hedge is
41// held (logged and counted once per episode) until a balance report or a fill changes that.
42//
43// Failures: a hedge that ends with nothing filled, or that the engine refuses, is a failure of its
44// instrument; the next hedge waits Config::retry. max_failures within failure_window bench the
45// instrument for Config::bench while another is not benched; when it is the last one, the executor
46// halts (no more hedges) until restart(). A hedge whose outcome the venue never reported (the
47// ack-timeout cancel, a reconciliation drop with quantity unaccounted for, a generic VenueReject
48// such as a REST timeout) holds every order for Config::uncertain_hold, so a fill still on its way
49// is booked before the positions are trusted again.
50//
51// Bands (Config::band, flat): a residual is hedged once it is worth `band` at the hedge
52// instrument's mid, and then until it is worth less than `flat`; inside the band nothing goes out.
53//
54// Maker mode (Config::maker): the hedge is a post-only limit at the hedge instrument's own touch
55// (a buy at its best bid, a sell at its best ask, our own orders left out) for the whole residual.
56// It rests while the residual keeps its sign and stays outside `flat`; when the touch on its side
57// moves it is cancelled and placed again at the new touch, at most every Config::repeg; with
58// Config::resize it is also placed again when its leaves are worth that much more or less than the
59// residual. A post-only refusal is not a failure: the next order waits `repeg`. With
60// Config::taker_after, an order that has rested that long is cancelled and the rest goes as the
61// IOC above. A maker hedge left open by an earlier session (same tag) is adopted. Book tickers do
62// not move ctx.book: a strategy that forwards the hedge instruments' tickers (on_book_ticker) has
63// the maker hedge priced at the newer of the ticker's touch and the depth book's, and a hedge
64// instrument whose ticker is fresh is not stale.
65//
66// De-risking (Config::derisk_after > 0): when no hedge instrument has taken the residual for that
67// long (unusable, balance short or halted), the executor reduces the exposure itself: reduce-only
68// IOC orders on a source whose position has the residual's sign, priced derisk_tolerance through
69// its touch, each at most derisk_step (base units), one at a time and derisk_interval apart. It
70// stops as soon as a hedge instrument can take the residual again, or the residual is gone. The
71// strategy must not quote the side a de-risk order crosses: pulling the quotes while can_hedge() is
72// false and quoting only the reducing side while held() does that.
73//
74// The executor has no timer of its own: the strategy calls on_timer from one of its timers (the
75// retry, hold and de-risk waits end at the next call after them). Every call is noexcept and
76// allocation-free. Linear instruments only: an inverse leg leaves it idle with an error.
77#include "fastmm/core/enums.hpp"
80#include "fastmm/core/log.hpp"
82#include "fastmm/core/oms.hpp"
83#include "fastmm/core/order.hpp"
85#include "fastmm/core/time.hpp"
88
89#include <algorithm>
90#include <array>
91#include <cstddef>
92#include <cstdint>
93#include <optional>
94#include <string_view>
95
96namespace fastmm {
97
98class HedgeExecutor {
99 public:
100 static constexpr std::size_t kMaxSources = 4;
101 static constexpr std::size_t kMaxHedges = 4;
102 static constexpr std::size_t kMaxFailures = 16;
103 // Maker mode looks its order up and cancels it (StrategyContext::order, cancel).
104 template <class Ctx>
105 static constexpr bool works_orders = requires(Ctx& c, ClientOrderId id) {
106 c.order(id);
107 c.cancel(id);
108 };
109
110 struct Config {
111 std::string_view name = "hedge"; // log prefix
112 std::uint32_t tag = 0; // user_tag of hedge orders
113 std::uint32_t derisk_tag = 0; // user_tag of de-risk orders
114 Duration retry = milliseconds(200); // after a hedge that filled nothing
115 int max_failures = 5; // within failure_window: bench, or halt on the last one
118 Duration stale{}; // a hedge book older than this is unusable; 0: never
119 Duration bench = milliseconds(60000); // how long a failing instrument sits out
120 Duration derisk_after{}; // 0: never de-risk
121 Qty derisk_step{}; // base units per de-risk order; 0: the whole residual
124 // Bands, quote currency at the hedge instrument's mid: hedge once the residual is worth `band`,
125 // then until it is worth less than `flat` (0: any residual; until it rounds under the lot).
126 Notional band{};
127 Notional flat{};
128 // Maker mode: a post-only order at the hedge's own touch instead of an IOC. It follows the
129 // touch at most every `repeg`, is placed again when its leaves are `resize` off the residual
130 // (0: never), and what it leaves after resting `taker_after` crosses (0: never).
131 bool maker = false;
135 };
137 struct Stats {
138 std::uint64_t hedges_sent = 0;
139 std::uint64_t hedge_failures = 0; // ended with nothing filled, or refused by the engine
140 std::uint64_t uncertain_ends = 0; // ended without the venue saying how
141 std::uint64_t halts = 0;
142 std::uint64_t hedges_held = 0; // episodes of a hedge no balance or margin could cover
143 std::uint64_t failovers = 0; // hedging moved to a later instrument in the list
144 std::uint64_t benches = 0; // instruments benched after max_failures
145 std::uint64_t derisk_episodes = 0;
146 std::uint64_t derisk_orders = 0;
147 std::uint64_t maker_moves = 0; // maker hedges cancelled to follow the touch or re-size
148 std::uint64_t maker_crossed = 0; // maker hedges cancelled at taker_after for an IOC
149 std::uint64_t maker_refused = 0; // maker hedges refused as crossing (post-only)
150 };
152 // What the last evaluation found.
153 enum class State : std::uint8_t {
154 Idle, // not started, or nothing evaluated yet
155 Flat, // the residual is zero
156 Waiting, // the residual rounds under the hedge instrument's minimum
157 InFlight, // a hedge or de-risk order is open
158 Reconciling, // a venue reconciles
159 Holding, // retry backoff or uncertain hold
160 Held, // no usable instrument's balance or margin covers the hedge
161 Unavailable, // no hedge instrument is usable
162 Halted, // every hedge instrument failed max_failures times; restart() clears it
163 Inside, // the residual is inside Config::band
164 Resting, // a maker hedge rests at the touch
165 };
166
167 // Why a hedge instrument is not usable now.
168 enum class Reason : std::uint8_t { Usable, Down, Killed, NoBook, Stale, Gated, Benched };
169
170 struct Status {
173 std::uint8_t active = 0; // index of the hedge instrument hedges go to
174 bool in_flight = false;
175 bool held = false;
176 bool halted = false;
177 bool derisking = false;
178 Timestamp hold_until{}; // end of the last retry or uncertain hold
179 };
181 // ---- setup (on_start) ---------------------------------------------------------------------
182
183 // Forgets the legs and every state but the stats. Call before adding legs in on_start.
184 void reset() noexcept {
185 n_sources_ = 0;
186 n_hedges_ = 0;
187 ready_ = false;
188 target_ = Qty{};
189 clear_state();
190 }
191 bool add_source(InstrumentId id) noexcept {
192 if (n_sources_ == kMaxSources) return false;
193 sources_[n_sources_++] = Leg{id, Ratio{}, 0};
194 return true;
195 }
196 bool add_hedge(InstrumentId id, Ratio tolerance) noexcept {
197 if (n_hedges_ == kMaxHedges) return false;
198 hedges_[n_hedges_++] = Leg{id, tolerance, 0};
199 return true;
200 }
201 // Checks the legs against the instrument table: each is configured, linear, used once, and there
202 // is at least one of each. Logs the reason and stays idle when not.
203 template <class Ctx>
204 bool start(Ctx& ctx, const Config& cfg) noexcept {
205 cfg_ = cfg;
206 clear_state();
207 ready_ = false;
208 if (cfg_.maker && !works_orders<Ctx>) {
209 FASTMM_LOG_ERROR("{}: maker mode needs a context that cancels orders; not hedging",
210 cfg_.name);
211 return false;
212 }
213 if (n_sources_ == 0 || n_hedges_ == 0) {
214 FASTMM_LOG_ERROR("{}: needs a source and a hedge instrument; not hedging", cfg_.name);
215 return false;
216 }
217 const auto n = ctx.instruments().size();
218 for (std::size_t i = 0; i < n_sources_ + n_hedges_; ++i) {
219 const InstrumentId id = leg(i).id;
220 if (id.value >= n) {
221 FASTMM_LOG_ERROR("{}: instrument {} is not among the {} configured; not hedging",
222 cfg_.name,
223 id.value,
224 n);
225 return false;
226 }
227 const Instrument& inst = ctx.instrument(id);
228 if (inst.inverse() || !inst.contract_multiplier.is_positive()) {
229 FASTMM_LOG_ERROR("{}: {}:{} is not a linear contract; not hedging",
230 cfg_.name,
231 ctx.venue_name(inst.venue),
232 inst.symbol.view());
233 return false;
234 }
235 for (std::size_t j = 0; j < i; ++j) {
236 if (leg(j).id == id) {
237 FASTMM_LOG_ERROR("{}: {}:{} is named twice; not hedging",
238 cfg_.name,
239 ctx.venue_name(inst.venue),
240 inst.symbol.view());
241 return false;
242 }
243 }
244 }
245 for (std::size_t i = 0; i < n_sources_ + n_hedges_; ++i)
246 venue_of_[i] = ctx.instrument(leg(i).id).venue;
247 ready_ = true;
248 return true;
249 }
250 // Parameters may change while running (on_params); the legs may not.
251 void set_config(const Config& cfg) noexcept { cfg_ = cfg; }
252 void set_tolerance(std::size_t hedge, Ratio tolerance) noexcept {
253 if (hedge < n_hedges_) hedges_[hedge].tolerance = tolerance;
254 }
255 // The net base position the strategy wants to hold; the residual is measured from it.
256 void set_target(Qty base) noexcept { target_ = base; }
257 // Clears a halt, the benches and the failure counts; hedging resumes from the positions.
258 void restart() noexcept {
259 halted_ = false;
260 next_ns_ = 0;
261 for (std::size_t i = 0; i < kMaxHedges; ++i) {
262 failures_[i] = 0;
263 bench_until_[i] = 0;
264 }
265 }
266
267 // ---- hooks: forward the strategy's -----------------------------------------------------------
268
269 // A fill of any leg: the residual moved. False for another instrument.
270 template <class Ctx>
271 bool on_fill(Ctx& ctx, const Fill& fill) noexcept {
272 if (!ready_ || !is_leg(fill.instrument)) return false;
273 update(ctx);
274 return true;
275 }
276
277 // The end of a hedge or de-risk order: counts a failure or holds, then looks again. False for
278 // anything else (another instrument, or an update that is not terminal).
279 template <class Ctx>
280 bool on_order_update(Ctx& ctx, const OmsUpdate& u) noexcept {
281 if (!ready_ || !u.terminal) return false;
282 const Order& o = u.order;
283 const std::int64_t now = ctx.now().ns;
284 if (derisk_open_ && o.cl_ord_id == derisk_id_) {
285 derisk_open_ = false;
286 if (uncertain(u)) hold_uncertain(o, now);
287 update(ctx);
288 return true;
289 }
290 const int k = hedge_index(o.instrument);
291 if (k < 0) return false;
292 if (maker_open_ && o.cl_ord_id == maker_id_) {
293 // Our own cancel ends most maker hedges: only a refusal is a failure, and a post-only one
294 // only means the touch moved.
295 maker_open_ = false;
296 maker_cancel_ = false;
297 forget_in_ticker(static_cast<std::size_t>(k), o);
299 ++stats_.maker_refused;
300 next_ns_ = std::max(next_ns_, now + cfg_.repeg.ns);
301 } else if (o.state == OrderState::Rejected) {
302 failed(ctx, static_cast<std::size_t>(k), now);
303 }
304 } else if (o.cum_qty.is_zero() &&
305 !(cfg_.maker && o.tif == TimeInForce::Gtc && o.state == OrderState::Canceled)) {
306 failed(ctx, static_cast<std::size_t>(k), now);
307 }
308 if (uncertain(u)) hold_uncertain(o, now);
309 update(ctx);
310 return true;
311 }
312
313 // A hedge instrument's book: a new touch to price against.
314 template <class Ctx>
315 void on_book(Ctx& ctx, InstrumentId id) noexcept {
316 if (ready_ && hedge_index(id) >= 0) update(ctx);
317 }
318
319 // A hedge instrument's book ticker: its touch, newer than the depth book's until the book
320 // updates. False for another instrument.
321 template <class Ctx>
322 bool on_book_ticker(Ctx& ctx, InstrumentId id, const BookTickerMsg& m) noexcept {
323 const int k = ready_ ? hedge_index(id) : -1;
324 if (k < 0) return false;
325 if (m.bid_px.is_positive() && m.ask_px > m.bid_px)
326 ticker_[static_cast<std::size_t>(k)] =
327 Ticker{m.bid_px, m.ask_px, m.bid_qty, m.ask_qty, ctx.now().ns};
328 update(ctx);
329 return true;
330 }
331
332 template <class Ctx>
333 void on_timer(Ctx& ctx) noexcept {
334 update(ctx);
335 }
336
337 // Order channels (channel != 0) of the legs' venues. Market data is covered by the books'
338 // validity: the engine clears a venue's books when its channel drops, and a book resync is a
339 // Resyncing followed by snapshots with no Live. Does not send: the next event does.
340 template <class Ctx>
341 void on_connection(Ctx&, const ConnectionStateMsg& m) noexcept {
342 if (!ready_ || m.channel == 0) return;
343 const std::uint32_t bit = 1U << (m.channel & 31U);
344 for (std::size_t i = 0; i < n_sources_ + n_hedges_; ++i) {
345 Leg& l = leg(i);
346 if (venue_of_[i] != m.hdr.venue) continue;
347 if (m.state == ConnState::Live) {
348 l.down &= ~bit;
349 } else {
350 l.down |= bit;
351 }
352 }
353 }
354
355 // A balance report of a leg's venue: a held hedge may fit now. False for another venue.
356 template <class Ctx>
357 bool on_balance(Ctx& ctx, const BalanceMsg& m) noexcept {
358 if (!ready_ || !involves(m.hdr.venue)) return false;
359 update(ctx);
360 return true;
361 }
362
363 // Looks at the positions and sends what they call for; the hooks above end here.
364 template <class Ctx>
365 void update(Ctx& ctx) noexcept {
366 if (!ready_) return;
367 const std::int64_t now = ctx.now().ns;
368 if (cfg_.maker && !maker_open_) adopt(ctx);
369 if (maker_open_ && keep_maker(ctx, now)) return;
370 if (in_flight(ctx)) {
371 state_ = State::InFlight;
372 return;
373 }
374 if (ctx.reconciling()) {
375 state_ = State::Reconciling;
376 return;
377 }
378 if (now < next_ns_) {
379 state_ = State::Holding;
380 return;
381 }
382 const Qty residual = this->residual(ctx);
383 if (halted_) {
384 state_ = State::Halted;
385 blocked(ctx, residual, now);
386 return;
387 }
388 if (residual.is_zero() || inside_flat(ctx, residual)) {
389 state_ = State::Flat;
390 split_ = false;
391 working_ = false;
392 unblock("flat");
393 return;
394 }
395 if (under_minimum(ctx, residual)) {
396 state_ = State::Waiting;
397 working_ = false;
398 unblock("the residual is under the hedge minimum");
399 return;
400 }
401 if (!working_ && cfg_.band.is_positive() && worth(ctx, residual) < cfg_.band) {
402 state_ = State::Inside;
403 unblock("the residual is inside the band");
404 return;
405 }
406 std::size_t first = n_hedges_;
407 for (std::size_t i = 0; i < n_hedges_; ++i) {
408 if (why(ctx, i, now) == Reason::Usable) {
409 first = i;
410 break;
411 }
412 }
413 if (first == n_hedges_) {
414 if (!unavailable_) {
415 unavailable_ = true;
416 const Instrument& h = ctx.instrument(hedges_[0].id);
417 FASTMM_LOG_WARN("{}: no hedge instrument can take {} ({}:{} is {})",
418 cfg_.name,
419 residual,
420 ctx.venue_name(h.venue),
421 h.symbol.view(),
422 to_string(why(ctx, 0, now)));
423 }
424 state_ = State::Unavailable;
425 blocked(ctx, residual, now);
426 return;
427 }
428 // The first usable instrument decides the size; a hedge its balance cannot cover goes to the
429 // next usable instrument that can take it.
430 bool cut = false;
431 const std::optional<NewOrderRequest> sized = order_on(ctx, first, residual, &cut);
432 if (!sized) {
433 state_ = State::Waiting;
434 unblock("the residual is under the hedge minimum");
435 return;
436 }
437 NewOrderRequest req = *sized;
438 std::size_t k = first;
439 if (!covered(ctx, req)) {
440 k = n_hedges_;
441 for (std::size_t j = first + 1; j < n_hedges_; ++j) {
442 if (why(ctx, j, now) != Reason::Usable) continue;
443 bool cut_j = false;
444 const std::optional<NewOrderRequest> r = order_on(ctx, j, residual, &cut_j);
445 if (r && covered(ctx, *r)) {
446 req = *r;
447 k = j;
448 cut = cut_j;
449 break;
450 }
451 }
452 }
453 if (k == n_hedges_) {
454 if (!held_) {
455 held_ = true;
456 ++stats_.hedges_held;
458 "{}: hedge {} {} @ {} held: no usable hedge venue's balance covers it ({} on {}:{}); "
459 "{} unhedged until a balance report or a fill changes that",
460 cfg_.name,
461 req.side,
462 req.qty,
463 req.price,
464 ctx.balance_room(req.instrument, req.side, req.price),
465 ctx.venue_name(ctx.instrument(req.instrument).venue),
466 ctx.instrument(req.instrument).symbol.view(),
467 residual);
468 }
469 state_ = State::Held;
470 blocked(ctx, residual, now);
471 return;
472 }
473 if (held_) {
474 held_ = false;
475 FASTMM_LOG_INFO("{}: the hedge venue's balance covers the hedge again", cfg_.name);
476 }
477 if (k != active_) switch_to(ctx, k, now);
478 unblock("a hedge instrument takes the residual again");
479 const auto sent = ctx.send(req);
480 if (!sent) {
481 FASTMM_LOG_WARN("{}: hedge {} {} @ {} refused: {}",
482 cfg_.name,
483 req.side,
484 req.qty,
485 req.price,
486 sent.error());
487 failed(ctx, k, now);
488 return;
489 }
490 ++stats_.hedges_sent;
491 state_ = State::InFlight;
492 working_ = true; // past the band: hedged until flat
493 if (cfg_.maker && !cross_) {
494 maker_open_ = true;
495 maker_id_ = *sent;
496 maker_k_ = k;
497 maker_sent_ns_ = now;
498 maker_move_ns_ = now;
499 state_ = State::Resting;
500 }
501 cross_ = false;
502 if (cut && !split_) {
503 split_ = true;
505 "{}: [risk] admits {} {} @ {} of the {} to hedge on {}:{}: it goes out in pieces",
506 cfg_.name,
507 req.side,
508 req.qty,
509 req.price,
510 residual,
511 ctx.venue_name(ctx.instrument(req.instrument).venue),
512 ctx.instrument(req.instrument).symbol.view());
513 }
514 }
515
516 // ---- state -----------------------------------------------------------------------------------
518 [[nodiscard]] bool ready() const noexcept { return ready_; }
519 [[nodiscard]] bool halted() const noexcept { return halted_; }
520 // The last hedge the positions asked for fits no usable instrument's balance.
521 [[nodiscard]] bool held() const noexcept { return held_; }
522 [[nodiscard]] bool derisking() const noexcept { return derisking_; }
523 [[nodiscard]] State state() const noexcept { return state_; }
524 [[nodiscard]] const Stats& stats() const noexcept { return stats_; }
525 [[nodiscard]] std::size_t hedge_count() const noexcept { return n_hedges_; }
526 [[nodiscard]] InstrumentId hedge_id(std::size_t i) const noexcept { return hedges_[i].id; }
527 [[nodiscard]] std::size_t active() const noexcept { return active_; }
528 [[nodiscard]] Qty target() const noexcept { return target_; }
529 [[nodiscard]] bool is_hedge(InstrumentId id) const noexcept { return hedge_index(id) >= 0; }
530 [[nodiscard]] bool is_source(InstrumentId id) const noexcept {
531 for (std::size_t i = 0; i < n_sources_; ++i) {
532 if (sources_[i].id == id) return true;
533 }
534 return false;
536 [[nodiscard]] bool is_leg(InstrumentId id) const noexcept {
537 return is_source(id) || is_hedge(id);
538 }
539 // A venue of any leg.
540 [[nodiscard]] bool involves(VenueId v) const noexcept {
541 for (std::size_t i = 0; i < n_sources_ + n_hedges_; ++i) {
542 if (venue_of_[i] == v) return true;
543 }
544 return false;
545 }
546
547 // Sources plus hedges minus the target, base units.
548 template <class Ctx>
549 [[nodiscard]] Qty residual(const Ctx& ctx) const noexcept {
550 Qty r = -target_;
551 for (std::size_t i = 0; i < n_sources_ + n_hedges_; ++i) {
552 const InstrumentId id = leg(i).id;
553 r += to_base(ctx.instrument(id), ctx.position(id).qty);
554 }
555 return r;
556 }
557
558 // The residual rounds under the lot or min_qty of every hedge instrument: no hedge order can
559 // take it, whichever instrument is usable.
560 template <class Ctx>
561 [[nodiscard]] bool under_minimum(const Ctx& ctx, Qty residual) const noexcept {
562 for (std::size_t i = 0; i < n_hedges_; ++i) {
563 const Instrument& inst = ctx.instrument(hedges_[i].id);
564 const Qty q = inst.round_qty(to_contracts(inst, residual.abs()));
565 if (q.is_positive() && q >= inst.min_qty) return false;
566 }
567 return true;
568 }
569
570 // Why hedge instrument `i` cannot take a hedge now (Reason::Usable: it can).
571 template <class Ctx>
572 [[nodiscard]] Reason why(const Ctx& ctx, std::size_t i, std::int64_t now) const noexcept {
573 const Leg& h = hedges_[i];
574 const VenueId v = venue_of_[n_sources_ + i];
575 if (h.down != 0) return Reason::Down;
576 if (ctx.venue_killed(v)) return Reason::Killed;
577 if (now < bench_until_[i]) return Reason::Benched;
578 const auto& b = ctx.book(h.id);
579 if (!b.is_valid()) return Reason::NoBook;
580 if (cfg_.stale.ns > 0) {
581 const Timestamp t = b.last_update();
582 const std::int64_t last = std::max(t.valid() ? t.ns : 0, ticker_[i].ns);
583 if (last > 0 && now - last > cfg_.stale.ns) return Reason::Stale;
584 }
585 if (ctx.venue_health(v).gated) return Reason::Gated;
586 return Reason::Usable;
587 }
588
589 // Some hedge instrument can take a hedge now, and hedging is not halted. A quoting strategy pulls
590 // its quotes while this is false: a fill could not be hedged, and a de-risk order may be working.
591 template <class Ctx>
592 [[nodiscard]] bool can_hedge(const Ctx& ctx) const noexcept {
593 if (!ready_ || halted_) return false;
594 const std::int64_t now = ctx.now().ns;
595 for (std::size_t i = 0; i < n_hedges_; ++i) {
596 if (why(ctx, i, now) == Reason::Usable) return true;
597 }
598 return false;
599 }
600
601 template <class Ctx>
602 [[nodiscard]] Status status(const Ctx& ctx) const noexcept {
603 Status s;
604 s.state = state_;
605 s.residual = residual(ctx);
606 s.active = static_cast<std::uint8_t>(active_);
607 s.in_flight = in_flight(ctx);
608 s.held = held_;
609 s.halted = halted_;
610 s.derisking = derisking_;
611 s.hold_until = Timestamp{next_ns_};
612 return s;
613 }
614
615 // ---- pure functions --------------------------------------------------------------------------
617 // Contracts to base units and back (linear: qty * multiplier).
618 [[nodiscard]] static constexpr Qty to_base(const Instrument& inst, Qty contracts) noexcept {
619 return Qty::from_raw(mul_raw(contracts, inst.contract_multiplier));
620 }
621 [[nodiscard]] static constexpr Qty to_contracts(const Instrument& inst, Qty base) noexcept {
622 if (!inst.contract_multiplier.is_positive()) return Qty{};
623 return Qty::from_raw(detail::mul_div(base.raw, kFixedScale, inst.contract_multiplier.raw));
624 }
625
626 // The order on `inst` that brings `residual` (base units) back towards zero: an IOC of
627 // -residual in contracts, rounded down to the lot and capped at max_qty, priced `tolerance`
628 // through the touch and rounded towards it. None when it rounds under the lot or min_qty, its
629 // notional is under min_notional, or the touch it needs is empty: a hedge the venue (or the risk
630 // check) must refuse would only count as a failure.
631 [[nodiscard]] static std::optional<NewOrderRequest> hedge_order(const Instrument& inst,
633 Price best_bid,
634 Price best_ask,
635 Ratio tolerance,
636 std::uint32_t tag) noexcept {
637 if (residual.is_zero()) return std::nullopt;
638 const Side side = residual.is_negative() ? Side::Buy : Side::Sell;
639 Qty qty = inst.round_qty(to_contracts(inst, residual.abs()));
640 if (inst.max_qty.is_positive() && qty > inst.max_qty) qty = inst.round_qty(inst.max_qty);
641 if (!qty.is_positive() || qty < inst.min_qty) return std::nullopt;
642 Price px;
643 if (side == Side::Buy) {
644 if (!best_ask.is_positive()) return std::nullopt;
645 px = inst.round_price(best_ask + best_ask * tolerance, Side::Buy);
646 } else {
647 if (!best_bid.is_positive()) return std::nullopt;
648 px = inst.round_price(best_bid - best_bid * tolerance, Side::Sell);
649 }
650 if (!px.is_positive()) return std::nullopt;
651 if (inst.min_notional.is_positive() && inst.notional(px, qty) < inst.min_notional)
652 return std::nullopt;
653 return NewOrderRequest::limit(inst.id, side, px, qty).ioc().tag(tag);
654 }
655
656 // The maker hedge of `residual` on `inst`: a post-only limit of -residual in contracts, rounded
657 // down to the lot and capped at max_qty, at the touch of its own side (`bid` for a buy, `ask` for
658 // a sell). None under the lot, min_qty or min_notional, or without that touch.
659 [[nodiscard]] static std::optional<NewOrderRequest> maker_order(
660 const Instrument& inst, Qty residual, Price bid, Price ask, std::uint32_t tag) noexcept {
661 if (residual.is_zero()) return std::nullopt;
662 const Side side = residual.is_negative() ? Side::Buy : Side::Sell;
663 Qty qty = inst.round_qty(to_contracts(inst, residual.abs()));
664 if (inst.max_qty.is_positive() && qty > inst.max_qty) qty = inst.round_qty(inst.max_qty);
665 if (!qty.is_positive() || qty < inst.min_qty) return std::nullopt;
666 const Price px = side == Side::Buy ? bid : ask;
667 if (!px.is_positive()) return std::nullopt;
668 if (inst.min_notional.is_positive() && inst.notional(px, qty) < inst.min_notional)
669 return std::nullopt;
670 return NewOrderRequest::limit(inst.id, side, px, qty).post_only().tag(tag);
671 }
672
673 // The largest quantity of `inst` whose notional at `price` is at most `cap`, rounded down to the
674 // lot (zero when not even one lot fits, or `price` is not positive).
675 [[nodiscard]] static constexpr Qty qty_within(const Instrument& inst,
676 Price price,
677 Notional cap) noexcept {
678 const Notional one = inst.notional(price, Qty::from_int(1));
679 if (!one.is_positive() || !cap.is_positive()) return Qty{};
680 Qty q = inst.round_qty(Qty::from_raw(detail::mul_div(cap.raw, kFixedScale, one.raw)));
681 // The notional rounds at each step: never over the cap.
682 while (q.is_positive() && inst.notional(price, q) > cap) q = q - inst.lot;
683 return q;
684 }
685
686 // The largest order of `side` on `inst` at `price` that [risk] admits now: max_order_qty,
687 // max_order_notional at that price, that side's room of max_position and of [risk.underlying]
688 // max_net, and what max_gross_notional and max_net_notional leave for it at that price.
689 // Qty::max() when none of them is set.
690 [[nodiscard]] static constexpr Qty risk_room(const RiskHeadroom& h,
691 const Instrument& inst,
692 Side side,
693 Price price) noexcept {
694 Qty room = h.max_order_qty;
695 room = std::min(room, side == Side::Buy ? h.buy_qty : h.sell_qty);
696 room = std::min(room, side == Side::Buy ? h.underlying_buy_qty : h.underlying_sell_qty);
697 Notional notional = h.max_order_notional;
698 notional =
699 std::min(notional, side == Side::Buy ? h.exposure_buy_notional : h.exposure_sell_notional);
700 if (notional != Notional::max()) room = std::min(room, qty_within(inst, price, notional));
701 return room;
702 }
703
704 // Cuts `r` to risk_room() when that is less and still an order the instrument takes (the lot,
705 // min_qty, min_notional). True when it was cut. An order the limits leave no such room for
706 // stays whole: the engine's refusal is then what the caller counts.
707 [[nodiscard]] static constexpr bool fit_risk(const RiskHeadroom& h,
708 const Instrument& inst,
709 NewOrderRequest& r) noexcept {
710 const Qty room = risk_room(h, inst, r.side, r.price);
711 if (room >= r.qty) return false;
712 const Qty q = inst.round_qty(room);
713 if (!q.is_positive() || q < inst.min_qty) return false;
714 if (inst.min_notional.is_positive() && inst.notional(r.price, q) < inst.min_notional)
715 return false;
716 r.qty = q;
717 return true;
718 }
719
720 // A terminal update whose outcome the venue did not report: the ack timeout cancelled an order
721 // the venue never acknowledged, reconciliation found it gone with quantity unaccounted for, or a
722 // connector turned a request whose outcome it does not know into a generic reject.
723 [[nodiscard]] static bool uncertain(const OmsUpdate& u) noexcept {
724 const Order& o = u.order;
725 return u.unresolved_qty.is_positive() ||
726 (o.state == OrderState::Canceled && o.venue_order_id.empty() && o.cum_qty.is_zero()) ||
729
730 [[nodiscard]] static constexpr std::string_view to_string(Reason r) noexcept {
731 switch (r) {
732 case Reason::Usable:
733 return "usable";
734 case Reason::Down:
735 return "down";
736 case Reason::Killed:
737 return "killed";
738 case Reason::NoBook:
739 return "without a book";
740 case Reason::Stale:
741 return "stale";
742 case Reason::Gated:
743 return "held by the feed-lag gate";
744 case Reason::Benched:
745 return "benched";
746 }
747 return "?";
748 }
749 [[nodiscard]] static constexpr std::string_view to_string(State s) noexcept {
750 switch (s) {
751 case State::Idle:
752 return "idle";
753 case State::Flat:
754 return "flat";
755 case State::Waiting:
756 return "waiting";
757 case State::InFlight:
758 return "in flight";
760 return "reconciling";
761 case State::Holding:
762 return "holding";
763 case State::Held:
764 return "held";
766 return "unavailable";
767 case State::Halted:
768 return "halted";
769 case State::Inside:
770 return "inside the band";
771 case State::Resting:
772 return "resting";
773 }
774 return "?";
775 }
776
777 private:
778 struct Ticker {
779 Price bid{};
780 Price ask{};
781 Qty bid_qty{};
782 Qty ask_qty{};
783 std::int64_t ns = 0; // when it arrived (engine time); 0: none
784 };
785 struct Leg {
786 InstrumentId id{};
787 Ratio tolerance{};
788 std::uint32_t down = 0; // bit per order channel of the venue that is not Live
789 };
790
791 [[nodiscard]] Leg& leg(std::size_t i) noexcept {
792 return i < n_sources_ ? sources_[i] : hedges_[i - n_sources_];
793 }
794 [[nodiscard]] const Leg& leg(std::size_t i) const noexcept {
795 return i < n_sources_ ? sources_[i] : hedges_[i - n_sources_];
796 }
797 [[nodiscard]] int hedge_index(InstrumentId id) const noexcept {
798 for (std::size_t i = 0; i < n_hedges_; ++i) {
799 if (hedges_[i].id == id) return static_cast<int>(i);
800 }
801 return -1;
802 }
803
804 void clear_state() noexcept {
805 for (std::size_t i = 0; i < kMaxSources + kMaxHedges; ++i) venue_of_[i] = VenueId{};
806 for (Leg& l : sources_) l.down = 0;
807 for (Leg& l : hedges_) l.down = 0;
808 next_ns_ = 0;
809 for (std::size_t i = 0; i < kMaxHedges; ++i) {
810 failures_[i] = 0;
811 bench_until_[i] = 0;
812 }
813 active_ = 0;
814 halted_ = false;
815 held_ = false;
816 unavailable_ = false;
817 state_ = State::Idle;
818 blocked_ = false;
819 blocked_ns_ = 0;
820 derisking_ = false;
821 derisk_open_ = false;
822 derisk_id_ = ClientOrderId{};
823 next_derisk_ns_ = 0;
824 derisk_stuck_ = false;
825 split_ = false;
826 working_ = false;
827 maker_open_ = false;
828 maker_cancel_ = false;
829 cross_ = false;
830 maker_id_ = ClientOrderId{};
831 maker_k_ = 0;
832 maker_sent_ns_ = 0;
833 maker_move_ns_ = 0;
834 ticker_ = {};
835 }
836
837 // What [risk] admits on `id` now. A context without the risk engine (a test double) has no
838 // limit.
839 template <class Ctx>
840 [[nodiscard]] static RiskHeadroom headroom(const Ctx& ctx, InstrumentId id) noexcept {
841 if constexpr (requires { ctx.risk_headroom(id); }) {
842 return ctx.risk_headroom(id);
843 } else {
844 return RiskHeadroom{};
845 }
846 }
847
848 // The hedge of `residual` on hedge instrument `i`, priced from its book and cut to what [risk]
849 // admits (`cut` says whether it was).
850 template <class Ctx>
851 [[nodiscard]] std::optional<NewOrderRequest> order_on(const Ctx& ctx,
852 std::size_t i,
854 bool* cut) const noexcept {
855 const Leg& h = hedges_[i];
856 const auto& b = ctx.book(h.id);
857 const Instrument& inst = ctx.instrument(h.id);
858 std::optional<NewOrderRequest> r =
859 cfg_.maker && !cross_
860 ? maker_order(inst,
861 residual,
862 touch(ctx, h.id, Side::Buy),
863 touch(ctx, h.id, Side::Sell),
864 cfg_.tag)
865 : hedge_order(
866 inst, residual, b.best_bid().price, b.best_ask().price, h.tolerance, cfg_.tag);
867 if (r) *cut = fit_risk(headroom(ctx, h.id), inst, *r);
868 return r;
869 }
870
871 // The best price of one side of hedge instrument `id`: its last forwarded ticker's when that is
872 // newer than the depth book, unless all it shows there is our maker hedge; else the depth book's
873 // without our own orders where the context can tell them (StrategyContext::best_ex_self).
874 template <class Ctx>
875 [[nodiscard]] Price touch(const Ctx& ctx, InstrumentId id, Side side) const noexcept {
876 const auto& b = ctx.book(id);
877 const int k = hedge_index(id);
878 if (k >= 0) {
879 const Ticker& t = ticker_[static_cast<std::size_t>(k)];
880 const Timestamp u = b.last_update();
881 if (t.ns > 0 && (!u.valid() || t.ns >= u.ns)) {
882 const Price px = side == Side::Buy ? t.bid : t.ask;
883 const Qty shown = side == Side::Buy ? t.bid_qty : t.ask_qty;
884 Qty ours{};
885 if constexpr (works_orders<Ctx>) {
886 if (maker_open_) {
887 const Order* o = ctx.order(maker_id_);
888 if (o != nullptr && o->instrument == id && o->side == side && o->price == px)
889 ours = o->leaves_qty();
890 }
891 }
892 if (px.is_positive() && (!ours.is_positive() || shown > ours)) return px;
893 }
894 }
895 if constexpr (requires { ctx.best_ex_self(id, side); }) {
896 return ctx.best_ex_self(id, side).price;
897 } else {
898 return side == Side::Buy ? b.best_bid().price : b.best_ask().price;
899 }
900 }
901
902 // The maker hedge `o` ended: the ticker no longer shows it. A side it was all of is left to the
903 // depth book until the next ticker.
904 void forget_in_ticker(std::size_t k, const Order& o) noexcept {
905 Ticker& t = ticker_[k];
906 Price& px = o.side == Side::Buy ? t.bid : t.ask;
907 Qty& shown = o.side == Side::Buy ? t.bid_qty : t.ask_qty;
908 if (t.ns == 0 || px != o.price) return;
909 shown = shown - o.leaves_qty();
910 if (!shown.is_positive()) px = Price{};
911 }
912
913 // What `residual` is worth at the mid of the hedge instrument hedges go to; Notional::max() while
914 // its book is not valid, so no band holds a hedge back.
915 template <class Ctx>
916 [[nodiscard]] Notional worth(const Ctx& ctx, Qty residual) const noexcept {
917 const InstrumentId id = hedges_[active_].id;
918 const auto& b = ctx.book(id);
919 if (!b.is_valid()) return Notional::max();
920 const Instrument& inst = ctx.instrument(id);
921 return inst.notional(b.mid(), to_contracts(inst, residual.abs()));
922 }
923 // The residual is within Config::flat.
924 template <class Ctx>
925 [[nodiscard]] bool inside_flat(const Ctx& ctx, Qty residual) const noexcept {
926 return cfg_.flat.is_positive() && worth(ctx, residual) < cfg_.flat;
927 }
928
929 // A maker hedge is open: keeps it, or cancels it to follow the touch, re-size, cross or stop.
930 // True while it stays open (resting, pending, or its cancel out); false once it has ended.
931 template <class Ctx>
932 bool keep_maker(Ctx& ctx, std::int64_t now) noexcept {
933 if constexpr (!works_orders<Ctx>) {
934 maker_open_ = false;
935 return false;
936 } else {
937 return keep_maker_on(ctx, now);
938 }
939 }
940 template <class Ctx>
941 bool keep_maker_on(Ctx& ctx, std::int64_t now) noexcept {
942 const Order* o = ctx.order(maker_id_);
943 if (o == nullptr) {
944 maker_open_ = false;
945 maker_cancel_ = false;
946 return false;
947 }
948 state_ = State::InFlight;
949 if (maker_cancel_ || is_pending(o->state)) return true;
950 const Qty residual = this->residual(ctx);
951 const InstrumentId id = o->instrument;
952 const Instrument& inst = ctx.instrument(id);
953 const Side want = residual.is_negative() ? Side::Buy : Side::Sell;
954 const bool stop = residual.is_zero() || inside_flat(ctx, residual) ||
955 under_minimum(ctx, residual) || ctx.reconciling() || halted_ ||
956 why(ctx, maker_k_, now) != Reason::Usable;
957 bool move = false;
958 if (!stop && want == o->side) {
959 if (cfg_.taker_after.ns > 0 && now - maker_sent_ns_ >= cfg_.taker_after.ns) {
960 move = true;
961 cross_ = true;
962 ++stats_.maker_crossed;
963 } else if (now - maker_move_ns_ >= cfg_.repeg.ns) {
964 const Price px = touch(ctx, id, want);
965 if (px.is_positive() && px != o->price) move = true;
966 if (cfg_.resize.is_positive()) {
967 const Qty need = inst.round_qty(to_contracts(inst, residual.abs()));
968 const Qty off = (o->leaves_qty() - need).abs();
969 if (inst.notional(o->price, off) > cfg_.resize) move = true;
970 }
971 }
972 if (!move) {
973 state_ = State::Resting;
974 return true;
975 }
976 }
977 if (stop) working_ = false;
978 if (ctx.cancel(maker_id_)) {
979 maker_cancel_ = true;
980 maker_move_ns_ = now;
981 if (move && !cross_) ++stats_.maker_moves;
982 }
983 return true;
984 }
985
986 // A maker hedge an earlier session left open (an open order with our tag on a hedge
987 // instrument) is taken over as the one resting.
988 template <class Ctx>
989 void adopt(const Ctx& ctx) noexcept {
990 if constexpr (requires { ctx.oms(); }) {
991 ctx.oms().for_each_open_order([&](Handle<Order>, const Order& o) {
992 if (maker_open_ || o.user_tag != cfg_.tag || hedge_index(o.instrument) < 0) return;
993 maker_open_ = true;
994 maker_cancel_ = false;
995 maker_id_ = o.cl_ord_id;
996 maker_k_ = static_cast<std::size_t>(hedge_index(o.instrument));
997 maker_sent_ns_ = ctx.now().ns;
998 maker_move_ns_ = 0;
999 });
1000 }
1001 }
1002 // The venue's balance or margin covers `r` (StrategyContext::balance_room).
1003 template <class Ctx>
1004 [[nodiscard]] static bool covered(const Ctx& ctx, const NewOrderRequest& r) noexcept {
1005 return ctx.balance_room(r.instrument, r.side, r.price) >= r.qty;
1006 }
1007
1008 template <class Ctx>
1009 [[nodiscard]] bool in_flight(const Ctx& ctx) const noexcept {
1010 if (derisk_open_) return true;
1011 for (std::size_t i = 0; i < n_hedges_; ++i) {
1012 const InstrumentId id = hedges_[i].id;
1013 if (ctx.open_qty(id, Side::Buy).is_positive() || ctx.open_qty(id, Side::Sell).is_positive())
1014 return true;
1015 }
1016 return false;
1017 }
1018
1019 void hold_uncertain(const Order& o, std::int64_t now) noexcept {
1020 ++stats_.uncertain_ends;
1021 const std::int64_t until = now + cfg_.uncertain_hold.ns;
1022 if (until > next_ns_) next_ns_ = until;
1024 "{}: order {} ended without the venue saying how; next order in {} ms at the earliest",
1025 cfg_.name,
1026 encode_cl_ord_id(o.cl_ord_id),
1027 cfg_.uncertain_hold.millis());
1028 }
1029
1030 template <class Ctx>
1031 void switch_to(const Ctx& ctx, std::size_t k, std::int64_t now) noexcept {
1032 const std::size_t from = active_;
1033 active_ = k;
1034 const InstrumentId a = hedges_[from].id;
1035 const InstrumentId b = hedges_[k].id;
1036 if (k > from) {
1037 ++stats_.failovers;
1038 const Reason r = why(ctx, from, now);
1039 FASTMM_LOG_WARN("{}: hedging moves from {}:{} to {}:{}: the first is {}",
1040 cfg_.name,
1041 ctx.venue_name(ctx.instrument(a).venue),
1042 ctx.instrument(a).symbol.view(),
1043 ctx.venue_name(ctx.instrument(b).venue),
1044 ctx.instrument(b).symbol.view(),
1045 r == Reason::Usable ? std::string_view{"short of balance"} : to_string(r));
1046 } else {
1047 FASTMM_LOG_WARN("{}: hedging back on {}:{} from {}:{}",
1048 cfg_.name,
1049 ctx.venue_name(ctx.instrument(b).venue),
1050 ctx.instrument(b).symbol.view(),
1051 ctx.venue_name(ctx.instrument(a).venue),
1052 ctx.instrument(a).symbol.view());
1053 }
1054 }
1055
1056 template <class Ctx>
1057 void failed(Ctx& ctx, std::size_t k, std::int64_t now) noexcept {
1058 ++stats_.hedge_failures;
1059 next_ns_ = now + cfg_.retry.ns;
1060 const auto n = static_cast<std::size_t>(cfg_.max_failures);
1061 std::size_t& count = failures_[k];
1062 fail_ns_[k][count % kMaxFailures] = now;
1063 ++count;
1064 if (halted_ || count < n) return;
1065 const std::int64_t oldest = fail_ns_[k][(count - n) % kMaxFailures];
1066 if (now - oldest > cfg_.failure_window.ns) return;
1067 bool other = false;
1068 for (std::size_t i = 0; i < n_hedges_; ++i) {
1069 if (i != k && now >= bench_until_[i]) other = true;
1070 }
1071 const Instrument& inst = ctx.instrument(hedges_[k].id);
1072 const std::string_view venue = ctx.venue_name(inst.venue);
1073 const std::string_view sym = inst.symbol.view();
1074 if (other) {
1075 bench_until_[k] = now + cfg_.bench.ns;
1076 count = 0;
1077 ++stats_.benches;
1078 FASTMM_LOG_WARN("{}: {} hedges on {}:{} filled nothing within {} ms: it sits out {} ms",
1079 cfg_.name,
1080 n,
1081 venue,
1082 sym,
1083 cfg_.failure_window.millis(),
1084 cfg_.bench.millis());
1085 return;
1086 }
1087 halted_ = true;
1088 ++stats_.halts;
1090 "{}: {} hedges on {}:{} filled nothing within {} ms: hedging stopped with {} unhedged; "
1091 "restart to resume",
1092 cfg_.name,
1093 n,
1094 venue,
1095 sym,
1096 cfg_.failure_window.millis(),
1097 residual(ctx));
1098 }
1099
1100 // ---- de-risking ----------------------------------------------------------------------------
1101
1102 // No hedge instrument took the residual: after derisk_after, reduce a source instead.
1103 template <class Ctx>
1104 void blocked(Ctx& ctx, Qty residual, std::int64_t now) noexcept {
1105 if (cfg_.derisk_after.ns <= 0 || residual.is_zero()) return;
1106 if (!blocked_) {
1107 blocked_ = true;
1108 blocked_ns_ = now;
1109 }
1110 if (now - blocked_ns_ < cfg_.derisk_after.ns) return;
1111 if (!derisking_) {
1112 derisking_ = true;
1113 derisk_stuck_ = false;
1114 ++stats_.derisk_episodes;
1116 "{}: no hedge instrument has taken {} for {} ms: de-risking the sources in steps of at "
1117 "most {}",
1118 cfg_.name,
1119 residual,
1120 cfg_.derisk_after.millis(),
1121 cfg_.derisk_step);
1122 }
1123 if (now < next_derisk_ns_) return;
1124 derisk_step(ctx, residual, now);
1125 }
1126
1127 // A hedge instrument takes the residual, or there is none to take.
1128 void unblock(std::string_view why) noexcept {
1129 unavailable_ = false;
1130 blocked_ = false;
1131 if (!derisking_) return;
1132 derisking_ = false;
1133 FASTMM_LOG_WARN("{}: de-risking ends: {}", cfg_.name, why);
1134 }
1135
1136 template <class Ctx>
1137 void derisk_step(Ctx& ctx, Qty residual, std::int64_t now) noexcept {
1138 const Side side = residual.is_positive() ? Side::Sell : Side::Buy;
1139 for (std::size_t i = 0; i < n_sources_; ++i) {
1140 const Leg& s = sources_[i];
1141 const Instrument& inst = ctx.instrument(s.id);
1142 const Qty pos = to_base(inst, ctx.position(s.id).qty);
1143 // Only a position on the residual's side is reduced.
1144 if (pos.is_zero() || pos.is_negative() != residual.is_negative()) continue;
1145 if (s.down != 0 || ctx.venue_killed(inst.venue)) continue;
1146 const auto& b = ctx.book(s.id);
1147 if (!b.is_valid()) continue;
1148 Qty base = residual.abs();
1149 if (pos.abs() < base) base = pos.abs();
1150 if (cfg_.derisk_step.is_positive() && cfg_.derisk_step < base) base = cfg_.derisk_step;
1151 std::optional<NewOrderRequest> r = hedge_order(inst,
1152 side == Side::Sell ? base : -base,
1153 b.best_bid().price,
1154 b.best_ask().price,
1155 cfg_.derisk_tolerance,
1156 cfg_.derisk_tag);
1157 // A reduce-only derivative order passes the engine's balance check; spot sells need base.
1158 if (!r) continue;
1159 if (!inst.is_derivative() && ctx.balance_room(s.id, r->side, r->price) < r->qty) continue;
1160 NewOrderRequest req = *r;
1161 req.reduce_only = true;
1162 static_cast<void>(fit_risk(headroom(ctx, s.id), inst, req));
1163 next_derisk_ns_ = now + cfg_.derisk_interval.ns;
1164 const auto sent = ctx.send(req);
1165 if (!sent) {
1166 FASTMM_LOG_WARN("{}: de-risk {}:{} {} {} @ {} refused: {}",
1167 cfg_.name,
1168 ctx.venue_name(inst.venue),
1169 inst.symbol.view(),
1170 req.side,
1171 req.qty,
1172 req.price,
1173 sent.error());
1174 return;
1175 }
1176 derisk_open_ = true;
1177 derisk_id_ = *sent;
1178 derisk_stuck_ = false;
1179 ++stats_.derisk_orders;
1180 return;
1181 }
1182 if (!derisk_stuck_) {
1183 derisk_stuck_ = true;
1184 FASTMM_LOG_WARN("{}: no source can take a de-risk order for {} now", cfg_.name, residual);
1185 }
1186 }
1187
1188 Config cfg_{};
1189 std::array<Leg, kMaxSources> sources_{};
1190 std::array<Leg, kMaxHedges> hedges_{};
1191 std::array<VenueId, kMaxSources + kMaxHedges> venue_of_{};
1192 std::size_t n_sources_ = 0;
1193 std::size_t n_hedges_ = 0;
1194 Qty target_{};
1195 std::int64_t next_ns_ = 0; // retry backoff or uncertain hold
1196 std::array<std::size_t, kMaxHedges> failures_{};
1197 std::array<std::array<std::int64_t, kMaxFailures>, kMaxHedges> fail_ns_{};
1198 std::array<std::int64_t, kMaxHedges> bench_until_{};
1199 std::array<Ticker, kMaxHedges> ticker_{}; // on_book_ticker, per hedge instrument
1200 std::size_t active_ = 0;
1201 Stats stats_{};
1202 State state_ = State::Idle;
1203 bool ready_ = false;
1204 bool halted_ = false;
1205 bool held_ = false;
1206 bool unavailable_ = false; // logged once until a hedge instrument takes the residual again
1207 bool split_ = false; // a hedge cut to a [risk] limit was logged; cleared when flat
1208 bool working_ = false; // the residual passed Config::band and is hedged until flat
1209 // maker mode
1210 bool maker_open_ = false; // maker_id_ is open
1211 bool maker_cancel_ = false; // ... and its cancel is out
1212 bool cross_ = false; // taker_after: the next hedge is an IOC
1213 ClientOrderId maker_id_{};
1214 std::size_t maker_k_ = 0; // its hedge instrument
1215 std::int64_t maker_sent_ns_ = 0; // when it went out (taker_after)
1216 std::int64_t maker_move_ns_ = 0; // when it went out or was last cancelled (repeg)
1217 // de-risking
1218 bool blocked_ = false;
1219 bool derisking_ = false;
1220 bool derisk_open_ = false;
1221 bool derisk_stuck_ = false;
1222 std::int64_t blocked_ns_ = 0;
1223 std::int64_t next_derisk_ns_ = 0;
1224 ClientOrderId derisk_id_{};
1225};
1226
1227} // namespace fastmm
Definition config.hpp:502
bool add_hedge(InstrumentId id, Ratio tolerance) noexcept
Definition hedge_executor.hpp:197
std::size_t active() const noexcept
Definition hedge_executor.hpp:526
bool involves(VenueId v) const noexcept
A venue of any leg.
Definition hedge_executor.hpp:539
static constexpr bool fit_risk(const RiskHeadroom &h, const Instrument &inst, NewOrderRequest &r) noexcept
Cuts r to risk_room() when that is less and still an order the instrument takes (the lot,...
Definition hedge_executor.hpp:705
State state() const noexcept
Definition hedge_executor.hpp:522
void update(Ctx &ctx) noexcept
Looks at the positions and sends what they call for; the hooks above end here.
Definition hedge_executor.hpp:365
Qty residual(const Ctx &ctx) const noexcept
Sources plus hedges minus the target, base units.
Definition hedge_executor.hpp:548
bool is_leg(InstrumentId id) const noexcept
Definition hedge_executor.hpp:535
bool on_fill(Ctx &ctx, const Fill &fill) noexcept
A fill of any leg: the residual moved. False for another instrument.
Definition hedge_executor.hpp:271
static constexpr std::size_t kMaxSources
Definition hedge_executor.hpp:102
void on_timer(Ctx &ctx) noexcept
Definition hedge_executor.hpp:333
void restart() noexcept
Clears a halt, the benches and the failure counts; hedging resumes from the positions.
Definition hedge_executor.hpp:259
InstrumentId hedge_id(std::size_t i) const noexcept
Definition hedge_executor.hpp:525
bool ready() const noexcept
Definition hedge_executor.hpp:517
static constexpr bool works_orders
Maker mode looks its order up and cancels it (StrategyContext::order, cancel).
Definition hedge_executor.hpp:107
void set_config(const Config &cfg) noexcept
Parameters may change while running (on_params); the legs may not.
Definition hedge_executor.hpp:252
Status status(const Ctx &ctx) const noexcept
Definition hedge_executor.hpp:601
bool on_order_update(Ctx &ctx, const OmsUpdate &u) noexcept
The end of a hedge or de-risk order: counts a failure or holds, then looks again.
Definition hedge_executor.hpp:280
bool can_hedge(const Ctx &ctx) const noexcept
Some hedge instrument can take a hedge now, and hedging is not halted.
Definition hedge_executor.hpp:591
bool start(Ctx &ctx, const Config &cfg) noexcept
Checks the legs against the instrument table: each is configured, linear, used once,...
Definition hedge_executor.hpp:205
bool under_minimum(const Ctx &ctx, Qty residual) const noexcept
The residual rounds under the lot or min_qty of every hedge instrument: no hedge order can take it,...
Definition hedge_executor.hpp:560
static constexpr Qty to_base(const Instrument &inst, Qty contracts) noexcept
Contracts to base units and back (linear: qty * multiplier).
Definition hedge_executor.hpp:616
Qty target() const noexcept
Definition hedge_executor.hpp:527
static constexpr Qty risk_room(const RiskHeadroom &h, const Instrument &inst, Side side, Price price) noexcept
The largest order of side on inst at price that [risk] admits now: max_order_qty, max_order_notional ...
Definition hedge_executor.hpp:688
static constexpr std::string_view to_string(Reason r) noexcept
Definition hedge_executor.hpp:728
const Stats & stats() const noexcept
Definition hedge_executor.hpp:523
bool is_source(InstrumentId id) const noexcept
Definition hedge_executor.hpp:529
bool held() const noexcept
The last hedge the positions asked for fits no usable instrument's balance.
Definition hedge_executor.hpp:520
static constexpr std::size_t kMaxHedges
Definition hedge_executor.hpp:103
static bool uncertain(const OmsUpdate &u) noexcept
A terminal update whose outcome the venue did not report: the ack timeout cancelled an order the venu...
Definition hedge_executor.hpp:721
void reset() noexcept
Forgets the legs and every state but the stats. Call before adding legs in on_start.
Definition hedge_executor.hpp:185
std::size_t hedge_count() const noexcept
Definition hedge_executor.hpp:524
void set_target(Qty base) noexcept
The net base position the strategy wants to hold; the residual is measured from it.
Definition hedge_executor.hpp:257
bool on_balance(Ctx &ctx, const BalanceMsg &m) noexcept
A balance report of a leg's venue: a held hedge may fit now. False for another venue.
Definition hedge_executor.hpp:357
bool halted() const noexcept
Definition hedge_executor.hpp:518
Reason why(const Ctx &ctx, std::size_t i, std::int64_t now) const noexcept
Why hedge instrument i cannot take a hedge now (Reason::Usable: it can).
Definition hedge_executor.hpp:571
void on_connection(Ctx &, const ConnectionStateMsg &m) noexcept
Order channels (channel != 0) of the legs' venues.
Definition hedge_executor.hpp:341
bool on_book_ticker(Ctx &ctx, InstrumentId id, const BookTickerMsg &m) noexcept
A hedge instrument's book ticker: its touch, newer than the depth book's until the book updates.
Definition hedge_executor.hpp:322
bool derisking() const noexcept
Definition hedge_executor.hpp:521
State
What the last evaluation found.
Definition hedge_executor.hpp:155
@ Resting
a maker hedge rests at the touch
@ Holding
retry backoff or uncertain hold
@ Reconciling
a venue reconciles
@ Unavailable
no hedge instrument is usable
@ Waiting
the residual rounds under the hedge instrument's minimum
@ Halted
every hedge instrument failed max_failures times; restart() clears it
@ Flat
the residual is zero
@ InFlight
a hedge or de-risk order is open
@ Inside
the residual is inside Config::band
@ Idle
not started, or nothing evaluated yet
@ Held
no usable instrument's balance or margin covers the hedge
static constexpr std::size_t kMaxFailures
Definition hedge_executor.hpp:104
bool is_hedge(InstrumentId id) const noexcept
Definition hedge_executor.hpp:528
bool add_source(InstrumentId id) noexcept
Definition hedge_executor.hpp:192
static std::optional< NewOrderRequest > hedge_order(const Instrument &inst, Qty residual, Price best_bid, Price best_ask, Ratio tolerance, std::uint32_t tag) noexcept
The order on inst that brings residual (base units) back towards zero: an IOC of -residual in contrac...
Definition hedge_executor.hpp:629
Reason
Why a hedge instrument is not usable now.
Definition hedge_executor.hpp:170
void on_book(Ctx &ctx, InstrumentId id) noexcept
A hedge instrument's book: a new touch to price against.
Definition hedge_executor.hpp:315
static constexpr Qty to_contracts(const Instrument &inst, Qty base) noexcept
Definition hedge_executor.hpp:619
static constexpr Qty qty_within(const Instrument &inst, Price price, Notional cap) noexcept
The largest quantity of inst whose notional at price is at most cap, rounded down to the lot (zero wh...
Definition hedge_executor.hpp:673
void set_tolerance(std::size_t hedge, Ratio tolerance) noexcept
Definition hedge_executor.hpp:253
static std::optional< NewOrderRequest > maker_order(const Instrument &inst, Qty residual, Price bid, Price ask, std::uint32_t tag) noexcept
The maker hedge of residual on inst: a post-only limit of -residual in contracts, rounded down to the...
Definition hedge_executor.hpp:657
All engine enumerations.
Fixed<Tag>: int64 fixed point with a global 1e-8 scale (ADR-0001).
Strategy hooks (ADR-0012): the hook table, the compile-time checker and the Fill view.
Instrument: the single definition of a tradable contract (5.3 / 5.15).
Asynchronous logging (5.10).
#define FASTMM_LOG_WARN(fmt_str,...)
Definition log.hpp:393
#define FASTMM_LOG_INFO(fmt_str,...)
Definition log.hpp:391
#define FASTMM_LOG_ERROR(fmt_str,...)
Definition log.hpp:395
Event bus message structs (5.5).
Definition strategy.hpp:23
StrongId< struct ClientOrderTag, std::uint64_t, 0 > ClientOrderId
48-bit: session_epoch(16) << 32 | seq(32). 0 is never issued.
Definition strong_id.hpp:41
constexpr Duration milliseconds(std::int64_t v) noexcept
Definition time.hpp:38
constexpr bool is_pending(OrderState s) noexcept
Definition enums.hpp:93
constexpr std::int64_t kFixedScale
1e-8
Definition fixed_point.hpp:23
@ VenueReject
Venue-originated.
Side
Definition enums.hpp:12
Fixed< struct QtyTag > Qty
Definition fixed_point.hpp:333
Fixed< struct NotionalTag > Notional
Definition fixed_point.hpp:334
StrongId< struct InstrumentTag, std::uint32_t > InstrumentId
Dense index into the engine's instrument table.
Definition strong_id.hpp:38
FixedString< 16 > encode_cl_ord_id(ClientOrderId id) noexcept
Definition strong_id.hpp:77
Fixed< struct PriceTag > Price
Definition fixed_point.hpp:332
constexpr std::int64_t mul_raw(Fixed< A > a, Fixed< B > b) noexcept
Generic scaled multiply for fixed*fixed in one domain (e.g. qty * multiplier).
Definition fixed_point.hpp:367
Fixed< RatioTag > Ratio
A dimensionless factor: 1.0 == 1e8 raw, 1 bp == 10'000 raw, so 0.0001 bp is the smallest step.
Definition fixed_point.hpp:336
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.
RiskLimits: the pre-trade limits a session runs with ([risk] in the configuration),...
The account's holding of one asset on one venue (EventType::Balance), as the venue reports it at its ...
Definition messages.hpp:412
Definition messages.hpp:229
Definition messages.hpp:651
Definition time.hpp:22
std::int64_t ns
Definition time.hpp:23
constexpr std::int64_t millis() const noexcept
Definition time.hpp:29
One execution as a strategy sees it (on_fill).
Definition hooks.hpp:56
constexpr bool is_negative() const noexcept
Definition fixed_point.hpp:303
static constexpr Fixed max() noexcept
Definition fixed_point.hpp:165
constexpr Fixed abs() const noexcept
Definition fixed_point.hpp:304
static constexpr Fixed from_raw(std::int64_t r) noexcept
Definition fixed_point.hpp:155
constexpr bool is_zero() const noexcept
Definition fixed_point.hpp:301
std::int64_t raw
Definition fixed_point.hpp:152
constexpr bool is_positive() const noexcept
Definition fixed_point.hpp:302
static constexpr Fixed from_int(std::int64_t units) noexcept
Whole units, e.g. from_int(100) == 100.00000000.
Definition fixed_point.hpp:161
Duration stale
a hedge book older than this is unusable; 0: never
Definition hedge_executor.hpp:120
Duration failure_window
Definition hedge_executor.hpp:118
Notional band
Bands, quote currency at the hedge instrument's mid: hedge once the residual is worth band,...
Definition hedge_executor.hpp:128
Duration taker_after
Definition hedge_executor.hpp:136
Duration uncertain_hold
Definition hedge_executor.hpp:119
bool maker
Maker mode: a post-only order at the hedge's own touch instead of an IOC.
Definition hedge_executor.hpp:133
Qty derisk_step
base units per de-risk order; 0: the whole residual
Definition hedge_executor.hpp:123
Notional flat
Definition hedge_executor.hpp:129
int max_failures
within failure_window: bench, or halt on the last one
Definition hedge_executor.hpp:117
std::uint32_t tag
user_tag of hedge orders
Definition hedge_executor.hpp:114
Duration bench
how long a failing instrument sits out
Definition hedge_executor.hpp:121
std::uint32_t derisk_tag
user_tag of de-risk orders
Definition hedge_executor.hpp:115
Duration derisk_interval
Definition hedge_executor.hpp:124
Duration derisk_after
0: never de-risk
Definition hedge_executor.hpp:122
Notional resize
Definition hedge_executor.hpp:135
Duration repeg
Definition hedge_executor.hpp:134
Ratio derisk_tolerance
Definition hedge_executor.hpp:125
Duration retry
after a hedge that filled nothing
Definition hedge_executor.hpp:116
std::string_view name
log prefix
Definition hedge_executor.hpp:113
Definition hedge_executor.hpp:139
std::uint64_t failovers
hedging moved to a later instrument in the list
Definition hedge_executor.hpp:145
std::uint64_t hedges_sent
Definition hedge_executor.hpp:140
std::uint64_t benches
instruments benched after max_failures
Definition hedge_executor.hpp:146
std::uint64_t derisk_orders
Definition hedge_executor.hpp:148
std::uint64_t maker_moves
maker hedges cancelled to follow the touch or re-size
Definition hedge_executor.hpp:149
std::uint64_t halts
Definition hedge_executor.hpp:143
std::uint64_t hedges_held
episodes of a hedge no balance or margin could cover
Definition hedge_executor.hpp:144
std::uint64_t uncertain_ends
ended without the venue saying how
Definition hedge_executor.hpp:142
std::uint64_t maker_refused
maker hedges refused as crossing (post-only)
Definition hedge_executor.hpp:151
std::uint64_t derisk_episodes
Definition hedge_executor.hpp:147
std::uint64_t maker_crossed
maker hedges cancelled at taker_after for an IOC
Definition hedge_executor.hpp:150
std::uint64_t hedge_failures
ended with nothing filled, or refused by the engine
Definition hedge_executor.hpp:141
Definition hedge_executor.hpp:172
Timestamp hold_until
end of the last retry or uncertain hold
Definition hedge_executor.hpp:180
bool held
Definition hedge_executor.hpp:177
std::uint8_t active
index of the hedge instrument hedges go to
Definition hedge_executor.hpp:175
bool halted
Definition hedge_executor.hpp:178
bool in_flight
Definition hedge_executor.hpp:176
bool derisking
Definition hedge_executor.hpp:179
Qty residual
Definition hedge_executor.hpp:174
State state
Definition hedge_executor.hpp:173
Definition instrument.hpp:29
constexpr Qty round_qty(Qty q) const noexcept
Definition instrument.hpp:76
Qty min_qty
8
Definition instrument.hpp:49
VenueId venue
1
Definition instrument.hpp:43
Symbol symbol
21
Definition instrument.hpp:56
constexpr LimitOrder tag(std::uint32_t user_tag) const noexcept
user_tag: echoed in the order record.
Definition order.hpp:154
constexpr LimitOrder ioc() const noexcept
Definition order.hpp:147
constexpr LimitOrder post_only() const noexcept
Definition order.hpp:136
Definition order.hpp:105
Side side
Definition order.hpp:112
Price price
Definition order.hpp:117
static constexpr LimitOrder limit(InstrumentId instrument, Side side, Price price, Qty qty) noexcept
A GTC limit order, refined with the builder's methods: ctx.send(NewOrderRequest::limit(id,...
Definition order.hpp:174
InstrumentId instrument
Definition order.hpp:106
Qty qty
Definition order.hpp:118
Definition oms.hpp:83
Definition order.hpp:16
OrderState state
1
Definition order.hpp:36
TimeInForce tif
1 -> 64
Definition order.hpp:35
VenueOrderId venue_order_id
41 -> 49
Definition order.hpp:28
ClientOrderId cl_ord_id
8
Definition order.hpp:27
InstrumentId instrument
4 -> 60
Definition order.hpp:31
RejectReason reject_reason
1
Definition order.hpp:37
Qty cum_qty
8 -> 96
Definition order.hpp:43
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
std::int64_t ns
Definition time.hpp:46
constexpr bool valid() const noexcept
Definition time.hpp:55
Time primitives.
VenueHealth: per venue, how late its market data arrives and how long our orders take to be acknowled...