FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
oms.hpp
Go to the documentation of this file.
1#pragma once
2// Order management (5.8): a Pool<Order> + OpenHashMap<ClientOrderId, Handle> + a ring of
3// recently terminal ids used to classify late venue messages.
4//
5// State machine (terminal states free the slot and go to the recently-terminal ring):
6// submit -> PendingNew
7// ack PendingNew -> Live; PendingReplace -> Live/PartiallyFilled (replace ok)
8// reject PendingNew -> Rejected; PendingReplace -> back to previous working state
9// cancel request Live/PartiallyFilled -> PendingCancel
10// cancel ack any open -> Canceled (unsolicited if we did not ask); Filled when the
11// venue's cum_qty covers the order
12// cancel reject PendingCancel -> back; >3 rejects -> ReconcileNeeded;
13// VenueUnknownOrder -> Canceled
14// fill cum >= qty -> Filled, else PartiallyFilled (pending states keep pending)
15// expired any open -> Expired; Filled when the venue's cum_qty covers the order
16// A cum_qty a venue reports that no fill message covered (a cancel ack, an expiry or a
17// reconciliation snapshot) becomes OmsUpdate::missed_qty for the engine to book. That booking is an
18// estimate - the order's own price, no fee - so it is remembered here until an execution names it:
19// one from the venue's trade history (OrderFillMsg::kReplayed), or a live one that arrives after
20// the cum_qty covering it (its cum_qty - qty lies below the booked cum_qty; order and execution
21// topics are not ordered on every venue). The execution then corrects the price and the fee
22// (OmsUpdate::corrected_qty) instead of the quantity being counted twice. The estimate is kept with
23// the order itself - its pool slot while it is open, its recently-terminal record after - so it
24// lasts exactly as long as the OMS can still tell an execution of that order from a foreign one.
25// It is lost only with the order's terminal record, kRecentlyTerminal orders later; that is
26// reported (OmsUpdate::forgotten_qty, OmsStats::synthetic_forgotten), since an execution naming
27// it after that would be booked as new.
28// Races: fill after cancel ack -> LateFill (position still updated from the terminal record's
29// instrument and side; the record takes the fill's quantity, and a Canceled or Expired order the
30// fill completes becomes Filled, so the order's last update agrees with its fills); cancel-reject
31// after fill -> ignored; ack for unknown id -> CancelUnknown
32// (never leave an unknown live order); ack for an order reconciliation marked cancelled ->
33// CancelUnknown; duplicate exec_id -> Duplicate; duplicate ack -> Ignored (also for the original
34// id while a replace to a new id is pending: only the new id's ack completes the replace).
35// Reconciliation (per venue): a cancel or replace still in flight stays pending; orders sent after
36// the snapshot was requested (above the Begin's sent watermark) are not marked cancelled.
38#include "fastmm/core/config_macros.hpp"
39#include "fastmm/core/containers/bucket_bits.hpp"
40#include "fastmm/core/containers/open_hash_map.hpp"
41#include "fastmm/core/containers/pool.hpp"
42#include "fastmm/core/containers/recent_map.hpp"
43#include "fastmm/core/containers/ring_buffer.hpp"
44#include "fastmm/core/containers/static_vector.hpp"
45#include "fastmm/core/enums.hpp"
48#include "fastmm/core/order.hpp"
50
51#include <cstdint>
52#include <limits>
53#include <memory>
54#include <optional>
55
56namespace fastmm {
57
58inline constexpr std::size_t kMaxOpenOrders = 4096;
59inline constexpr std::size_t kRecentlyTerminal = 4096;
60// Executions the OMS remembers by the venue's id, so that one it is given again (a replay of the
61// venue's trade history reading back past rows it already had) is dropped as a duplicate. 4096 was
62// not enough: live, Binance spot replays re-sent executions 4,000 and more executions after the
63// private stream had reported them, naming no order, and each was booked a second time into the
64// position and the PnL. 64Ki executions is days of a busy market maker's fills and costs 1.6 MiB,
65// allocated with the OMS.
66inline constexpr std::size_t kExecMemory = std::size_t{1} << 16;
67// Client order ids per session: the wire form is 48 bits, epoch(16) << 32 | seq(32).
68inline constexpr std::uint64_t kMaxSeq = 0xFFFF'FFFFULL;
69
70enum class OmsAction : std::uint8_t {
71 None = 0,
72 Ignored, // message did not apply (duplicate ack, late cancel-reject, ...)
73 Duplicate, // duplicate exec_id
74 CancelUnknown, // ack/fill for an id we do not know: engine must cancel it
75 LateFill, // fill for a recently terminal order: position, and the terminal record's
76 // cum_qty and state (changed = true when they moved)
77 UnknownFill, // fill for a completely unknown id: update position, alert
78 ReconcileNeeded, // too many cancel rejects
79};
80
81struct OmsUpdate {
82 Order order{}; // snapshot after the transition; for a recently terminal id only the terminal
83 // record's fields (id, instrument, venue, side, state, price, qty, cum_qty);
84 // empty if unknown
85 Handle<Order> handle{}; // invalid once terminal (slot freed) or unknown
88 bool known = false; // the id mapped to an order (open or recently terminal)
89 bool changed = false; // state or quantities changed
90 bool terminal = false; // the order reached a terminal state in this update
91 // The venue (or the connector for it) refused the order's new or replace leg in this update: the
92 // order is Rejected, back to working at its old price, or cancelled by a cancel-then-new replace.
94 Qty fill_qty{}; // for fills
96 // Quantity the venue reports as filled that we never saw a fill message for (a private-stream
97 // outage covered by a cancel ack, an expiry or a reconciliation snapshot). The engine books it
98 // as a synthetic fill at the order's own price; see Engine::book_missed_fill.
100 // A cancel-replace to a new id completed: the order carries on under order.cl_ord_id and this
101 // one is gone. It never produces an update of its own (the OMS renames the record in place), so
102 // anything that tracks orders by id closes it here.
104 // Quantity that was still working when a reconciliation snapshot failed to mention the order.
105 // The venue does not say whether it was cancelled or filled, so nothing can be booked; it is
106 // reported so the engine can say the position may be wrong instead of assuming it is not.
108 // Part of a replayed execution (OrderFillMsg::kReplayed) whose quantity a synthetic fill already
109 // put in the position: the execution names what it was, so its price and its fee replace the
110 // estimate rather than the quantity being counted twice. `synthetic_px` is the price the estimate
111 // used. See Engine::on_fill and PositionTracker::correct_fill.
114 // An estimate no execution named whose order this update pushed out of the OMS's memory of
115 // recently terminal orders (another order than this update's): `forgotten_id` and the quantity
116 // still estimated. An execution the venue replays for it from now on cannot be told from a
117 // foreign one, and would be booked on top of the estimate.
120 // The order's times (Oms::times), and the pool slot it had: set on every update of an open
121 // order, the terminal one included (`handle` is invalid then, the slot already free).
126struct OmsStats {
127 std::uint32_t open = 0;
128 std::uint64_t submitted = 0;
129 std::uint64_t acked = 0;
130 std::uint64_t rejected = 0;
131 std::uint64_t canceled = 0;
132 std::uint64_t filled = 0;
133 std::uint64_t fills = 0;
134 std::uint64_t expired = 0;
135 std::uint64_t unknown_ids = 0;
136 std::uint64_t duplicates = 0;
137 std::uint64_t late_fills = 0;
138 std::uint64_t unsolicited_cancels = 0;
139 std::uint64_t missed_fills = 0; // cum_qty jumps a fill message never reported
140 // Missed fills a replayed execution later named, so their price and fee stopped being estimates.
141 std::uint64_t corrected_fills = 0;
142 // Orders holding an estimate no execution has named yet (a gauge): the position and the PnL
143 // include that much quantity at the orders' own prices, with no fee.
144 std::uint32_t synthetic_pending = 0;
145 // Estimates whose order left the OMS's memory (kRecentlyTerminal later terminal orders) before an
146 // execution named them: their price and fee stay estimates, and an execution for them would now
147 // be counted twice.
148 std::uint64_t synthetic_forgotten = 0;
149 std::uint64_t ack_timeouts = 0; // PendingNew orders swept by sweep_pending()
150 // Orders a reconciliation snapshot did not report that still had working quantity: the venue
151 // ended them and never said how, so the position may be short by up to that much.
152 std::uint64_t reconcile_unresolved = 0;
153};
155enum class OrderClass : std::uint8_t { Open, RecentlyTerminal, Unknown };
156
157class Oms {
158 public:
159 // `max_seq` is the highest client order id sequence this session may issue; only tests lower it
160 // from kMaxSeq (reaching it takes 4.3 billion orders).
161 explicit Oms(std::uint16_t session_epoch = 1, std::uint64_t max_seq = kMaxSeq) noexcept
162 : epoch_(session_epoch), max_seq_(max_seq) {
163 for (auto& per_inst : best_own_) per_inst[0] = per_inst[1] = Price{};
164 for (auto& per_inst : open_qty_) per_inst[0] = per_inst[1] = Qty{};
165 }
166 Oms(const Oms&) = delete;
167 Oms& operator=(const Oms&) = delete;
169 [[nodiscard]] std::uint16_t session_epoch() const noexcept { return epoch_; }
170 // An invalid id once the session's 32-bit sequence is used up: the wire form carries 48 bits
171 // (epoch 16 + seq 32), so reusing a sequence would repeat a ClientOrderId within the session and
172 // let a late venue message match the wrong order. The engine turns that into a kill switch.
173 [[nodiscard]] ClientOrderId next_cl_ord_id() noexcept {
174 if (FASTMM_UNLIKELY(seq_ >= max_seq_)) return ClientOrderId{};
175 return make_cl_ord_id(epoch_, static_cast<std::uint32_t>(++seq_));
176 }
177 // Client order ids left in this session.
178 [[nodiscard]] std::uint64_t ids_left() const noexcept { return max_seq_ - seq_; }
179 [[nodiscard]] const OmsStats& stats() const noexcept { return stats_; }
180 [[nodiscard]] std::uint32_t open_count() const noexcept { return stats_.open; }
181 [[nodiscard]] std::uint32_t open_count(InstrumentId id) const noexcept {
182 return open_per_inst_[id.value];
184 // Sum of leaves of open orders on (instrument, side): "in-flight same-side exposure".
185 [[nodiscard]] Qty open_qty(InstrumentId id, Side s) const noexcept {
186 return open_qty_[id.value][static_cast<std::size_t>(s)];
188 // Best price among our own open orders on (instrument, side); Price{} if none. For STP.
189 [[nodiscard]] Price best_own_px(InstrumentId id, Side s) const noexcept {
190 return best_own_[id.value][static_cast<std::size_t>(s)];
192
193 // ---- outbound ---------------------------------------------------------------------------
194
195 // `context`: the strategy's quote context of the order's side now (OrderTrail::context).
198 Timestamp now,
199 const QuoteContext* context = nullptr) noexcept {
200 if (FASTMM_UNLIKELY(req.instrument.value >= kMaxInstruments))
202 if (FASTMM_UNLIKELY(open_handle(id).valid())) return fail(RejectReason::DuplicateId);
203 const Handle<Order> h = pool_.allocate();
204 if (FASTMM_UNLIKELY(!h.valid())) return fail(RejectReason::PoolExhausted);
205 if (FASTMM_UNLIKELY(!add_open(id, h))) {
206 pool_.free(h);
208 }
209 by_inst_.set(InstBits::bucket(req.instrument.value), h.idx);
210 Order& o = pool_.get(h);
211 o = Order{};
212 o.cl_ord_id = id;
213 o.instrument = req.instrument;
214 o.venue = req.venue;
215 o.side = req.side;
216 o.type = req.type;
217 o.tif = req.tif;
218 o.flags = static_cast<std::uint8_t>((req.post_only ? Order::kPostOnly : 0) |
219 (req.reduce_only ? Order::kReduceOnly : 0));
221 o.price = req.price;
222 o.qty = req.qty;
223 o.created = now;
224 o.user_tag = req.user_tag;
225 OrderTrail& t = trails_[h.idx];
226 t = OrderTrail{};
227 t.times.sent = now;
228 t.placed = now;
229 t.placed_px = req.price;
230 if (context != nullptr) t.context = *context;
231 estimates_[h.idx] = Estimate{}; // terminate() moved the last order's to its record
232 ++stats_.submitted;
233 ++stats_.open;
234 ++open_per_inst_[o.instrument.value];
235 open_qty_[o.instrument.value][static_cast<std::size_t>(o.side)] += o.qty;
236 Price& best = best_own_[o.instrument.value][static_cast<std::size_t>(o.side)];
237 if (best.is_zero() || better(o.side, o.price, best)) best = o.price;
238 return h;
239 }
240
241 // `now`: the cancel's send time (OrderTrail::pending_sent).
243 if (!pool_.is_live(h)) return fail(RejectReason::UnknownOrder);
244 Order& o = pool_.get(h);
247 trails_[h.idx].pending_sent = now;
248 return {};
249 }
250
251 // Cancel of an order that is still waiting for its ack (the ack-timeout sweep only). A venue
252 // that never saw the order answers VenueUnknownOrder, and on_cancel_reject ends it.
253 Result<void, RejectReason> request_cancel_unacked(Handle<Order> h, Timestamp now = {}) noexcept {
254 if (!pool_.is_live(h)) return fail(RejectReason::UnknownOrder);
255 Order& o = pool_.get(h);
258 trails_[h.idx].pending_sent = now;
259 return {};
260 }
261
262 // new_id may equal the current id for venues that amend in place. `now`: the replace's send
263 // time, which becomes OrderTimes::sent once it is acknowledged; `context`: the side's quote
264 // context now, which becomes OrderTrail::context then.
265 Result<void, RejectReason> request_replace(Handle<Order> h,
267 Price px,
268 Qty qty,
269 Timestamp now = {},
270 const QuoteContext* context = nullptr) noexcept {
271 if (!pool_.is_live(h)) return fail(RejectReason::UnknownOrder);
272 Order& o = pool_.get(h);
274 if (new_id != o.cl_ord_id) {
275 if (open_handle(new_id).valid()) return fail(RejectReason::DuplicateId);
276 if (!add_open(new_id, h)) return fail(RejectReason::PoolExhausted);
277 }
278 o.pending_cl_ord_id = new_id;
279 o.pending_price = px;
280 o.pending_qty = qty;
282 OrderTrail& t = trails_[h.idx];
283 t.pending_sent = now;
284 t.pending_context = context != nullptr ? *context : QuoteContext{};
285 return {};
286 }
287
288 // ---- inbound ----------------------------------------------------------------------------
289
290 OmsUpdate on_ack(const OrderAckMsg& m) noexcept {
291 OmsUpdate u;
292 Handle<Order> h = lookup(m.cl_ord_id, u);
293 if (!h.valid()) {
294 if (!u.known) {
295 u.action = OmsAction::CancelUnknown; // a live order we do not know: cancel it
296 ++stats_.unknown_ids;
297 } else if (u.order.has(Order::kReconciled)) {
298 // Reconciliation took it for gone, yet the venue has it (the snapshot missed an order
299 // still in flight). Nothing tracks it any more: cancel it rather than leave it live.
300 u.action = OmsAction::CancelUnknown;
301 } else {
302 u.action = OmsAction::Ignored; // late ack for a terminal order
303 }
304 return u;
305 }
306 Order& o = pool_.get(h);
307 u.prev = o.state;
308 switch (o.state) {
311 o.venue_order_id = m.venue_order_id;
312 ++stats_.acked;
313 u.changed = true;
314 trails_[h.idx].times.venue_ack = m.hdr.exch_ts;
315 trails_[h.idx].times.local_ack = m.hdr.recv_ts;
316 break;
318 // Only the replacement's ack completes it (the same id for an in-place amend). An ack that
319 // repeats the current id while a replace to a new id is in flight is a duplicate of the
320 // original ack (Binance sends one from the WS API response and one from the user stream):
321 // applying it would take the replace for confirmed, leave the new id mapped after the order
322 // ends and let the new leg's ack read a freed slot while that order stays live untracked.
323 if (m.cl_ord_id == o.pending_cl_ord_id) {
324 const ClientOrderId old_id = o.cl_ord_id;
325 const bool rekey = o.pending_cl_ord_id != o.cl_ord_id;
326 // An in-place amend keeps the venue's order even when it is given a new client id
327 // (Binance Spot keepPriority), so the fills booked against it stay.
328 const bool new_venue_order = rekey && (m.flags & OrderAckMsg::kAmendedInPlace) == 0;
329 apply_replace(u, h, o, rekey, new_venue_order);
330 if (o.cl_ord_id != old_id) u.replaced_cl_ord_id = old_id;
331 o.venue_order_id = m.venue_order_id;
332 u.changed = true;
333 OrderTrail& t = trails_[h.idx];
334 t.times = OrderTimes{t.pending_sent, m.hdr.exch_ts, m.hdr.recv_ts};
337 ++t.amends;
338 } else {
339 u.action = OmsAction::Ignored;
340 }
341 break;
342 default:
343 u.action = OmsAction::Ignored; // duplicate ack
344 // A venue that answers twice (API response and user stream) may put its time on either.
345 if (m.cl_ord_id == o.cl_ord_id && !trails_[h.idx].times.venue_ack.valid())
346 trails_[h.idx].times.venue_ack = m.hdr.exch_ts;
347 break;
348 }
349 finish_update(u, h, o);
350 return u;
351 }
352
353 OmsUpdate on_reject(const OrderRejectMsg& m) noexcept {
354 OmsUpdate u;
355 Handle<Order> h = lookup(m.cl_ord_id, u);
356 if (!h.valid()) {
357 u.action = OmsAction::Ignored;
358 return u;
359 }
360 Order& o = pool_.get(h);
361 u.prev = o.state;
362 if (o.state == OrderState::PendingNew) {
363 o.reject_reason = m.reason;
364 u.refused = m.reason;
365 ++stats_.rejected;
366 terminate(u, h, o, OrderState::Rejected);
367 return u;
368 }
369 if (o.state == OrderState::PendingReplace && m.cl_ord_id == o.pending_cl_ord_id) {
370 // Replace failed. If the venue already cancelled the original (cancel-then-new
371 // style replace) the order is gone; otherwise it keeps working unchanged.
372 u.refused = m.reason;
374 clear_pending(o);
375 terminate(u, h, o, OrderState::Canceled);
376 return u;
377 }
378 clear_pending(o);
379 trails_[h.idx].pending_sent = Timestamp{};
381 u.changed = true;
382 finish_update(u, h, o);
383 return u;
384 }
385 u.action = OmsAction::Ignored;
386 finish_update(u, h, o);
387 return u;
388 }
389
391 OmsUpdate u;
392 Handle<Order> h = lookup(m.cl_ord_id, u);
393 if (!h.valid()) {
394 u.action = OmsAction::Ignored;
395 return u;
396 }
397 Order& o = pool_.get(h);
398 u.prev = o.state;
399 absorb_cum(h, o, m.cum_qty, u);
400 if (o.state == OrderState::PendingReplace && m.cl_ord_id == o.cl_ord_id) {
401 // Old leg of a cancel-then-new replace: wait for the new leg's ack/reject.
403 finish_update(u, h, o);
404 return u;
405 }
406 // The cancel raced a fill that finished the order: it is Filled, not Canceled.
407 if (o.cum_qty >= o.qty) {
408 ++stats_.filled;
409 terminate(u, h, o, OrderState::Filled);
410 return u;
411 }
414 ++stats_.unsolicited_cancels;
415 }
416 terminate(u, h, o, OrderState::Canceled);
417 return u;
418 }
419
421 OmsUpdate u;
422 Handle<Order> h = lookup(m.cl_ord_id, u);
423 if (!h.valid()) {
424 u.action = OmsAction::Ignored; // e.g. already filled: ignore
425 return u;
426 }
427 Order& o = pool_.get(h);
428 u.prev = o.state;
430 u.action = OmsAction::Ignored;
431 finish_update(u, h, o);
432 return u;
433 }
434 if (m.reason == RejectReason::VenueUnknownOrder) {
435 // The venue has no such order: it is gone (filled/cancelled elsewhere).
436 terminate(u, h, o, OrderState::Canceled);
437 return u;
438 }
440 trails_[h.idx].pending_sent = Timestamp{};
441 o.cancel_attempts = static_cast<std::uint8_t>(o.cancel_attempts + 1);
442 if (o.cancel_attempts > 3) u.action = OmsAction::ReconcileNeeded;
443 u.changed = true;
444 finish_update(u, h, o);
445 return u;
446 }
447
448 OmsUpdate on_fill(const OrderFillMsg& m) noexcept {
449 OmsUpdate u;
450 u.fill_qty = m.qty;
451 u.fill_px = m.price;
452 if (!m.exec_id.empty() && !remember_exec(m)) {
453 u.action = OmsAction::Duplicate;
454 ++stats_.duplicates;
455 return u;
456 }
457 Handle<Order> h = lookup(m.cl_ord_id, u);
458 // A replayed execution may be one the venue already counted into a cum_qty the engine booked as
459 // a synthetic fill. Taking that quantity out of the order's estimate here is what keeps it from
460 // being booked twice, whether the order is still open or recently terminal.
461 // A live execution can also arrive after the cum_qty that covers it: venues that publish order
462 // states and executions on separate topics (Bybit's `order` and `execution`) may end an order
463 // with its cumulative quantity first. The quantity was booked then as a synthetic fill; the
464 // part of this execution at or below that cum_qty (this execution spans cum_qty - qty to
465 // cum_qty on the venue's count) is the estimate being named, not new quantity.
466 // Without a cum_qty (Deribit's trades) only an order that has ended can tell: the venue's
467 // final cum_qty was all it will ever fill, so the execution is within the estimate.
468 const bool replayed = (m.flags & OrderFillMsg::kReplayed) != 0;
469 if (FASTMM_UNLIKELY(stats_.synthetic_pending != 0) && u.known) {
470 if (!replayed && m.cum_qty.is_positive()) {
471 const Qty booked = h.valid() ? pool_.get(h).cum_qty : u.order.cum_qty;
472 Qty covered = booked - (m.cum_qty - m.qty);
473 if (covered > m.qty) covered = m.qty;
474 if (covered.is_positive()) take_synthetic(h, m.cl_ord_id, covered, u);
475 } else if (replayed || !h.valid()) {
476 take_synthetic(h, m.cl_ord_id, m.qty, u);
477 }
478 }
479 ++stats_.fills;
480 if (!h.valid()) {
481 if (u.known) {
482 u.action = OmsAction::LateFill;
483 ++stats_.late_fills;
484 late_fill(m, u);
485 } else {
486 u.action = OmsAction::UnknownFill;
487 ++stats_.unknown_ids;
488 }
489 return u;
490 }
491 Order& o = pool_.get(h);
492 u.prev = o.state;
493 const Qty before = o.cum_qty;
494 // Only the part the position does not already hold moves the order forward: a replayed
495 // execution carries no cumulative quantity of its own.
496 const Qty fresh = m.qty - u.corrected_qty;
497 Qty cum = m.cum_qty.is_positive() ? m.cum_qty : o.cum_qty + fresh;
498 if (cum < before) cum = before; // out-of-order cum: never go backwards
499 if (cum > o.qty) cum = o.qty;
500 open_qty_[o.instrument.value][static_cast<std::size_t>(o.side)] -= (cum - before);
501 o.cum_qty = cum;
502 if (o.venue_order_id.empty()) o.venue_order_id = m.venue_order_id;
503 u.changed = true;
504 if (o.cum_qty >= o.qty) {
505 ++stats_.filled;
506 terminate(u, h, o, OrderState::Filled);
507 return u;
508 }
511 finish_update(u, h, o);
512 return u;
513 }
514
516 OmsUpdate u;
517 Handle<Order> h = lookup(m.cl_ord_id, u);
518 if (!h.valid()) {
519 u.action = OmsAction::Ignored;
520 return u;
521 }
522 Order& o = pool_.get(h);
523 u.prev = o.state;
524 absorb_cum(h, o, m.cum_qty, u);
525 if (o.cum_qty >= o.qty) { // an IOC that filled completely is Filled, not Expired
526 ++stats_.filled;
527 terminate(u, h, o, OrderState::Filled);
528 return u;
529 }
530 ++stats_.expired;
531 terminate(u, h, o, OrderState::Expired);
532 return u;
533 }
534
535 // ---- reconciliation ---------------------------------------------------------------------
536
537 // Starts reconciling `venue`'s orders (an invalid venue: every venue). `sent_watermark` is the
538 // highest id the venue had sent when it requested the snapshot: orders above it cannot be in the
539 // snapshot, and reconcile_end() leaves them alone. Without it every unreported order ends.
541 std::optional<ClientOrderId> sent_watermark = std::nullopt) noexcept {
542 ReconcileScope& sc = recon_scope_[venue.value];
543 sc.bounded = sent_watermark.has_value();
544 sc.watermark = sent_watermark.value_or(ClientOrderId{});
545 pool_.for_each([&](Handle<Order>, Order& o) {
546 if (in_scope(o, venue)) o.flags &= static_cast<std::uint8_t>(~Order::kSeenInReconcile);
547 });
548 }
549 // Venue reports an open order. Unknown -> CancelUnknown (engine cancels by venue id).
550 OmsUpdate reconcile_open_order(const ReconcileMsg& m) noexcept {
551 OmsUpdate u;
552 Handle<Order> h = lookup(m.cl_ord_id, u);
553 if (!h.valid()) {
554 u.action = OmsAction::CancelUnknown;
555 ++stats_.unknown_ids;
556 return u;
557 }
558 Order& o = pool_.get(h);
559 u.prev = o.state;
561 if (!o.venue_order_id.empty() || !m.venue_order_id.empty()) o.venue_order_id = m.venue_order_id;
562 absorb_cum(h, o, m.cum_qty, u);
563 // The venue has it, so a new order was accepted. A cancel or replace is left pending: its ack
564 // or reject is still on the way and settles the order (clearing it made that cancel ack look
565 // unsolicited while the quote manager kept the order as a working quote).
566 if (o.state == OrderState::PendingNew) {
568 u.changed = true;
569 }
570 finish_update(u, h, o);
571 return u;
572 }
573 // Every open order of `venue` (invalid: every venue) the snapshot did not report is marked
574 // Canceled, except orders sent after the snapshot was requested (see reconcile_begin).
575 // F(const OmsUpdate&) runs after each order ends and outside the pool iteration, so it may place
576 // or cancel orders.
577 template <class F>
578 void reconcile_end(F&& f, VenueId venue = VenueId::invalid()) noexcept {
579 const ReconcileScope& sc = recon_scope_[venue.value];
580 StaticVector<Handle<Order>, kMaxOpenOrders> unseen;
581 pool_.for_each([&](Handle<Order> h, const Order& o) {
582 if (!in_scope(o, venue) || o.has(Order::kSeenInReconcile)) return;
583 if (sc.bounded && o.cl_ord_id.value > sc.watermark.value) return; // not sent yet
584 static_cast<void>(unseen.push_back(h));
585 });
586 for (const Handle<Order> h : unseen) {
587 if (!pool_.is_live(h)) continue;
588 Order& o = pool_.get(h);
589 OmsUpdate u;
590 u.prev = o.state;
591 u.known = true;
593 // Working quantity nobody accounted for: the snapshot proves the order is over, not how it
594 // ended. Treating it as cancelled is a guess, so report it instead of hiding it.
595 if (o.leaves_qty().is_positive()) {
596 u.unresolved_qty = o.leaves_qty();
597 ++stats_.reconcile_unresolved;
598 }
599 terminate(u, h, o, OrderState::Canceled, /*by_reconcile=*/true);
600 f(u);
601 }
602 }
603
604 // ---- ack timeout ------------------------------------------------------------------------
605
606 // Orders still PendingNew `timeout` after they were submitted: the request or its ack was lost,
607 // and nothing else ever frees them. They hold a pool slot, a max_open_orders slot and same-side
608 // open quantity that feeds max_position, so the engine force-cancels them (the venue may know
609 // the order even though we never saw its ack). F(Handle<Order>, const Order&) runs outside the
610 // pool iteration, so it may send. Returns the number reported.
611 template <class F>
612 std::size_t sweep_pending(Timestamp now, Duration timeout, F&& f) noexcept {
613 if (timeout.ns <= 0) return 0;
614 StaticVector<Handle<Order>, kMaxOpenOrders> stale;
615 pool_.for_each([&](Handle<Order> h, const Order& o) {
616 if (o.state != OrderState::PendingNew || !o.created.valid()) return;
617 if (now - o.created < timeout) return;
618 static_cast<void>(stale.push_back(h));
619 });
620 for (const Handle<Order> h : stale) {
621 if (!pool_.is_live(h)) continue;
622 ++stats_.ack_timeouts;
623 f(h, pool_.get(h));
624 }
625 return stale.size();
626 }
628 // ---- queries ----------------------------------------------------------------------------
630 [[nodiscard]] const Order& get(Handle<Order> h) const noexcept { return pool_.get(h); }
631 [[nodiscard]] Order& get(Handle<Order> h) noexcept { return pool_.get(h); }
632 [[nodiscard]] bool is_live(Handle<Order> h) const noexcept { return pool_.is_live(h); }
633 // Send and ack times of an open order.
634 [[nodiscard]] const OrderTimes& times(Handle<Order> h) const noexcept {
635 return trails_[h.idx].times;
637 // How the order `id` names got where it is: an open order's (its own id or a pending replace's),
638 // else a recently terminal one's as it ended; nullptr for an id the OMS does not remember.
639 [[nodiscard]] const OrderTrail* trail(ClientOrderId id) const noexcept {
640 const std::uint32_t* v = ids_.find(id);
641 if (v == nullptr) return nullptr;
642 if ((*v & kTerminalRef) == 0) return &trails_[*v];
643 const std::uint64_t pos = terminal_pos(id);
644 if (recently_terminal_.at_pos(pos) == nullptr) return nullptr;
645 return &terminal_trails_[pos & (kRecentlyTerminal - 1)];
646 }
647 [[nodiscard]] Handle<Order> find(ClientOrderId id) const noexcept { return open_handle(id); }
648 [[nodiscard]] OrderClass classify(ClientOrderId id) const noexcept {
649 if (open_handle(id).valid()) return OrderClass::Open;
650 if (find_terminal(id) != nullptr) return OrderClass::RecentlyTerminal;
651 return OrderClass::Unknown;
653 // Ascending handle order (deterministic). F(Handle<Order>, const Order&).
654 template <class F>
655 void for_each_open_order(F&& f) const noexcept {
656 pool_.for_each([&](Handle<Order> h, const Order& o) { f(h, o); });
657 }
658 template <class F>
659 void for_each_open_order(InstrumentId id, F&& f) const noexcept {
660 by_inst_.for_each(InstBits::bucket(id.value), [&](std::uint32_t idx) {
661 const Order& o = pool_.get(Handle<Order>{idx});
662 if (o.instrument == id) f(Handle<Order>{idx}, o);
663 });
664 }
665 void warm_up() noexcept { pool_.warm_up(); }
666
667 private:
668 // Quantity booked at `price` because a venue message reported it as cumulative and no execution
669 // ever named it (Engine::book_missed_fill). It stays with the order until an execution does.
670 struct Estimate {
671 Qty qty;
672 Price price;
673 };
674 struct TerminalRecord {
675 ClientOrderId cl_ord_id;
676 Price price;
677 Qty qty;
678 Qty cum_qty;
679 InstrumentId instrument;
680 VenueId venue;
681 OrderState state;
682 Side side;
683 bool by_reconcile; // marked Canceled by reconcile_end(), not reported by the venue
684 Estimate estimate; // the order's estimate no execution has named yet
685 };
686 struct ReconcileScope {
687 ClientOrderId watermark{};
688 bool bounded = false;
689 };
690
691 [[nodiscard]] static bool in_scope(const Order& o, VenueId venue) noexcept {
692 return !venue.valid() || o.venue == venue;
693 }
694
695 // A venue message carries more cumulative quantity than the fills we booked: the difference
696 // traded while we were not listening. Advance cum_qty (and the open-quantity accounting) and
697 // report the difference so the caller can book it; without that the position, the PnL and the
698 // max-loss budget silently lose those fills.
699 void absorb_cum(Handle<Order> h, Order& o, Qty reported, OmsUpdate& u) noexcept {
700 Qty cum = reported;
701 if (cum > o.qty) cum = o.qty;
702 if (cum <= o.cum_qty) return;
703 const Qty diff = cum - o.cum_qty;
704 open_qty_[o.instrument.value][static_cast<std::size_t>(o.side)] -= diff;
705 o.cum_qty = cum;
706 u.missed_qty += diff;
707 u.changed = true;
708 ++stats_.missed_fills;
709 note_synthetic(estimates_[h.idx], diff, o.price);
710 }
711
712 // ---- synthetic fills waiting to be named ------------------------------------------------
713
714 // The engine is about to book `qty` at `px` without knowing what it really traded at. Remember
715 // it with the order so a later execution corrects it instead of adding it again. No order holds
716 // one in normal operation (synthetic_pending is 0), which is the only test on_fill pays for this.
717 void note_synthetic(Estimate& e, Qty qty, Price px) noexcept {
718 if (!e.qty.is_positive()) ++stats_.synthetic_pending;
719 e.qty += qty;
720 e.price = px;
721 }
722
723 // Takes up to `qty` of the order's outstanding estimate into `u`: the open order `h`, else the
724 // recently terminal order `id`.
725 void take_synthetic(Handle<Order> h, ClientOrderId id, Qty qty, OmsUpdate& u) noexcept {
726 Estimate* e = nullptr;
727 if (h.valid()) {
728 e = &estimates_[h.idx];
729 } else if (TerminalRecord* r = find_terminal(id); r != nullptr) {
730 e = &r->estimate;
731 }
732 if (e == nullptr || !e->qty.is_positive()) return;
733 u.corrected_qty = qty < e->qty ? qty : e->qty;
734 u.synthetic_px = e->price;
735 e->qty -= u.corrected_qty;
736 ++stats_.corrected_fills;
737 if (!e->qty.is_positive()) {
738 *e = Estimate{};
739 --stats_.synthetic_pending;
740 }
741 }
742
743 // ---- ids_ -------------------------------------------------------------------------------
744
745 // The pool slot of the open order `id` names (its own id or a pending replace's).
746 [[nodiscard]] Handle<Order> open_handle(ClientOrderId id) const noexcept {
747 const std::uint32_t* v = ids_.find(id);
748 return v == nullptr || (*v & kTerminalRef) != 0 ? Handle<Order>{} : Handle<Order>{*v};
749 }
750 // Maps `id` to the open order `h`, over a terminal record the id may still name. False when the
751 // map is full.
752 [[nodiscard]] bool add_open(ClientOrderId id, Handle<Order> h) noexcept {
753 return ids_.assign(id, h.idx) != nullptr;
754 }
755 // Unmaps `id` if it names an open order (not if it already names its terminal record).
756 void drop_open(ClientOrderId id) noexcept {
757 const std::uint32_t* v = ids_.find(id);
758 if (v != nullptr && (*v & kTerminalRef) == 0) ids_.erase(id);
759 }
760 [[nodiscard]] static constexpr std::uint32_t terminal_ref(std::uint64_t pos) noexcept {
761 return kTerminalRef | static_cast<std::uint32_t>(pos & (kRecentlyTerminal - 1));
762 }
763 // The ring position of the newest terminal record of `id`: next_pos(), where at_pos() finds
764 // nothing, when `id` names none.
765 [[nodiscard]] std::uint64_t terminal_pos(ClientOrderId id) const noexcept {
766 const std::uint32_t* v = ids_.find(id);
767 if (v == nullptr || (*v & kTerminalRef) == 0) return recently_terminal_.next_pos();
768 const std::uint64_t head = recently_terminal_.head_pos();
769 return head + ((*v - head) & (kRecentlyTerminal - 1));
770 }
771 // The newest terminal record of `id`: an id the OMS never had (another client's order on a
772 // shared account) costs one hash probe, not a walk of the ring.
773 [[nodiscard]] const TerminalRecord* find_terminal(ClientOrderId id) const noexcept {
774 return recently_terminal_.at_pos(terminal_pos(id));
775 }
776 [[nodiscard]] TerminalRecord* find_terminal(ClientOrderId id) noexcept {
777 return recently_terminal_.at_pos(terminal_pos(id));
778 }
779
780 // Adds `r` to the recently terminal orders. The oldest one leaves when they are full, and with it
781 // the last means of telling an execution of that order from a foreign one: an estimate it still
782 // held is reported in `u` rather than dropped without a trace.
783 void remember_terminal(const TerminalRecord& r, const OrderTrail& trail, OmsUpdate& u) noexcept {
784 if (recently_terminal_.full()) {
785 const TerminalRecord& gone = recently_terminal_.front();
786 if (FASTMM_UNLIKELY(gone.estimate.qty.is_positive())) {
787 u.forgotten_qty = gone.estimate.qty;
788 u.forgotten_id = gone.cl_ord_id;
789 ++stats_.synthetic_forgotten;
790 --stats_.synthetic_pending;
791 }
792 // An id names its newest record: unmap it only if that is the one leaving.
793 const std::uint32_t* v = ids_.find(gone.cl_ord_id);
794 if (v != nullptr && *v == terminal_ref(recently_terminal_.head_pos()))
795 ids_.erase(gone.cl_ord_id);
796 }
797 // The id that named the open order names its terminal record from now on.
798 static_cast<void>(ids_.assign(r.cl_ord_id, terminal_ref(recently_terminal_.next_pos())));
799 terminal_trails_[recently_terminal_.next_pos() & (kRecentlyTerminal - 1)] = trail;
800 recently_terminal_.push(r);
801 }
802
803 // A fill for an order that already ended: a cancel ack (or a cancel reject for an order the venue
804 // no longer has) overtook the execution. The terminal record takes the quantity, so a later
805 // duplicate or replay of the order reads the right cum_qty, and an order the fill completes is
806 // Filled, not Canceled. u.changed tells the engine to write the corrected order.
807 void late_fill(const OrderFillMsg& m, OmsUpdate& u) noexcept {
808 TerminalRecord* r = find_terminal(m.cl_ord_id);
809 if (r == nullptr) return;
810 u.prev = r->state;
811 const Qty fresh = m.qty - u.corrected_qty;
812 Qty cum = m.cum_qty.is_positive() ? m.cum_qty : r->cum_qty + fresh;
813 if (cum > r->qty) cum = r->qty;
814 if (cum <= r->cum_qty) return;
815 r->cum_qty = cum;
816 if (cum >= r->qty && (r->state == OrderState::Canceled || r->state == OrderState::Expired)) {
817 r->state = OrderState::Filled;
818 ++stats_.filled;
819 }
820 u.order.cum_qty = r->cum_qty;
821 u.order.state = r->state;
822 u.changed = true;
823 }
824
825 // Finds an open order; sets u.known if the id is open or recently terminal.
826 Handle<Order> lookup(ClientOrderId id, OmsUpdate& u) noexcept {
827 const std::uint32_t* v = ids_.find(id);
828 if (v == nullptr) return Handle<Order>{};
829 if ((*v & kTerminalRef) == 0) {
830 u.known = true;
831 u.handle = Handle<Order>{*v};
832 return u.handle;
833 }
834 const TerminalRecord* r = find_terminal(id);
835 if (r != nullptr) {
836 // The slot is gone; a late fill still needs to know what it was for.
837 u.known = true;
838 u.order.cl_ord_id = r->cl_ord_id;
839 u.order.instrument = r->instrument;
840 u.order.venue = r->venue;
841 u.order.side = r->side;
842 u.order.state = r->state;
843 u.order.price = r->price;
844 u.order.qty = r->qty;
845 u.order.cum_qty = r->cum_qty;
846 if (r->by_reconcile) u.order.flags |= Order::kReconciled;
847 }
848 return Handle<Order>{};
849 }
850
851 void finish_update(OmsUpdate& u, Handle<Order> h, const Order& o) noexcept {
852 u.order = o;
853 u.handle = h;
854 u.times = trails_[h.idx].times;
855 u.slot = h;
856 }
857
858 // `rekey`: the replacement carries a new client id. `new_venue_order`: it is a different order
859 // on the venue (cancel-replace), so its cumulative quantity starts at zero; an in-place amend
860 // rekeys without that.
861 void apply_replace(
862 OmsUpdate& u, Handle<Order> h, Order& o, bool rekey, bool new_venue_order) noexcept {
863 const std::size_t s = static_cast<std::size_t>(o.side);
864 Qty& open = open_qty_[o.instrument.value][s];
865 open -= o.leaves_qty();
866 Estimate& e = estimates_[h.idx];
867 if (rekey && new_venue_order && FASTMM_UNLIKELY(e.qty.is_positive())) {
868 // The old leg ended with quantity booked as an estimate (its cancel ack reported a cum_qty no
869 // fill covered), and its executions still name its id. It keeps a terminal record, like any
870 // ended order, so that they correct the estimate rather than add to it; the new leg starts
871 // with none.
872 const OrderState end = o.cum_qty >= o.qty ? OrderState::Filled : OrderState::Canceled;
873 remember_terminal(
874 TerminalRecord{
875 o.cl_ord_id, o.price, o.qty, o.cum_qty, o.instrument, o.venue, end, o.side, false, e},
876 trails_[h.idx],
877 u);
878 e = Estimate{};
879 }
880 if (rekey) {
881 drop_open(o.cl_ord_id);
882 o.cl_ord_id = o.pending_cl_ord_id;
883 }
884 if (new_venue_order) o.cum_qty = Qty{};
885 const Price old_px = o.price;
886 o.price = o.pending_price;
887 o.qty = o.pending_qty;
888 if (o.cum_qty > o.qty) o.cum_qty = o.qty;
889 open += o.leaves_qty();
890 o.pending_cl_ord_id = ClientOrderId{};
891 o.pending_price = Price{};
892 o.pending_qty = Qty{};
893 o.flags &= static_cast<std::uint8_t>(~Order::kReplaceOldCanceled);
894 o.state = o.cum_qty.is_zero() ? OrderState::Live : OrderState::PartiallyFilled;
895 Price& best = best_own_[o.instrument.value][s];
896 if (best.is_zero() || better(o.side, o.price, best)) {
897 best = o.price;
898 } else if (old_px == best) {
899 recompute_best_own(o.instrument, o.side);
900 }
901 }
902 void clear_pending(Order& o) noexcept {
903 if (o.pending_cl_ord_id.valid() && o.pending_cl_ord_id != o.cl_ord_id)
904 drop_open(o.pending_cl_ord_id);
905 o.pending_cl_ord_id = ClientOrderId{};
906 o.pending_price = Price{};
907 o.pending_qty = Qty{};
908 o.flags &= static_cast<std::uint8_t>(~Order::kReplaceOldCanceled);
909 }
910
911 void terminate(OmsUpdate& u,
912 Handle<Order> h,
913 Order& o,
914 OrderState final_state,
915 bool by_reconcile = false) noexcept {
916 o.state = final_state;
917 if (final_state == OrderState::Canceled) ++stats_.canceled;
918 --stats_.open;
919 --open_per_inst_[o.instrument.value];
920 const std::size_t s = static_cast<std::size_t>(o.side);
921 open_qty_[o.instrument.value][s] -= o.leaves_qty();
922 if (o.pending_cl_ord_id.valid() && o.pending_cl_ord_id != o.cl_ord_id)
923 drop_open(o.pending_cl_ord_id);
924 // The estimate goes with the order into its terminal record, which its id names from now on:
925 // executions of it are told from foreign ones for as long as that record lasts.
926 remember_terminal(TerminalRecord{o.cl_ord_id,
927 o.price,
928 o.qty,
929 o.cum_qty,
930 o.instrument,
931 o.venue,
932 final_state,
933 o.side,
934 by_reconcile,
935 estimates_[h.idx]},
936 trails_[h.idx],
937 u);
938 estimates_[h.idx] = Estimate{};
939 u.order = o;
940 u.handle = Handle<Order>{};
941 u.times = trails_[h.idx].times;
942 u.slot = h;
943 u.changed = true;
944 u.terminal = true;
945 const InstrumentId inst = o.instrument;
946 const Side side = o.side;
947 const Price px = o.price;
948 by_inst_.clear(InstBits::bucket(inst.value), h.idx);
949 pool_.free(h);
950 if (px == best_own_[inst.value][s]) recompute_best_own(inst, side);
951 }
952
953 // Scans the instrument's live orders (by_inst_), not every live order.
954 void recompute_best_own(InstrumentId inst, Side side) noexcept {
955 Price best{};
956 by_inst_.for_each(InstBits::bucket(inst.value), [&](std::uint32_t idx) {
957 const Order& o = pool_.get(Handle<Order>{idx});
958 if (o.side != side || o.instrument != inst) return;
959 if (best.is_zero() || better(side, o.price, best)) best = o.price;
960 });
961 best_own_[inst.value][static_cast<std::size_t>(side)] = best;
962 }
963
964 // An execution is what the venue says it is: its id on that instrument and side (the two halves
965 // of a self-trade share an id). Not the order it names: the private stream names it and a
966 // replayed trade history may not (a venue order id the connector no longer maps), and keying on
967 // the order booked such an execution twice.
968 bool remember_exec(const OrderFillMsg& m) noexcept {
969 const std::uint64_t key = m.exec_id.hash() ^
970 (static_cast<std::uint64_t>(m.hdr.instrument.value) << 1U) ^
971 (static_cast<std::uint64_t>(m.side) * 0x9E3779B97F4A7C15ULL);
972 return exec_seen_.assign(key, 1);
973 }
974
975 std::uint16_t epoch_;
976 std::uint64_t max_seq_;
977 std::uint64_t seq_ = 0; // 64-bit so the comparison with max_seq_ cannot itself wrap
978 OmsStats stats_{};
979 Pool<Order, kMaxOpenOrders> pool_;
980 // The pool slots of each instrument's live orders, for for_each_open_order(id) in slot order and
981 // recompute_best_own.
982 using InstBits = BucketBits<kMaxOpenOrders, kMaxInstruments>;
983 InstBits by_inst_;
984 // Each open order's ids (its own and a pending replace's) to its pool slot, and each recently
985 // terminal order's id to its newest record in recently_terminal_ (kTerminalRef | ring slot). An
986 // order that ends keeps its entry, which names the record from then on, so terminate() moves no
987 // id between maps; the record leaving the ring takes the entry out.
988 static constexpr std::uint32_t kTerminalRef = 1U << 31;
989 static_assert(kMaxOpenOrders < kTerminalRef && kRecentlyTerminal <= kTerminalRef);
990 OpenHashMap<ClientOrderId, std::uint32_t, kMaxOpenOrders * 4> ids_;
991 RingBuffer<TerminalRecord, kRecentlyTerminal> recently_terminal_;
992 RecentMap<std::uint64_t, std::uint8_t, kExecMemory> exec_seen_;
993 Price best_own_[kMaxInstruments][2];
994 Qty open_qty_[kMaxInstruments][2];
995 std::uint32_t open_per_inst_[kMaxInstruments] = {};
996 ReconcileScope recon_scope_[std::numeric_limits<VenueId::rep_type>::max() + 1U] = {};
997 // OrderTrail by pool slot, apart from Order so the order record keeps its 128-byte layout, and by
998 // recently_terminal_ ring slot for the orders that ended (on the heap: the OMS is large already).
999 std::unique_ptr<OrderTrail[]> trails_ = std::make_unique<OrderTrail[]>(kMaxOpenOrders);
1000 std::unique_ptr<OrderTrail[]> terminal_trails_ =
1001 std::make_unique<OrderTrail[]>(kRecentlyTerminal);
1002 // Each open order's estimate (absorb_cum), by pool slot; terminate() moves it to the order's
1003 // terminal record.
1004 std::unique_ptr<Estimate[]> estimates_ = std::make_unique<Estimate[]>(kMaxOpenOrders);
1005};
1006
1007} // namespace fastmm
BookView: the read interface every book implementation (L2Book, L3Book::to_l2 view,...
Definition oms.hpp:159
Result< void, RejectReason > request_replace(Handle< Order > h, ClientOrderId new_id, Price px, Qty qty, Timestamp now={}, const QuoteContext *context=nullptr) noexcept
new_id may equal the current id for venues that amend in place.
Definition oms.hpp:266
void reconcile_begin(VenueId venue=VenueId::invalid(), std::optional< ClientOrderId > sent_watermark=std::nullopt) noexcept
Starts reconciling venue's orders (an invalid venue: every venue).
Definition oms.hpp:539
const OrderTimes & times(Handle< Order > h) const noexcept
Send and ack times of an open order.
Definition oms.hpp:631
std::size_t sweep_pending(Timestamp now, Duration timeout, F &&f) noexcept
Orders still PendingNew timeout after they were submitted: the request or its ack was lost,...
Definition oms.hpp:610
Result< void, RejectReason > request_cancel_unacked(Handle< Order > h, Timestamp now={}) noexcept
Cancel of an order that is still waiting for its ack (the ack-timeout sweep only).
Definition oms.hpp:254
OrderClass classify(ClientOrderId id) const noexcept
Definition oms.hpp:645
std::uint64_t ids_left() const noexcept
Client order ids left in this session.
Definition oms.hpp:180
OmsUpdate on_ack(const OrderAckMsg &m) noexcept
Definition oms.hpp:290
Price best_own_px(InstrumentId id, Side s) const noexcept
Best price among our own open orders on (instrument, side); Price{} if none. For STP.
Definition oms.hpp:191
void reconcile_end(F &&f, VenueId venue=VenueId::invalid()) noexcept
Every open order of venue (invalid: every venue) the snapshot did not report is marked Canceled,...
Definition oms.hpp:577
Qty open_qty(InstrumentId id, Side s) const noexcept
Sum of leaves of open orders on (instrument, side): "in-flight same-side exposure".
Definition oms.hpp:187
OmsUpdate on_expired(const OrderExpiredMsg &m) noexcept
Definition oms.hpp:515
OmsUpdate on_reject(const OrderRejectMsg &m) noexcept
Definition oms.hpp:353
Oms & operator=(const Oms &)=delete
OmsUpdate on_fill(const OrderFillMsg &m) noexcept
Definition oms.hpp:448
bool is_live(Handle< Order > h) const noexcept
Definition oms.hpp:629
std::uint16_t session_epoch() const noexcept
Definition oms.hpp:171
ClientOrderId next_cl_ord_id() noexcept
An invalid id once the session's 32-bit sequence is used up: the wire form carries 48 bits (epoch 16 ...
Definition oms.hpp:175
OmsUpdate on_cancel_ack(const OrderCancelAckMsg &m) noexcept
Definition oms.hpp:390
void warm_up() noexcept
Definition oms.hpp:662
OmsUpdate on_cancel_reject(const OrderCancelRejectMsg &m) noexcept
Definition oms.hpp:420
OmsUpdate reconcile_open_order(const ReconcileMsg &m) noexcept
Venue reports an open order. Unknown -> CancelUnknown (engine cancels by venue id).
Definition oms.hpp:549
Handle< Order > find(ClientOrderId id) const noexcept
Definition oms.hpp:644
Result< Handle< Order >, RejectReason > submit(const NewOrderRequest &req, ClientOrderId id, Timestamp now, const QuoteContext *context=nullptr) noexcept
context: the strategy's quote context of the order's side now (OrderTrail::context).
Definition oms.hpp:197
const OmsStats & stats() const noexcept
Definition oms.hpp:181
Result< void, RejectReason > request_cancel(Handle< Order > h, Timestamp now={}) noexcept
now: the cancel's send time (OrderTrail::pending_sent).
Definition oms.hpp:243
void for_each_open_order(F &&f) const noexcept
Ascending handle order (deterministic). F(Handle<Order>, const Order&).
Definition oms.hpp:652
std::uint32_t open_count() const noexcept
Definition oms.hpp:182
const Order & get(Handle< Order > h) const noexcept
Definition oms.hpp:627
const OrderTrail * trail(ClientOrderId id) const noexcept
How the order id names got where it is: an open order's (its own id or a pending replace's),...
Definition oms.hpp:636
Definition result.hpp:30
Minimal expected<T, E>: the hot path never throws, it returns Result.
All engine enumerations.
Instrument: the single definition of a tradable contract (5.3 / 5.15).
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
OrderState
Definition enums.hpp:79
constexpr ClientOrderId make_cl_ord_id(std::uint16_t epoch, std::uint32_t seq) noexcept
Definition strong_id.hpp:103
RejectReason
Ordered exactly like RiskEngine::check_new evaluates them (5.7), followed by OMS / transport / venue ...
Definition enums.hpp:123
@ PoolExhausted
OMS / transport.
OrderClass
Definition oms.hpp:157
Side
Definition enums.hpp:12
Fixed< struct QtyTag > Qty
Definition fixed_point.hpp:333
constexpr std::size_t kMaxOpenOrders
Definition oms.hpp:60
constexpr Unexpected< std::decay_t< E > > fail(E &&e) noexcept
Definition result.hpp:25
constexpr std::uint64_t kMaxSeq
Client order ids per session: the wire form is 48 bits, epoch(16) << 32 | seq(32).
Definition oms.hpp:70
constexpr std::size_t kExecMemory
Executions the OMS remembers by the venue's id, so that one it is given again (a replay of the venue'...
Definition oms.hpp:68
StrongId< struct InstrumentTag, std::uint32_t > InstrumentId
Dense index into the engine's instrument table.
Definition strong_id.hpp:38
constexpr std::size_t kRecentlyTerminal
Definition oms.hpp:61
Fixed< struct PriceTag > Price
Definition fixed_point.hpp:332
constexpr std::size_t kMaxInstruments
Definition instrument.hpp:26
constexpr bool better(Side s, Price p, Price q) noexcept
Definition book_view.hpp:48
OmsAction
Definition oms.hpp:72
@ LateFill
fill for a recently terminal order: position, and the terminal record's cum_qty and state (changed = ...
@ CancelUnknown
ack/fill for an id we do not know: engine must cancel it
@ UnknownFill
fill for a completely unknown id: update position, alert
@ Ignored
message did not apply (duplicate ack, late cancel-reject, ...)
@ ReconcileNeeded
too many cancel rejects
@ Duplicate
duplicate exec_id
StrongId< struct VenueTag, std::uint8_t > VenueId
Definition strong_id.hpp:39
Order: the OMS's 128-byte record for one order across its lifetime.
Definition time.hpp:22
constexpr bool is_zero() const noexcept
Definition fixed_point.hpp:301
constexpr bool is_positive() const noexcept
Definition fixed_point.hpp:302
Definition strong_id.hpp:54
constexpr bool valid() const noexcept
Definition strong_id.hpp:58
std::uint32_t idx
Definition strong_id.hpp:55
Definition order.hpp:105
bool reduce_only
Definition order.hpp:116
Side side
Definition order.hpp:112
VenueId venue
Definition order.hpp:107
OrderType type
Definition order.hpp:113
bool post_only
Definition order.hpp:115
std::uint32_t user_tag
Definition order.hpp:119
Price price
Definition order.hpp:117
TimeInForce tif
Definition order.hpp:114
InstrumentId instrument
Definition order.hpp:106
Qty qty
Definition order.hpp:118
Definition oms.hpp:128
std::uint64_t late_fills
Definition oms.hpp:139
std::uint64_t corrected_fills
Missed fills a replayed execution later named, so their price and fee stopped being estimates.
Definition oms.hpp:143
std::uint32_t open
Definition oms.hpp:129
std::uint64_t duplicates
Definition oms.hpp:138
std::uint64_t synthetic_forgotten
Estimates whose order left the OMS's memory (kRecentlyTerminal later terminal orders) before an execu...
Definition oms.hpp:150
std::uint64_t reconcile_unresolved
Orders a reconciliation snapshot did not report that still had working quantity: the venue ended them...
Definition oms.hpp:154
std::uint64_t unsolicited_cancels
Definition oms.hpp:140
std::uint32_t synthetic_pending
Orders holding an estimate no execution has named yet (a gauge): the position and the PnL include tha...
Definition oms.hpp:146
std::uint64_t unknown_ids
Definition oms.hpp:137
std::uint64_t filled
Definition oms.hpp:134
std::uint64_t missed_fills
cum_qty jumps a fill message never reported
Definition oms.hpp:141
std::uint64_t rejected
Definition oms.hpp:132
std::uint64_t canceled
Definition oms.hpp:133
std::uint64_t fills
Definition oms.hpp:135
std::uint64_t expired
Definition oms.hpp:136
std::uint64_t ack_timeouts
PendingNew orders swept by sweep_pending()
Definition oms.hpp:151
std::uint64_t submitted
Definition oms.hpp:130
std::uint64_t acked
Definition oms.hpp:131
Definition oms.hpp:83
OrderTimes times
The order's times (Oms::times), and the pool slot it had: set on every update of an open order,...
Definition oms.hpp:124
Price fill_px
Definition oms.hpp:97
bool known
the id mapped to an order (open or recently terminal)
Definition oms.hpp:90
Price synthetic_px
Definition oms.hpp:115
Qty corrected_qty
Part of a replayed execution (OrderFillMsg::kReplayed) whose quantity a synthetic fill already put in...
Definition oms.hpp:114
Qty unresolved_qty
Quantity that was still working when a reconciliation snapshot failed to mention the order.
Definition oms.hpp:109
Qty forgotten_qty
An estimate no execution named whose order this update pushed out of the OMS's memory of recently ter...
Definition oms.hpp:120
Qty fill_qty
for fills
Definition oms.hpp:96
Handle< Order > slot
Definition oms.hpp:125
Handle< Order > handle
invalid once terminal (slot freed) or unknown
Definition oms.hpp:87
Order order
snapshot after the transition; for a recently terminal id only the terminal record's fields (id,...
Definition oms.hpp:84
ClientOrderId forgotten_id
Definition oms.hpp:121
bool terminal
the order reached a terminal state in this update
Definition oms.hpp:92
OrderState prev
Definition oms.hpp:88
RejectReason refused
The venue (or the connector for it) refused the order's new or replace leg in this update: the order ...
Definition oms.hpp:95
bool changed
state or quantities changed
Definition oms.hpp:91
ClientOrderId replaced_cl_ord_id
A cancel-replace to a new id completed: the order carries on under order.cl_ord_id and this one is go...
Definition oms.hpp:105
Qty missed_qty
Quantity the venue reports as filled that we never saw a fill message for (a private-stream outage co...
Definition oms.hpp:101
OmsAction action
Definition oms.hpp:89
Definition messages.hpp:267
static constexpr std::uint8_t kAmendedInPlace
The venue amended the resting order in place (Binance Spot order.amend.keepPriority,...
Definition messages.hpp:271
Definition messages.hpp:292
Definition messages.hpp:301
Definition messages.hpp:340
Definition messages.hpp:312
static constexpr std::uint8_t kReplayed
The execution comes from the venue's trade history (Venue::request_executions), not from the private ...
Definition messages.hpp:316
Definition messages.hpp:281
When the order's working leg (the order, or its latest replacement once acknowledged) was sent and ac...
Definition order.hpp:60
Timestamp sent
engine clock when the order or replace went out
Definition order.hpp:61
How an order came to be where it was when something happened to it: kept by the OMS next to Order (Om...
Definition order.hpp:83
OrderTimes times
the working leg: sent (the order, or its last accepted replace)
Definition order.hpp:84
Price placed_px
the first leg's price
Definition order.hpp:88
Timestamp pending_sent
the cancel or replace in flight went out; invalid: none.
Definition order.hpp:86
std::uint32_t amends
replaces the venue accepted
Definition order.hpp:89
Timestamp placed
the first leg went out
Definition order.hpp:85
QuoteContext pending_context
the side's context when the replace in flight went out
Definition order.hpp:92
QuoteContext context
the side's context when the working leg went out
Definition order.hpp:91
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
Qty qty
8 -> 88
Definition order.hpp:42
constexpr Qty leaves_qty() const noexcept
Definition order.hpp:49
std::uint8_t flags
1
Definition order.hpp:38
Price pending_price
8 -> 120
Definition order.hpp:46
constexpr bool has(Flags f) const noexcept
Definition order.hpp:54
std::uint8_t cancel_attempts
1
Definition order.hpp:39
ClientOrderId pending_cl_ord_id
8 -> 112 replace: id of the replacement order
Definition order.hpp:45
Timestamp created
8 -> 104
Definition order.hpp:44
VenueId venue
1
Definition order.hpp:32
constexpr bool is_working() const noexcept
Definition order.hpp:51
Qty pending_qty
8 -> 128
Definition order.hpp:47
InstrumentId instrument
4 -> 60
Definition order.hpp:31
Side side
1
Definition order.hpp:33
std::uint32_t user_tag
4 -> 72 (QuoteManager slot id etc.)
Definition order.hpp:40
RejectReason reject_reason
1
Definition order.hpp:37
Qty cum_qty
8 -> 96
Definition order.hpp:43
OrderType type
1
Definition order.hpp:34
Price price
8 -> 80
Definition order.hpp:41
@ kReplaceOldCanceled
cancel-then-new replace: old leg already cancelled
Definition order.hpp:24
@ kReconciled
state fixed up by reconciliation
Definition order.hpp:21
@ kReduceOnly
Definition order.hpp:19
@ kPostOnly
Definition order.hpp:18
@ kSeenInReconcile
scratch flag during a reconcile pass
Definition order.hpp:22
@ kUnsolicitedCancel
venue cancelled it (not requested by us)
Definition order.hpp:20
Definition order.hpp:72
Control thread injects the venue's view after a reconnect (5.8).
Definition messages.hpp:668
static constexpr StrongId invalid() noexcept
Definition strong_id.hpp:30
Rep value
Definition strong_id.hpp:26
constexpr bool valid() const noexcept
Definition strong_id.hpp:31
Definition time.hpp:45
constexpr bool valid() const noexcept
Definition time.hpp:55