1pub mod config;
19pub mod ids_generator;
20pub mod inflight;
21pub mod orders;
22
23mod settlement;
24mod spread;
25
26#[cfg(test)]
27mod tests;
28
29use std::{
30 cell::RefCell,
31 cmp::min,
32 fmt::Debug,
33 mem,
34 ops::{Add, Sub},
35 rc::Rc,
36};
37
38use indexmap::{IndexMap, IndexSet};
39use jiff::SignedDuration;
40use nautilus_common::{
41 cache::Cache,
42 clock::Clock,
43 messages::execution::{
44 BatchCancelOrders, BatchModifyOrders, CancelAllOrders, CancelOrder, ModifyOrder,
45 },
46 msgbus::{self, MessagingSwitchboard},
47};
48use nautilus_core::{UUID4, UnixNanos, correctness::CorrectnessResult};
49use nautilus_model::{
50 data::{
51 Bar, BarType, InstrumentClose, MarkPriceUpdate, OrderBookDelta, OrderBookDeltas,
52 OrderBookDepth, QuoteTick, TradeTick,
53 order::{BookOrder, OrderId},
54 },
55 enums::{
56 AccountType, AggregationSource, AggressorSide, BookAction, BookType, ContingencyType,
57 InstrumentCloseType, LiquiditySide, MarketStatus, MarketStatusAction, OmsType, OrderSide,
58 OrderStatus, OrderType, PositionSide, PriceType, RecordFlag, TimeInForce, TriggerType,
59 },
60 events::{
61 OrderAccepted, OrderCancelRejected, OrderCanceled, OrderEventAny, OrderExpired,
62 OrderFilled, OrderModifyRejected, OrderRejected, OrderSubmitted, OrderTriggered,
63 OrderUpdated,
64 },
65 identifiers::{
66 AccountId, ClientOrderId, InstrumentId, PositionId, StrategyId, TradeId, TraderId, Venue,
67 VenueOrderId,
68 },
69 instruments::{Instrument, InstrumentAny},
70 orderbook::{BookLevel, OrderBook},
71 orders::{MarketOrder, Order, OrderAny, OrderCore},
72 position::{Position, PositionReplayEvent},
73 types::{
74 Currency, Money, Price, Quantity,
75 fixed::{FIXED_PRECISION, raw_scales_match},
76 price::PriceRaw,
77 quantity::QuantityRaw,
78 },
79};
80use rust_decimal::{Decimal, RoundingStrategy};
81use ustr::Ustr;
82
83use self::{
84 config::{OrderMatchingEngineConfig, OrderPriorityResetPolicy},
85 ids_generator::IdsGenerator,
86 inflight::InflightOrders,
87 orders::{MatchingOrders, OtoCommand},
88};
89use crate::{
90 matching::{MatchAction, OrderMatchingCore, RestingOrder},
91 models::{
92 fee::{FeeModel, FeeModelHandle},
93 fill::{FillModel, FillModelHandle, is_price_tradable},
94 },
95 protection::protection_price_calculate,
96 trailing::{store_trailing_stop_activation, trailing_stop_calculate},
97};
98
99pub struct OrderMatchingEngine {
101 pub venue: Venue,
103 pub instrument: InstrumentAny,
105 pub raw_id: u32,
107 pub book_type: BookType,
109 pub oms_type: OmsType,
111 pub account_type: AccountType,
113 pub market_status: MarketStatus,
115 pub config: OrderMatchingEngineConfig,
117 core: OrderMatchingCore,
118 clock: Rc<RefCell<dyn Clock>>,
119 cache: Rc<RefCell<Cache>>,
120 book: OrderBook,
121 fill_model: FillModelHandle,
122 fee_model: FeeModelHandle,
123 event_handler: Option<Rc<dyn Fn(OrderEventAny)>>,
124 inflight_orders: InflightOrders,
125 target_bid: Option<Price>,
126 target_ask: Option<Price>,
127 target_last: Option<Price>,
128 last_bar_bid: Option<Bar>,
129 last_bar_ask: Option<Bar>,
130 fill_at_market: bool,
131 collapse_bar_trades: bool,
132 last_bar_trade: Option<(Price, Quantity, AggressorSide)>,
133 execution_bar_types: IndexMap<InstrumentId, BarType>,
134 execution_bar_deltas: IndexMap<BarType, SignedDuration>,
135 account_ids: IndexMap<TraderId, AccountId>,
136 pending_fills: IndexMap<TradeId, PendingFill>,
137 post_match_order_ids: IndexSet<ClientOrderId>,
138 orders: MatchingOrders,
139 ids_generator: IdsGenerator,
140 last_trade_size: Option<Quantity>,
141 l1_trade_size: Option<QuantityRaw>,
142 trade_consumption: QuantityRaw,
143 bid_consumption: IndexMap<PriceRaw, (QuantityRaw, QuantityRaw)>,
144 ask_consumption: IndexMap<PriceRaw, (QuantityRaw, QuantityRaw)>,
145 queue_pending: IndexMap<ClientOrderId, PriceRaw>,
146 queue_ahead_orders: IndexMap<ClientOrderId, IndexMap<OrderId, QuantityRaw>>,
147 queue_ahead_total: IndexMap<ClientOrderId, (PriceRaw, QuantityRaw)>,
148 queue_snapshot_in_progress: bool,
149 queue_ids_by_price: IndexMap<PriceRaw, IndexSet<ClientOrderId>>,
150 queue_excess: IndexMap<ClientOrderId, QuantityRaw>,
151 queue_id_scratch: Vec<ClientOrderId>,
152 queue_pending_scratch: Vec<(ClientOrderId, PriceRaw)>,
153 queue_stale_scratch: Vec<ClientOrderId>,
154 queue_entry_scratch: Vec<(ClientOrderId, QuantityRaw, QuantityRaw)>,
155 prev_bid_price_raw: PriceRaw,
156 prev_ask_price_raw: PriceRaw,
157 tob_initialized: bool,
158 last_quote_bid: Option<Price>,
159 last_quote_ask: Option<Price>,
160 precision_mismatch_streak: u32,
161 instrument_close: Option<InstrumentClose>,
162
163 pending_resolution: Option<MarketStatus>,
165 expiration_processed: bool,
166 option_settlement_failed: bool,
167 option_settlement_warning: Option<&'static str>,
168}
169
170impl Debug for OrderMatchingEngine {
171 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172 f.debug_struct(stringify!(OrderMatchingEngine))
173 .field("venue", &self.venue)
174 .field("instrument", &self.instrument.id())
175 .finish()
176 }
177}
178
179impl OrderMatchingEngine {
180 #[expect(clippy::too_many_arguments)]
182 pub fn new(
183 instrument: InstrumentAny,
184 raw_id: u32,
185 fill_model: FillModelHandle,
186 fee_model: FeeModelHandle,
187 book_type: BookType,
188 oms_type: OmsType,
189 account_type: AccountType,
190 clock: Rc<RefCell<dyn Clock>>,
191 cache: Rc<RefCell<Cache>>,
192 config: OrderMatchingEngineConfig,
193 ) -> Self {
194 let book = OrderBook::new(instrument.id(), book_type);
195 let mut core = OrderMatchingCore::new(instrument.id(), instrument.price_increment());
196 core.set_fill_limit_inside_spread(Self::fill_limit_inside_spread_or_false(&fill_model));
197
198 let ids_generator = IdsGenerator::new(
199 instrument.id().venue,
200 oms_type,
201 raw_id,
202 config.use_random_ids,
203 config.use_position_ids,
204 cache.clone(),
205 );
206
207 Self {
208 venue: instrument.id().venue,
209 instrument,
210 raw_id,
211 fill_model,
212 fee_model,
213 event_handler: None,
214 inflight_orders: InflightOrders::default(),
215 book_type,
216 oms_type,
217 account_type,
218 clock,
219 cache,
220 book,
221 market_status: MarketStatus::Open,
222 config,
223 core,
224 target_bid: None,
225 target_ask: None,
226 target_last: None,
227 last_bar_bid: None,
228 last_bar_ask: None,
229 fill_at_market: true,
230 collapse_bar_trades: false,
231 last_bar_trade: None,
232 execution_bar_types: IndexMap::new(),
233 execution_bar_deltas: IndexMap::new(),
234 account_ids: IndexMap::new(),
235 pending_fills: IndexMap::new(),
236 post_match_order_ids: IndexSet::new(),
237 orders: MatchingOrders::default(),
238 ids_generator,
239 last_trade_size: None,
240 l1_trade_size: None,
241 trade_consumption: 0,
242 bid_consumption: IndexMap::new(),
243 ask_consumption: IndexMap::new(),
244 queue_pending: IndexMap::new(),
245 queue_ahead_orders: IndexMap::new(),
246 queue_ahead_total: IndexMap::new(),
247 queue_snapshot_in_progress: false,
248 queue_ids_by_price: IndexMap::new(),
249 queue_excess: IndexMap::new(),
250 queue_id_scratch: Vec::new(),
251 queue_pending_scratch: Vec::new(),
252 queue_stale_scratch: Vec::new(),
253 queue_entry_scratch: Vec::new(),
254 prev_bid_price_raw: 0,
255 prev_ask_price_raw: 0,
256 tob_initialized: false,
257 last_quote_bid: None,
258 last_quote_ask: None,
259 precision_mismatch_streak: 0,
260 instrument_close: None,
261 pending_resolution: None,
262 expiration_processed: false,
263 option_settlement_failed: false,
264 option_settlement_warning: None,
265 }
266 }
267
268 pub fn set_event_handler(&mut self, handler: Rc<dyn Fn(OrderEventAny)>) {
275 self.event_handler = Some(handler);
276 }
277
278 pub fn set_inflight_orders(&mut self, orders: InflightOrders) {
280 self.inflight_orders = orders;
281 }
282
283 pub fn set_matching_orders(&mut self, orders: MatchingOrders) {
288 self.orders = orders;
289 }
290
291 fn dispatch_order_event(&self, event: OrderEventAny) {
292 if let Some(handler) = &self.event_handler {
293 handler(event);
294 } else {
295 let endpoint = MessagingSwitchboard::exec_engine_process();
296 msgbus::send_order_event(endpoint, event);
297 }
298 }
299
300 pub fn reset(&mut self) {
306 self.book.reset();
307 self.execution_bar_types.clear();
308 self.execution_bar_deltas.clear();
309 self.account_ids.clear();
310 self.pending_fills.clear();
311 self.post_match_order_ids.clear();
312 self.orders
313 .reset(self.instrument.id(), &self.cache.borrow());
314 self.core.reset();
315 self.target_bid = None;
316 self.target_ask = None;
317 self.target_last = None;
318 self.last_trade_size = None;
319 self.l1_trade_size = None;
320 self.trade_consumption = 0;
321 self.bid_consumption.clear();
322 self.ask_consumption.clear();
323 self.queue_pending.clear();
324 self.queue_ahead_orders.clear();
325 self.queue_ahead_total.clear();
326 self.queue_snapshot_in_progress = false;
327 self.queue_ids_by_price.clear();
328 self.queue_excess.clear();
329 self.queue_id_scratch.clear();
330 self.queue_pending_scratch.clear();
331 self.queue_stale_scratch.clear();
332 self.queue_entry_scratch.clear();
333 self.prev_bid_price_raw = 0;
334 self.prev_ask_price_raw = 0;
335 self.tob_initialized = false;
336 self.last_quote_bid = None;
337 self.last_quote_ask = None;
338 self.last_bar_bid = None;
339 self.last_bar_ask = None;
340 self.precision_mismatch_streak = 0;
341 self.instrument_close = None;
342 self.market_status = MarketStatus::Open;
343 self.pending_resolution = None;
344 self.expiration_processed = false;
345 self.option_settlement_failed = false;
346 self.option_settlement_warning = None;
347 self.fill_at_market = true;
348 self.ids_generator.reset();
349
350 log::info!("Reset {}", self.instrument.id());
351 }
352
353 fn apply_liquidity_consumption(
354 &mut self,
355 mut fills: Vec<(Price, Quantity)>,
356 order: &OrderAny,
357 leaves_qty: Quantity,
358 book_prices: Option<&[Price]>,
359 trade_size: Option<QuantityRaw>,
360 mut journal: Option<&mut ConsumptionJournal>,
361 ) -> Vec<(Price, Quantity)> {
362 if !self.config.liquidity_consumption {
363 return fills;
364 }
365
366 let mut adjusted_len = 0;
367
368 let mut remaining_qty = trade_size.map_or(leaves_qty.raw(), |trade_size| {
369 leaves_qty
370 .raw()
371 .min(trade_size.saturating_sub(self.trade_consumption))
372 });
373
374 for fill_idx in 0..fills.len() {
375 if remaining_qty == 0 {
376 break;
377 }
378
379 let (price, qty) = fills[fill_idx];
380
381 let book_price = book_prices
384 .and_then(|bp| bp.get(fill_idx).copied())
385 .unwrap_or(price);
386
387 let adjusted_qty_raw = self.consume_book_level(
388 order.order_side(),
389 book_price,
390 qty,
391 remaining_qty,
392 journal.as_deref_mut(),
393 );
394
395 if adjusted_qty_raw == 0 {
396 continue;
397 }
398
399 remaining_qty -= adjusted_qty_raw;
400 if trade_size.is_some() {
401 self.trade_consumption += adjusted_qty_raw;
402 }
403
404 let adjusted_qty = Quantity::from_raw(adjusted_qty_raw, qty.precision);
405 fills[adjusted_len] = (price, adjusted_qty);
406 adjusted_len += 1;
407
408 if order.order_type() == OrderType::MarketToLimit && order.filled_qty().is_zero() {
409 break;
410 }
411 }
412
413 fills.truncate(adjusted_len);
414 fills
415 }
416
417 fn consume_book_level(
418 &mut self,
419 order_side: OrderSide,
420 book_price: Price,
421 qty: Quantity,
422 remaining_qty: QuantityRaw,
423 journal: Option<&mut ConsumptionJournal>,
424 ) -> QuantityRaw {
425 let book_price_raw = book_price.raw();
426 let level_size = self
427 .book
428 .get_quantity_at_level(book_price, order_side, qty.precision);
429
430 let consumption = match order_side {
431 OrderSide::Buy => &mut self.ask_consumption,
432 OrderSide::Sell => &mut self.bid_consumption,
433 };
434
435 if let Some(journal) = journal {
436 journal
437 .levels
438 .push((book_price_raw, consumption.get(&book_price_raw).copied()));
439 }
440
441 let (original_size, consumed) = consumption
442 .entry(book_price_raw)
443 .or_insert((level_size.raw(), 0));
444
445 if *original_size != level_size.raw() {
447 *original_size = level_size.raw();
448 *consumed = 0;
449 }
450
451 let available = original_size.saturating_sub(*consumed);
452 let adjusted_qty_raw = min(min(qty.raw(), available), remaining_qty);
453 *consumed += adjusted_qty_raw;
454 adjusted_qty_raw
455 }
456
457 fn fok_consumption_journal(&self, order: &OrderAny) -> Option<ConsumptionJournal> {
464 if !self.config.liquidity_consumption || order.time_in_force() != TimeInForce::Fok {
465 return None;
466 }
467
468 Some(ConsumptionJournal {
469 order_side: order.order_side(),
470 trade_consumption: self.trade_consumption,
471 levels: Vec::new(),
472 })
473 }
474
475 fn revert_consumption_journal(&mut self, journal: ConsumptionJournal) {
476 self.trade_consumption = journal.trade_consumption;
477
478 let consumption = match journal.order_side {
479 OrderSide::Buy => &mut self.ask_consumption,
480 OrderSide::Sell => &mut self.bid_consumption,
481 };
482
483 for (price_raw, prior) in journal.levels.into_iter().rev() {
486 match prior {
487 Some(prior) => {
488 consumption.insert(price_raw, prior);
489 }
490 None => {
491 consumption.shift_remove(&price_raw);
492 }
493 }
494 }
495 }
496
497 fn is_fok_unfillable(
498 &self,
499 order: &OrderAny,
500 fills: &[(Price, Quantity)],
501 required_qty: Quantity,
502 ) -> bool {
503 if order.time_in_force() != TimeInForce::Fok {
504 return false;
505 }
506
507 let mut total_size = Quantity::zero(order.quantity().precision);
508 let initial_market_to_limit =
509 order.order_type() == OrderType::MarketToLimit && order.filled_qty().is_zero();
510 let mut first_price = None;
511
512 for &(fill_px, fill_qty) in fills {
513 if let Some(fill_px) = self.normalize_price_for_current_instrument(fill_px)
514 && let Some(fill_qty) = self.normalize_quantity_for_current_instrument(fill_qty)
515 {
516 if initial_market_to_limit {
517 if fill_qty.is_zero() {
518 continue;
519 }
520
521 if first_price.is_some_and(|price| price != fill_px) {
522 break;
523 }
524
525 first_price = Some(fill_px);
526 }
527
528 total_size = total_size.add(fill_qty);
529 }
530 }
531
532 required_qty > total_size
533 }
534
535 fn seed_trade_consumption(
536 &mut self,
537 trade_price_raw: PriceRaw,
538 trade_size_raw: QuantityRaw,
539 trade_ts_event: UnixNanos,
540 aggressor_side: AggressorSide,
541 ) {
542 if trade_size_raw == 0 {
543 return;
544 }
545
546 if self.book.ts_last > trade_ts_event {
549 return;
550 }
551
552 let book = &self.book;
553
554 let consumption = match aggressor_side {
555 AggressorSide::Buy => &mut self.ask_consumption,
556 AggressorSide::Sell => &mut self.bid_consumption,
557 AggressorSide::NoAggressor => return,
558 };
559
560 let mut remaining = trade_size_raw;
561
562 match aggressor_side {
563 AggressorSide::Buy => {
564 for level in book
565 .asks(None)
566 .take_while(|level| level.price.value.raw() <= trade_price_raw)
567 {
568 Self::consume_trade_level(consumption, &mut remaining, level);
569 if remaining == 0 {
570 break;
571 }
572 }
573 }
574 AggressorSide::Sell => {
575 for level in book
576 .bids(None)
577 .take_while(|level| level.price.value.raw() >= trade_price_raw)
578 {
579 Self::consume_trade_level(consumption, &mut remaining, level);
580 if remaining == 0 {
581 break;
582 }
583 }
584 }
585 AggressorSide::NoAggressor => unreachable!(),
586 }
587 }
588
589 fn consume_trade_level(
590 consumption: &mut IndexMap<PriceRaw, (QuantityRaw, QuantityRaw)>,
591 remaining: &mut QuantityRaw,
592 level: &BookLevel,
593 ) {
594 let level_size = level.size_raw();
595 let entry = consumption
596 .entry(level.price.value.raw())
597 .or_insert((level_size, 0));
598
599 if entry.0 != level_size {
601 entry.0 = level_size;
602 entry.1 = 0;
603 }
604
605 let available = level_size.saturating_sub(entry.1);
606 let consume = min(*remaining, available);
607 entry.1 += consume;
608 *remaining -= consume;
609 }
610
611 pub fn set_fill_model(&mut self, fill_model: FillModelHandle) {
613 self.core
614 .set_fill_limit_inside_spread(Self::fill_limit_inside_spread_or_false(&fill_model));
615 self.fill_model = fill_model;
616 }
617
618 fn fill_limit_inside_spread_or_false(fill_model: &FillModelHandle) -> bool {
619 fill_model.fill_limit_inside_spread().unwrap_or_else(|e| {
620 log::error!("Failed to query fill model spread behavior: {e}");
621 false
622 })
623 }
624
625 fn snapshot_queue_position(&mut self, order: &OrderAny, price: Price) {
626 if !self.config.queue_position {
627 return;
628 }
629
630 let size_prec = self.instrument.size_precision();
631
632 let qty_ahead = self.book.get_quantity_at_level(
635 price,
636 OrderCore::opposite_side(order.order_side()),
637 size_prec,
638 );
639
640 let client_order_id = order.client_order_id();
641
642 self.remove_queue_position(client_order_id);
643 self.queue_ids_by_price
644 .entry(price.raw())
645 .or_default()
646 .insert(client_order_id);
647
648 if self.book_type == BookType::L1_MBP && qty_ahead.is_zero() {
653 let behind_bbo = match order.order_side() {
654 OrderSide::Buy => self.book.best_bid_price().is_some_and(|bid| price < bid),
655 OrderSide::Sell => self.book.best_ask_price().is_some_and(|ask| price > ask),
656 };
657
658 if behind_bbo {
659 self.queue_pending.insert(client_order_id, price.raw());
660 return;
661 }
662 }
663
664 self.queue_ahead_total
665 .insert(client_order_id, (price.raw(), qty_ahead.raw()));
666
667 if self.book_type == BookType::L3_MBO {
669 let orders_ahead: IndexMap<OrderId, QuantityRaw> = self
670 .book
671 .get_orders_at_level(price, OrderCore::opposite_side(order.order_side()))
672 .iter()
673 .map(|book_order| (book_order.order_id, book_order.size.raw()))
674 .collect();
675 self.queue_ahead_orders
676 .insert(client_order_id, orders_ahead);
677 }
678 }
679
680 fn remove_queue_position(&mut self, client_order_id: ClientOrderId) {
681 let pending_price = self.queue_pending.shift_remove(&client_order_id);
682 let ahead_price = self
683 .queue_ahead_total
684 .shift_remove(&client_order_id)
685 .map(|(price_raw, _)| price_raw);
686 self.queue_ahead_orders.shift_remove(&client_order_id);
687 self.queue_excess.shift_remove(&client_order_id);
688
689 for price_raw in [pending_price, ahead_price].into_iter().flatten() {
690 let remove_price = self
691 .queue_ids_by_price
692 .get_mut(&price_raw)
693 .is_some_and(|ids| {
694 ids.shift_remove(&client_order_id);
695 ids.is_empty()
696 });
697
698 if remove_price {
699 self.queue_ids_by_price.shift_remove(&price_raw);
700 }
701 }
702 }
703
704 fn take_queue_ids_at_price(&mut self, price_raw: PriceRaw) -> Vec<ClientOrderId> {
705 let mut ids = Self::take_cleared(&mut self.queue_id_scratch);
706 if let Some(tracked_ids) = self.queue_ids_by_price.get(&price_raw) {
707 ids.extend(tracked_ids.iter().copied());
708 }
709
710 ids
711 }
712
713 fn decrement_queue_on_trade(
714 &mut self,
715 price_raw: PriceRaw,
716 trade_size_raw: QuantityRaw,
717 aggressor_side: AggressorSide,
718 ) {
719 if !self.config.queue_position {
720 return;
721 }
722
723 self.queue_excess.clear();
724
725 let keys = self.take_queue_ids_at_price(price_raw);
726 let mut entries = Self::take_cleared(&mut self.queue_entry_scratch);
727 let mut stale = Self::take_cleared(&mut self.queue_stale_scratch);
728
729 for client_order_id in keys.iter().copied() {
730 let (order_price_raw, ahead_raw) =
731 match self.queue_ahead_total.get(&client_order_id).copied() {
732 Some(v) => v,
733 None => continue,
734 };
735
736 let cache = self.cache.borrow();
737
738 let order_info = cache.order(&client_order_id).and_then(|order| {
739 if order.is_closed() {
740 return None;
741 }
742
743 let has_pending_updates = self
744 .orders
745 .pending_updates
746 .borrow()
747 .contains_key(&client_order_id);
748 let has_pending_fills = self
749 .orders
750 .cached_filled_qty
751 .borrow()
752 .get(&client_order_id)
753 .is_some_and(|filled_qty| *filled_qty != order.filled_qty());
754 let snapshot;
755 let order = if has_pending_updates || has_pending_fills {
756 snapshot = self.order_snapshot(client_order_id)?;
757 &snapshot
758 } else {
759 &order
760 };
761
762 Some((order.order_side(), order.leaves_qty().raw()))
763 });
764
765 drop(cache);
766
767 let Some((order_side, leaves_raw)) = order_info else {
768 stale.push(client_order_id);
769 continue;
770 };
771
772 if order_price_raw != price_raw || ahead_raw == 0 {
773 continue;
774 }
775
776 let should_decrement = matches!(aggressor_side, AggressorSide::NoAggressor)
777 || (aggressor_side == AggressorSide::Buy && order_side == OrderSide::Sell)
778 || (aggressor_side == AggressorSide::Sell && order_side == OrderSide::Buy);
779
780 if should_decrement {
781 entries.push((client_order_id, ahead_raw, leaves_raw));
782 }
783 }
784
785 for id in stale.drain(..) {
786 self.remove_queue_position(id);
787 }
788
789 entries.sort_by_key(|&(_, ahead, _)| ahead);
791
792 let mut remaining = trade_size_raw;
793 let mut prev_position: QuantityRaw = 0;
794
795 for (client_order_id, ahead_raw, leaves_raw) in &entries {
796 if remaining == 0 {
797 let new_ahead = ahead_raw.saturating_sub(trade_size_raw);
798 self.reduce_queue_ahead(*client_order_id, price_raw, *ahead_raw, new_ahead);
799 if new_ahead == 0 {
800 self.queue_excess.insert(*client_order_id, 0);
802 }
803
804 continue;
805 }
806
807 let gap = ahead_raw.saturating_sub(prev_position);
809 let queue_consumed = remaining.min(gap);
810 remaining -= queue_consumed;
811
812 if remaining == 0 && queue_consumed < gap {
813 let new_ahead = ahead_raw.saturating_sub(trade_size_raw);
814 self.reduce_queue_ahead(*client_order_id, price_raw, *ahead_raw, new_ahead);
815 continue;
816 }
817
818 self.reduce_queue_ahead(*client_order_id, price_raw, *ahead_raw, 0);
819 let excess = remaining.min(*leaves_raw);
820 self.queue_excess.insert(*client_order_id, excess);
821 remaining -= excess;
822 prev_position = ahead_raw + excess;
823 }
824
825 self.queue_id_scratch = keys;
826 self.queue_entry_scratch = entries;
827 self.queue_stale_scratch = stale;
828 }
829
830 fn reduce_queue_ahead(
834 &mut self,
835 client_order_id: ClientOrderId,
836 price_raw: PriceRaw,
837 ahead_raw: QuantityRaw,
838 new_ahead_raw: QuantityRaw,
839 ) {
840 self.queue_ahead_total
841 .insert(client_order_id, (price_raw, new_ahead_raw));
842 self.consume_queue_ahead_orders(client_order_id, ahead_raw.saturating_sub(new_ahead_raw));
843 }
844
845 fn consume_queue_ahead_orders(
847 &mut self,
848 client_order_id: ClientOrderId,
849 mut amount_raw: QuantityRaw,
850 ) {
851 let Some(orders_ahead) = self.queue_ahead_orders.get_mut(&client_order_id) else {
852 return;
853 };
854
855 while amount_raw > 0 {
856 let Some((&book_order_id, &size_raw)) = orders_ahead.get_index(0) else {
857 break;
858 };
859
860 if size_raw <= amount_raw {
861 orders_ahead.shift_remove(&book_order_id);
862 amount_raw -= size_raw;
863 } else {
864 orders_ahead.insert(book_order_id, size_raw - amount_raw);
865 amount_raw = 0;
866 }
867 }
868 }
869
870 fn determine_trade_fill_qty(&self, order: &OrderAny) -> Option<QuantityRaw> {
871 if !self.config.queue_position {
872 return Some(order.leaves_qty().raw());
873 }
874
875 let client_order_id = order.client_order_id();
876
877 if self.queue_pending.contains_key(&client_order_id) {
879 return None;
880 }
881
882 if let Some(&(tracked_price_raw, ahead_raw)) = self.queue_ahead_total.get(&client_order_id)
883 && let Some(order_price) = order.price()
884 && order_price.raw() == tracked_price_raw
885 && ahead_raw > 0
886 {
887 return None;
888 }
889
890 let leaves_raw = order.leaves_qty().raw();
891 if leaves_raw == 0 {
892 return None;
893 }
894
895 let mut available_raw = leaves_raw;
896
897 if let Some(trade_size) = self.last_trade_size {
899 let remaining = trade_size.raw().saturating_sub(self.trade_consumption);
900 available_raw = available_raw.min(remaining);
901
902 if let Some(&excess_raw) = self.queue_excess.get(&client_order_id) {
903 if excess_raw == 0 {
904 return None;
905 }
906
907 available_raw = available_raw.min(excess_raw);
908 }
909 }
910
911 if available_raw == 0 {
912 return None;
913 }
914
915 Some(available_raw)
916 }
917
918 fn rebase_queue_positions(&mut self) {
925 if !self.config.queue_position {
926 return;
927 }
928
929 let tracked: Vec<_> = self
930 .queue_ahead_total
931 .iter()
932 .map(|(&client_order_id, &(price_raw, ahead_raw))| {
933 (client_order_id, price_raw, ahead_raw)
934 })
935 .collect();
936
937 let mut stale = Self::take_cleared(&mut self.queue_stale_scratch);
938 let size_precision = self.instrument.size_precision();
939 let price_precision = self.instrument.price_precision();
940
941 for (client_order_id, price_raw, ahead_raw) in tracked {
942 let Some(order_side) = self.queue_order_side(client_order_id) else {
943 stale.push(client_order_id);
944 continue;
945 };
946
947 let price = Price::from_raw(price_raw, price_precision);
948 let visible_raw = self
949 .book
950 .get_quantity_at_level(price, OrderCore::opposite_side(order_side), size_precision)
951 .raw();
952 let rebased_raw = ahead_raw.min(visible_raw);
953
954 if self.book_type == BookType::L3_MBO {
955 let previous_orders = self
956 .queue_ahead_orders
957 .get(&client_order_id)
958 .cloned()
959 .unwrap_or_default();
960 let mut orders_ahead = IndexMap::new();
961 let mut total_raw = 0;
962
963 for book_order in self
964 .book
965 .get_orders_at_level(price, OrderCore::opposite_side(order_side))
966 {
967 if !previous_orders.contains_key(&book_order.order_id) {
968 continue;
969 }
970
971 let previous_size_raw = previous_orders[&book_order.order_id];
972 let size_raw = previous_size_raw.min(book_order.size.raw());
973 orders_ahead.insert(book_order.order_id, size_raw);
974 total_raw += size_raw;
975 }
976
977 self.queue_ahead_orders
978 .insert(client_order_id, orders_ahead);
979 self.queue_ahead_total
980 .insert(client_order_id, (price_raw, total_raw));
981 } else {
982 self.queue_ahead_total
983 .insert(client_order_id, (price_raw, rebased_raw));
984 }
985 }
986
987 for client_order_id in stale.drain(..) {
988 self.remove_queue_position(client_order_id);
989 }
990
991 self.queue_stale_scratch = stale;
992 }
993
994 fn adjust_queue_for_delta(&mut self, delta: &OrderBookDelta) {
995 if delta.action == BookAction::Delete {
996 if self.is_order_granular_delta(delta.flags) {
997 self.advance_l3_queue_on_delete(delta.order.order_id);
998 } else {
999 self.clear_queue_on_delete(delta.order.price.raw(), delta.order.side);
1000 }
1001 } else if delta.action == BookAction::Update {
1002 if self.is_order_granular_delta(delta.flags) {
1003 self.adjust_l3_queue_on_update(&delta.order);
1004 } else {
1005 self.cap_queue_ahead(
1006 delta.order.price.raw(),
1007 delta.order.size.raw(),
1008 delta.order.side,
1009 );
1010 }
1011 }
1012 }
1013
1014 fn clear_queue_on_delete(
1015 &mut self,
1016 deleted_price_raw: PriceRaw,
1017 deleted_side: Option<OrderSide>,
1018 ) {
1019 let keys = self.take_queue_ids_at_price(deleted_price_raw);
1020 for client_order_id in keys.iter().copied() {
1021 if let Some(&(order_price_raw, ahead_raw)) =
1022 self.queue_ahead_total.get(&client_order_id)
1023 && order_price_raw == deleted_price_raw
1024 {
1025 let matches_side = self
1026 .cache
1027 .borrow()
1028 .order(&client_order_id)
1029 .is_some_and(|o| Some(o.order_side()) == deleted_side);
1030
1031 if matches_side {
1032 self.reduce_queue_ahead(client_order_id, order_price_raw, ahead_raw, 0);
1033 }
1034 }
1035 }
1036
1037 self.queue_id_scratch = keys;
1038 }
1039
1040 fn is_order_granular_delta(&self, flags: u8) -> bool {
1043 self.book_type == BookType::L3_MBO
1044 && !RecordFlag::F_TOB.matches(flags)
1045 && !RecordFlag::F_MBP.matches(flags)
1046 }
1047
1048 fn advance_l3_queue_on_delete(&mut self, book_order_id: OrderId) {
1049 for (client_order_id, orders_ahead) in &mut self.queue_ahead_orders {
1050 let Some(size_raw) = orders_ahead.shift_remove(&book_order_id) else {
1051 continue;
1052 };
1053
1054 if let Some((_, ahead_raw)) = self.queue_ahead_total.get_mut(client_order_id) {
1055 *ahead_raw = ahead_raw.saturating_sub(size_raw);
1056 }
1057 }
1058 }
1059
1060 fn adjust_l3_queue_on_update(&mut self, book_order: &BookOrder) {
1066 for (client_order_id, orders_ahead) in &mut self.queue_ahead_orders {
1067 let Some(&tracked_size_raw) = orders_ahead.get(&book_order.order_id) else {
1068 continue;
1069 };
1070
1071 let Some((tracked_price_raw, ahead_raw)) =
1072 self.queue_ahead_total.get_mut(client_order_id)
1073 else {
1074 continue;
1075 };
1076
1077 if book_order.price.raw() != *tracked_price_raw {
1078 *ahead_raw = ahead_raw.saturating_sub(tracked_size_raw);
1079 orders_ahead.shift_remove(&book_order.order_id);
1080 } else if book_order.size.raw() < tracked_size_raw {
1081 *ahead_raw = ahead_raw.saturating_sub(tracked_size_raw - book_order.size.raw());
1083 orders_ahead.insert(book_order.order_id, book_order.size.raw());
1084 } else if book_order.size.raw() > tracked_size_raw {
1085 *ahead_raw = ahead_raw.saturating_add(book_order.size.raw() - tracked_size_raw);
1086 orders_ahead.insert(book_order.order_id, book_order.size.raw());
1087 }
1088 }
1089 }
1090
1091 fn cap_queue_ahead(
1092 &mut self,
1093 price_raw: PriceRaw,
1094 size_raw: QuantityRaw,
1095 order_side: Option<OrderSide>,
1096 ) {
1097 let keys = self.take_queue_ids_at_price(price_raw);
1098 let mut stale = Self::take_cleared(&mut self.queue_stale_scratch);
1099
1100 for client_order_id in keys.iter().copied() {
1101 let (order_price_raw, ahead_raw) =
1102 match self.queue_ahead_total.get(&client_order_id).copied() {
1103 Some(v) => v,
1104 None => continue,
1105 };
1106
1107 if order_price_raw != price_raw || ahead_raw <= size_raw {
1108 continue;
1109 }
1110
1111 let Some(side) = self.queue_order_side(client_order_id) else {
1112 stale.push(client_order_id);
1113 continue;
1114 };
1115
1116 if Some(side) != order_side {
1117 continue;
1118 }
1119
1120 self.reduce_queue_ahead(client_order_id, order_price_raw, ahead_raw, size_raw);
1121 }
1122
1123 for id in stale.drain(..) {
1124 self.remove_queue_position(id);
1125 }
1126
1127 self.queue_id_scratch = keys;
1128 self.queue_stale_scratch = stale;
1129 }
1130
1131 fn seed_tob_baseline(&mut self) {
1132 let bid = self.book.best_bid_price();
1133 let ask = self.book.best_ask_price();
1134 self.prev_bid_price_raw = bid.map_or(0, |p| p.raw());
1135 self.prev_ask_price_raw = ask.map_or(0, |p| p.raw());
1136 self.tob_initialized = bid.is_some() || ask.is_some();
1137 }
1138
1139 fn decrement_l1_queue_on_quote(
1140 &mut self,
1141 bid_price_raw: PriceRaw,
1142 bid_size_raw: QuantityRaw,
1143 ask_price_raw: PriceRaw,
1144 ask_size_raw: QuantityRaw,
1145 ) {
1146 if !self.config.queue_position {
1147 return;
1148 }
1149
1150 if self.tob_initialized {
1152 if bid_price_raw < self.prev_bid_price_raw {
1154 self.adjust_l1_queue_on_price_move(bid_price_raw, bid_size_raw, OrderSide::Buy);
1155 }
1156
1157 if ask_price_raw > self.prev_ask_price_raw {
1159 self.adjust_l1_queue_on_price_move(ask_price_raw, ask_size_raw, OrderSide::Sell);
1160 }
1161 }
1162
1163 self.resolve_pending_l1_snapshots(bid_price_raw, bid_size_raw, ask_price_raw, ask_size_raw);
1165 self.cap_queue_ahead(bid_price_raw, bid_size_raw, Some(OrderSide::Buy));
1166 self.cap_queue_ahead(ask_price_raw, ask_size_raw, Some(OrderSide::Sell));
1167 }
1168
1169 fn adjust_l1_queue_on_price_move(
1170 &mut self,
1171 new_price_raw: PriceRaw,
1172 new_size_raw: QuantityRaw,
1173 order_side: OrderSide,
1174 ) {
1175 let mut keys = Self::take_cleared(&mut self.queue_id_scratch);
1176 keys.extend(self.queue_ahead_total.keys().copied());
1177 let mut stale = Self::take_cleared(&mut self.queue_stale_scratch);
1178
1179 for client_order_id in keys.iter().copied() {
1180 let Some(&(order_price_raw, ahead_raw)) = self.queue_ahead_total.get(&client_order_id)
1181 else {
1182 continue;
1183 };
1184
1185 let Some(side) = self.queue_order_side(client_order_id) else {
1186 stale.push(client_order_id);
1187 continue;
1188 };
1189
1190 if side != order_side {
1191 continue;
1192 }
1193
1194 let crossed = match order_side {
1197 OrderSide::Buy => order_price_raw > new_price_raw,
1198 _ => order_price_raw < new_price_raw,
1199 };
1200
1201 if crossed {
1202 self.queue_ahead_total
1203 .insert(client_order_id, (order_price_raw, 0));
1204 } else if order_price_raw == new_price_raw && ahead_raw > new_size_raw {
1205 self.queue_ahead_total
1206 .insert(client_order_id, (order_price_raw, new_size_raw));
1207 }
1208 }
1209
1210 for id in stale.drain(..) {
1211 self.remove_queue_position(id);
1212 }
1213
1214 let mut pending = Self::take_cleared(&mut self.queue_pending_scratch);
1215 pending.extend(
1216 self.queue_pending
1217 .iter()
1218 .map(|(&client_order_id, &price_raw)| (client_order_id, price_raw)),
1219 );
1220
1221 for (client_order_id, order_price_raw) in pending.iter().copied() {
1222 let Some(side) = self.queue_order_side(client_order_id) else {
1223 stale.push(client_order_id);
1224 continue;
1225 };
1226
1227 if side != order_side {
1228 continue;
1229 }
1230
1231 let crossed = match order_side {
1232 OrderSide::Buy => order_price_raw > new_price_raw,
1233 _ => order_price_raw < new_price_raw,
1234 };
1235
1236 if crossed {
1237 self.queue_pending.shift_remove(&client_order_id);
1238 self.queue_ahead_total
1239 .insert(client_order_id, (order_price_raw, 0));
1240 } else if order_price_raw == new_price_raw {
1241 self.queue_pending.shift_remove(&client_order_id);
1242 self.queue_ahead_total
1243 .insert(client_order_id, (order_price_raw, new_size_raw));
1244 }
1245 }
1246
1247 for id in stale.drain(..) {
1248 self.remove_queue_position(id);
1249 }
1250
1251 self.queue_id_scratch = keys;
1252 self.queue_pending_scratch = pending;
1253 self.queue_stale_scratch = stale;
1254 }
1255
1256 fn resolve_pending_l1_snapshots(
1257 &mut self,
1258 bid_price_raw: PriceRaw,
1259 bid_size_raw: QuantityRaw,
1260 ask_price_raw: PriceRaw,
1261 ask_size_raw: QuantityRaw,
1262 ) {
1263 let mut keys = self.take_queue_ids_at_price(bid_price_raw);
1264 if ask_price_raw != bid_price_raw
1265 && let Some(ask_ids) = self.queue_ids_by_price.get(&ask_price_raw)
1266 {
1267 keys.extend(ask_ids.iter().copied());
1268 }
1269
1270 let mut stale = Self::take_cleared(&mut self.queue_stale_scratch);
1271
1272 for client_order_id in keys.iter().copied() {
1273 let Some(&order_price_raw) = self.queue_pending.get(&client_order_id) else {
1274 continue;
1275 };
1276
1277 let Some(side) = self.queue_order_side(client_order_id) else {
1278 stale.push(client_order_id);
1279 continue;
1280 };
1281
1282 let matched_size = match side {
1284 OrderSide::Buy if order_price_raw == bid_price_raw => Some(bid_size_raw),
1285 OrderSide::Sell if order_price_raw == ask_price_raw => Some(ask_size_raw),
1286 _ => None,
1287 };
1288
1289 if let Some(size) = matched_size {
1290 self.queue_pending.shift_remove(&client_order_id);
1291 self.queue_ahead_total
1292 .insert(client_order_id, (order_price_raw, size));
1293 }
1294 }
1295
1296 for id in stale.drain(..) {
1297 self.remove_queue_position(id);
1298 }
1299
1300 self.queue_id_scratch = keys;
1301 self.queue_stale_scratch = stale;
1302 }
1303
1304 fn resolve_pending_on_trade(&mut self, trade_price_raw: PriceRaw) {
1305 let mut pending = Self::take_cleared(&mut self.queue_pending_scratch);
1306 pending.extend(
1307 self.queue_pending
1308 .iter()
1309 .map(|(&client_order_id, &price_raw)| (client_order_id, price_raw)),
1310 );
1311 let mut stale = Self::take_cleared(&mut self.queue_stale_scratch);
1312
1313 for (client_order_id, order_price_raw) in pending.iter().copied() {
1314 let Some(side) = self.queue_order_side(client_order_id) else {
1315 stale.push(client_order_id);
1316 continue;
1317 };
1318
1319 let crossed = match side {
1321 OrderSide::Buy => trade_price_raw < order_price_raw,
1322 OrderSide::Sell => trade_price_raw > order_price_raw,
1323 };
1324
1325 if crossed {
1326 self.queue_pending.shift_remove(&client_order_id);
1327 self.queue_ahead_total
1328 .insert(client_order_id, (order_price_raw, 0));
1329 }
1330 }
1331
1332 for id in stale.drain(..) {
1333 self.remove_queue_position(id);
1334 }
1335
1336 self.queue_pending_scratch = pending;
1337 self.queue_stale_scratch = stale;
1338 }
1339
1340 fn queue_order_side(&self, client_order_id: ClientOrderId) -> Option<OrderSide> {
1341 self.cache
1342 .borrow()
1343 .order_ref(&client_order_id)
1344 .filter(|order| !order.is_closed())
1345 .map(|order| order.order_side())
1346 }
1347
1348 fn take_cleared<T>(buf: &mut Vec<T>) -> Vec<T> {
1349 let mut items = mem::take(buf);
1350 items.clear();
1351 items
1352 }
1353
1354 #[must_use]
1355 pub fn best_bid_price(&self) -> Option<Price> {
1357 self.book.best_bid_price()
1358 }
1359
1360 #[must_use]
1361 pub fn best_ask_price(&self) -> Option<Price> {
1363 self.book.best_ask_price()
1364 }
1365
1366 #[must_use]
1367 pub const fn get_book(&self) -> &OrderBook {
1369 &self.book
1370 }
1371
1372 #[must_use]
1373 pub fn get_open_bid_orders(&self) -> Vec<RestingOrder> {
1375 self.core.get_orders_bid()
1376 }
1377
1378 #[must_use]
1379 pub fn get_open_ask_orders(&self) -> Vec<RestingOrder> {
1381 self.core.get_orders_ask()
1382 }
1383
1384 #[must_use]
1385 pub fn get_open_orders(&self) -> Vec<RestingOrder> {
1387 self.core.get_orders()
1388 }
1389
1390 #[must_use]
1391 pub fn order_exists(&self, client_order_id: ClientOrderId) -> bool {
1393 self.core.order_exists(client_order_id)
1394 }
1395
1396 #[must_use]
1397 pub fn cached_filled_qty_len(&self) -> usize {
1399 let cache = self.cache.borrow();
1400 self.orders
1401 .cached_filled_qty
1402 .borrow()
1403 .keys()
1404 .filter(|id| {
1405 cache
1406 .order(id)
1407 .is_some_and(|order| order.instrument_id() == self.instrument.id())
1408 })
1409 .count()
1410 }
1411
1412 #[must_use]
1413 pub const fn get_core(&self) -> &OrderMatchingCore {
1414 &self.core
1415 }
1416
1417 pub fn set_fill_at_market(&mut self, value: bool) {
1418 self.fill_at_market = value;
1419 }
1420
1421 pub fn update_instrument(&mut self, instrument: InstrumentAny) -> anyhow::Result<()> {
1427 if instrument.id() != self.instrument.id() {
1428 anyhow::bail!(
1429 "Cannot update instrument {} with {}",
1430 self.instrument.id(),
1431 instrument.id()
1432 );
1433 }
1434
1435 if self.requires_pending_resolution()
1436 && instrument.expiration_ns() != self.instrument.expiration_ns()
1437 && !self.expiration_processed
1438 && self.instrument_close.is_none()
1439 && instrument.expiration_ns().is_none_or(|ns| {
1440 ns == UnixNanos::default() || ns > self.clock.borrow().timestamp_ns()
1441 })
1442 && let Some(status) = self.pending_resolution.take()
1443 {
1444 self.market_status = status;
1445 }
1446
1447 let changed = instrument.price_increment() != self.instrument.price_increment()
1448 || instrument.price_precision() != self.instrument.price_precision()
1449 || instrument.size_precision() != self.instrument.size_precision();
1450
1451 if changed {
1452 self.core
1453 .update_price_increment(instrument.price_increment());
1454 self.book.reset();
1455 self.l1_trade_size = None;
1456 self.trade_consumption = 0;
1457 self.bid_consumption.clear();
1458 self.ask_consumption.clear();
1459 self.queue_pending.clear();
1460 self.queue_ahead_orders.clear();
1461 self.queue_ahead_total.clear();
1462 self.queue_ids_by_price.clear();
1463 self.queue_excess.clear();
1464 self.prev_bid_price_raw = 0;
1465 self.prev_ask_price_raw = 0;
1466 self.tob_initialized = false;
1467 self.last_quote_bid = None;
1468 self.last_quote_ask = None;
1469 self.precision_mismatch_streak = 0;
1470 self.target_bid = None;
1471 self.target_ask = None;
1472 self.target_last = None;
1473 self.last_bar_bid = None;
1474 self.last_bar_ask = None;
1475 self.core.bid = None;
1476 self.core.ask = None;
1477 self.core.last = None;
1478 log::info!(
1479 "Updated instrument {} (price_precision={} size_precision={})",
1480 instrument.id(),
1481 instrument.price_precision(),
1482 instrument.size_precision()
1483 );
1484 }
1485
1486 self.instrument = instrument;
1487
1488 if changed {
1489 self.drop_incompatible_core_orders();
1490 }
1491
1492 Ok(())
1493 }
1494
1495 fn check_price_precision(&self, actual: u8, field: &str) -> anyhow::Result<()> {
1496 let expected = self.instrument.price_precision();
1497 if actual != expected {
1498 anyhow::bail!(
1499 "Invalid {field} precision {actual}, expected {expected} for {}",
1500 self.instrument.id()
1501 );
1502 }
1503
1504 Ok(())
1505 }
1506
1507 fn check_size_precision(&self, actual: u8, field: &str) -> anyhow::Result<()> {
1508 let expected = self.instrument.size_precision();
1509 if actual != expected {
1510 anyhow::bail!(
1511 "Invalid {field} precision {actual}, expected {expected} for {}",
1512 self.instrument.id()
1513 );
1514 }
1515
1516 Ok(())
1517 }
1518
1519 fn log_precision_mismatch(
1520 &mut self,
1521 data_type: &str,
1522 instrument_id: InstrumentId,
1523 err: &anyhow::Error,
1524 ) {
1525 self.precision_mismatch_streak = self.precision_mismatch_streak.saturating_add(1);
1526 let streak = self.precision_mismatch_streak;
1527
1528 if streak <= 3 || streak.is_multiple_of(100) {
1529 log::warn!(
1530 "Skipping {data_type} for {instrument_id}: {err} \
1531 (consecutive_precision_mismatches={streak})"
1532 );
1533 }
1534
1535 if streak == 20 {
1536 log::error!(
1537 "Precision mismatches reached {streak} consecutive events for \
1538 {instrument_id}; check instrument update flow and upstream market data"
1539 );
1540 }
1541 }
1542
1543 fn drop_incompatible_core_orders(&mut self) {
1544 let client_order_ids: Vec<ClientOrderId> = self
1545 .core
1546 .iter_orders()
1547 .filter(|order| {
1548 !self.resting_order_matches_current_instrument(order)
1549 || !self.cached_order_matches_current_instrument(order.client_order_id)
1550 })
1551 .map(|order| order.client_order_id)
1552 .collect();
1553
1554 for client_order_id in client_order_ids {
1555 let order = self
1556 .cache
1557 .borrow()
1558 .order(&client_order_id)
1559 .map(|o| o.clone());
1560
1561 if let Some(order) = order
1562 && (order.is_inflight() || order.is_open())
1563 {
1564 log::warn!(
1565 "Canceling order {client_order_id} after instrument update: \
1566 price, trigger price, or quantity is not compatible with {}",
1567 self.instrument.id()
1568 );
1569 self.cancel_order(&order, None);
1570 } else {
1571 self.delete_core_order(client_order_id);
1572 self.orders
1573 .cached_filled_qty
1574 .borrow_mut()
1575 .swap_remove(&client_order_id);
1576 }
1577 }
1578 }
1579
1580 fn cached_order_matches_current_instrument(&self, client_order_id: ClientOrderId) -> bool {
1581 self.cache
1582 .borrow()
1583 .order(&client_order_id)
1584 .is_none_or(|order| {
1585 Self::quantity_matches_precision(order.quantity(), self.instrument.size_precision())
1586 })
1587 }
1588
1589 fn resting_order_matches_current_instrument(&self, order: &RestingOrder) -> bool {
1590 order
1591 .limit_price
1592 .is_none_or(|price| self.price_matches_current_instrument(price))
1593 && order
1594 .trigger_price
1595 .is_none_or(|price| self.price_matches_current_instrument(price))
1596 }
1597
1598 fn price_matches_current_instrument(&self, price: Price) -> bool {
1599 Self::price_matches_precision(price, self.instrument.price_precision())
1600 && Self::price_matches_tick(price, self.instrument.price_increment())
1601 }
1602
1603 fn price_matches_precision(price: Price, precision: u8) -> bool {
1604 let precision_diff = FIXED_PRECISION.saturating_sub(precision);
1605 let scale = PriceRaw::pow(10, u32::from(precision_diff));
1606 price.raw() % scale == 0
1607 }
1608
1609 fn price_matches_tick(price: Price, increment: Price) -> bool {
1610 let increment_raw = increment.raw().abs();
1611 increment_raw == 0 || price.raw() % increment_raw == 0
1612 }
1613
1614 fn quantity_matches_precision(quantity: Quantity, precision: u8) -> bool {
1615 let precision_diff = FIXED_PRECISION.saturating_sub(precision);
1616 let scale = QuantityRaw::pow(10, u32::from(precision_diff));
1617 quantity.raw().is_multiple_of(scale)
1618 }
1619
1620 fn normalize_price_for_current_instrument(&self, price: Price) -> Option<Price> {
1621 if !self.price_matches_current_instrument(price) {
1622 return None;
1623 }
1624
1625 Some(Price::from_raw(
1626 price.raw(),
1627 self.instrument.price_precision(),
1628 ))
1629 }
1630
1631 fn normalize_quantity_for_current_instrument(&self, quantity: Quantity) -> Option<Quantity> {
1632 let precision = self.instrument.size_precision();
1633 if !Self::quantity_matches_precision(quantity, precision) {
1634 return None;
1635 }
1636
1637 Some(Quantity::from_raw(quantity.raw(), precision))
1638 }
1639
1640 pub fn process_order_book_delta(&mut self, delta: &OrderBookDelta) -> anyhow::Result<()> {
1649 log::debug!("Processing {delta}");
1650
1651 if matches!(delta.action, BookAction::Add | BookAction::Update) {
1653 self.check_price_precision(delta.order.price.precision, "delta order price")?;
1654 self.check_size_precision(delta.order.size.precision, "delta order size")?;
1655 }
1656
1657 if self.book_type == BookType::L1_MBP {
1659 self.iterate(delta.ts_init, AggressorSide::NoAggressor);
1660 return Ok(());
1661 }
1662
1663 self.book.apply_delta(delta)?;
1664
1665 let is_snapshot = RecordFlag::F_SNAPSHOT.matches(delta.flags);
1666 let is_last = RecordFlag::F_LAST.matches(delta.flags);
1667 let is_clear = delta.action == BookAction::Clear;
1668 let snapshot_complete = is_last && (is_snapshot || self.queue_snapshot_in_progress);
1669 if self.config.queue_position {
1670 if is_snapshot && !is_last {
1671 self.queue_snapshot_in_progress = true;
1675 }
1676
1677 if snapshot_complete {
1678 self.queue_snapshot_in_progress = false;
1679 self.rebase_queue_positions();
1680 } else if is_clear && !is_snapshot {
1681 self.rebase_queue_positions();
1682 } else if !self.queue_snapshot_in_progress {
1683 self.adjust_queue_for_delta(delta);
1684 }
1685 }
1686
1687 if self.config.queue_position && (snapshot_complete || (is_clear && !is_snapshot)) {
1688 self.seed_tob_baseline();
1689 }
1690
1691 self.iterate(delta.ts_init, AggressorSide::NoAggressor);
1692 Ok(())
1693 }
1694
1695 pub fn process_order_book_deltas(&mut self, deltas: &OrderBookDeltas) -> anyhow::Result<()> {
1704 log::debug!("Processing {deltas}");
1705
1706 for delta in &deltas.deltas {
1708 if matches!(delta.action, BookAction::Add | BookAction::Update) {
1709 self.check_price_precision(delta.order.price.precision, "delta order price")?;
1710 self.check_size_precision(delta.order.size.precision, "delta order size")?;
1711 }
1712 }
1713
1714 if self.book_type == BookType::L1_MBP {
1716 self.iterate(deltas.ts_init, AggressorSide::NoAggressor);
1717 return Ok(());
1718 }
1719
1720 self.book.apply_deltas(deltas)?;
1721
1722 let mut has_snapshot_or_clear = false;
1723
1724 if self.config.queue_position {
1725 for delta in &deltas.deltas {
1726 if RecordFlag::F_SNAPSHOT.matches(delta.flags) || delta.action == BookAction::Clear
1727 {
1728 has_snapshot_or_clear = true;
1729 break;
1730 }
1731
1732 self.adjust_queue_for_delta(delta);
1733 }
1734 }
1735
1736 if self.config.queue_position && has_snapshot_or_clear {
1737 self.queue_snapshot_in_progress = false;
1738 self.rebase_queue_positions();
1739 self.seed_tob_baseline();
1740 }
1741
1742 self.iterate(deltas.ts_init, AggressorSide::NoAggressor);
1743 Ok(())
1744 }
1745
1746 pub fn process_order_book_depth(&mut self, depth: &OrderBookDepth) -> anyhow::Result<()> {
1756 log::debug!("Processing OrderBookDepth for {}", depth.instrument_id);
1757
1758 for order in &depth.bids {
1760 if order.side.is_none() || !order.size.is_positive() {
1761 continue;
1762 }
1763
1764 self.check_price_precision(order.price.precision, "bid price")?;
1765 self.check_size_precision(order.size.precision, "bid size")?;
1766 }
1767
1768 for order in &depth.asks {
1769 if order.side.is_none() || !order.size.is_positive() {
1770 continue;
1771 }
1772
1773 self.check_price_precision(order.price.precision, "ask price")?;
1774 self.check_size_precision(order.size.precision, "ask size")?;
1775 }
1776
1777 let top_bid = Self::first_valid_depth_order(&depth.bids, OrderSide::Buy);
1778 let top_ask = Self::first_valid_depth_order(&depth.asks, OrderSide::Sell);
1779
1780 if self.book_type == BookType::L1_MBP {
1783 let quote = QuoteTick::new(
1784 depth.instrument_id,
1785 Self::depth_quote_price(top_bid, self.instrument.price_precision()),
1786 Self::depth_quote_price(top_ask, self.instrument.price_precision()),
1787 Self::depth_quote_size(top_bid, self.instrument.size_precision()),
1788 Self::depth_quote_size(top_ask, self.instrument.size_precision()),
1789 depth.ts_event,
1790 depth.ts_init,
1791 );
1792 self.book.update_quote_tick("e)?;
1793 self.reset_trade_liquidity(quote.ts_event);
1794 self.last_quote_bid = top_bid.map(|order| order.price);
1795 self.last_quote_ask = top_ask.map(|order| order.price);
1796 } else {
1797 self.book.apply_depth(depth)?;
1798 }
1799
1800 if self.config.queue_position {
1802 self.rebase_queue_positions();
1803 let bid_price_raw = top_bid.map_or(0, |order| order.price.raw());
1804 let bid_size_raw = top_bid.map_or(0, |order| order.size.raw());
1805 let ask_price_raw = top_ask.map_or(0, |order| order.price.raw());
1806 let ask_size_raw = top_ask.map_or(0, |order| order.size.raw());
1807
1808 self.decrement_l1_queue_on_quote(
1809 bid_price_raw,
1810 bid_size_raw,
1811 ask_price_raw,
1812 ask_size_raw,
1813 );
1814
1815 self.prev_bid_price_raw = bid_price_raw;
1816 self.prev_ask_price_raw = ask_price_raw;
1817 self.tob_initialized = true;
1818 }
1819
1820 self.iterate(depth.ts_init, AggressorSide::NoAggressor);
1821 Ok(())
1822 }
1823
1824 fn first_valid_depth_order(orders: &[BookOrder], side: OrderSide) -> Option<BookOrder> {
1825 orders
1826 .iter()
1827 .copied()
1828 .find(|order| order.side == Some(side) && order.size.is_positive())
1829 }
1830
1831 fn depth_quote_price(order: Option<BookOrder>, price_precision: u8) -> Price {
1832 order.map_or_else(|| Price::zero(price_precision), |order| order.price)
1833 }
1834
1835 fn depth_quote_size(order: Option<BookOrder>, size_precision: u8) -> Quantity {
1836 order.map_or_else(|| Quantity::zero(size_precision), |order| order.size)
1837 }
1838
1839 pub fn process_mark_price(&mut self, mark: &MarkPriceUpdate) {
1843 self.core.mark = Some(mark.value);
1844 self.iterate_with_mode(
1845 mark.ts_init,
1846 AggressorSide::NoAggressor,
1847 OrderMatchMode::StopTriggers(TriggerType::MarkPrice),
1848 );
1849 }
1850
1851 pub fn process_quote_tick(&mut self, quote: &QuoteTick) {
1853 log::debug!("Processing {quote}");
1854
1855 if let Err(e) = self.check_price_precision(quote.bid_price.precision, "bid_price") {
1856 self.log_precision_mismatch("quote tick", quote.instrument_id, &e);
1857 return;
1858 }
1859
1860 if let Err(e) = self.check_price_precision(quote.ask_price.precision, "ask_price") {
1861 self.log_precision_mismatch("quote tick", quote.instrument_id, &e);
1862 return;
1863 }
1864
1865 if let Err(e) = self.check_size_precision(quote.bid_size.precision, "bid_size") {
1866 self.log_precision_mismatch("quote tick", quote.instrument_id, &e);
1867 return;
1868 }
1869
1870 if let Err(e) = self.check_size_precision(quote.ask_size.precision, "ask_size") {
1871 self.log_precision_mismatch("quote tick", quote.instrument_id, &e);
1872 return;
1873 }
1874
1875 self.precision_mismatch_streak = 0;
1876
1877 if self.book_type == BookType::L1_MBP {
1878 if quote.ts_event < self.book.ts_last {
1880 log::warn!(
1881 "Skipping stale quote: ts_event {} < book.ts_last {} for {}",
1882 quote.ts_event,
1883 self.book.ts_last,
1884 self.book.instrument_id,
1885 );
1886 self.iterate(quote.ts_init, AggressorSide::NoAggressor);
1887 return;
1888 }
1889
1890 if !self.update_quote_tick_or_skip(quote, "quote tick") {
1891 return;
1892 }
1893
1894 if self.config.queue_position {
1895 self.decrement_l1_queue_on_quote(
1896 quote.bid_price.raw(),
1897 quote.bid_size.raw(),
1898 quote.ask_price.raw(),
1899 quote.ask_size.raw(),
1900 );
1901 self.prev_bid_price_raw = quote.bid_price.raw();
1902 self.prev_ask_price_raw = quote.ask_price.raw();
1903 self.tob_initialized = true;
1904 }
1905
1906 self.last_quote_bid = Some(quote.bid_price);
1907 self.last_quote_ask = Some(quote.ask_price);
1908 }
1909
1910 self.iterate(quote.ts_init, AggressorSide::NoAggressor);
1911 }
1912
1913 pub fn process_bar(&mut self, bar: &Bar) {
1923 log::debug!("Processing {bar}");
1924
1925 debug_assert!(
1926 bar.high >= bar.open
1927 && bar.high >= bar.low
1928 && bar.high >= bar.close
1929 && bar.low <= bar.open
1930 && bar.low <= bar.close,
1931 "OHLC invariant violated for {bar}"
1932 );
1933
1934 if !self.config.bar_execution || self.book_type != BookType::L1_MBP {
1936 return;
1937 }
1938
1939 let bar_type = bar.bar_type;
1940
1941 if bar_type.aggregation_source() == AggregationSource::Internal {
1943 return;
1944 }
1945
1946 if let Err(e) = self.check_price_precision(bar.open.precision, "bar open") {
1947 self.log_precision_mismatch("bar", bar.instrument_id(), &e);
1948 return;
1949 }
1950
1951 if let Err(e) = self.check_price_precision(bar.high.precision, "bar high") {
1952 self.log_precision_mismatch("bar", bar.instrument_id(), &e);
1953 return;
1954 }
1955
1956 if let Err(e) = self.check_price_precision(bar.low.precision, "bar low") {
1957 self.log_precision_mismatch("bar", bar.instrument_id(), &e);
1958 return;
1959 }
1960
1961 if let Err(e) = self.check_price_precision(bar.close.precision, "bar close") {
1962 self.log_precision_mismatch("bar", bar.instrument_id(), &e);
1963 return;
1964 }
1965
1966 if let Err(e) = self.check_size_precision(bar.volume.precision, "bar volume") {
1967 self.log_precision_mismatch("bar", bar.instrument_id(), &e);
1968 return;
1969 }
1970
1971 self.precision_mismatch_streak = 0;
1972
1973 let price_type = bar_type.spec().price_type;
1974 if price_type == PriceType::Mark {
1975 log::warn!(
1976 "Cannot process bar for {} with `PriceType::Mark`, mark price bars are not supported for bar execution",
1977 bar.instrument_id(),
1978 );
1979 return;
1980 }
1981
1982 if !bar_type.spec().is_time_aggregated() {
1983 log::warn!(
1984 "Cannot process bar {bar_type}, bar execution requires time-aggregated bars",
1985 );
1986 return;
1987 }
1988
1989 let execution_bar_type = match self.execution_bar_types.get(&bar.instrument_id()) {
1990 Some(execution_bar_type) => *execution_bar_type,
1991 None => {
1992 self.execution_bar_types
1993 .insert(bar.instrument_id(), bar_type);
1994 self.execution_bar_deltas
1995 .insert(bar_type, bar_type.spec().timedelta());
1996 bar_type
1997 }
1998 };
1999
2000 if execution_bar_type != bar_type {
2001 let bar_type_timedelta = *self
2002 .execution_bar_deltas
2003 .entry(bar_type)
2004 .or_insert_with(|| bar_type.spec().timedelta());
2005
2006 if self.execution_bar_deltas.get(&execution_bar_type).unwrap() < &bar_type_timedelta {
2007 return;
2008 }
2009
2010 self.execution_bar_types
2011 .insert(bar_type.instrument_id(), bar_type);
2012 }
2013
2014 match price_type {
2015 PriceType::Last | PriceType::Mid => self.process_trade_ticks_from_bar(bar),
2016 PriceType::Bid => {
2017 self.last_bar_bid = Some(bar.to_owned());
2018 self.process_quote_ticks_from_bar();
2019 }
2020 PriceType::Ask => {
2021 self.last_bar_ask = Some(bar.to_owned());
2022 self.process_quote_ticks_from_bar();
2023 }
2024 PriceType::Mark => {
2025 unreachable!("PriceType::Mark bars return before execution bar state updates")
2026 }
2027 }
2028 }
2029
2030 fn process_trade_ticks_from_bar(&mut self, bar: &Bar) {
2031 self.collapse_bar_trades = self.has_nothing_to_match(bar.ts_init);
2034
2035 let sizes = BarTickSizes::from_volume(bar.volume, self.instrument.size_increment());
2036
2037 let aggressor_side = if self.core.last.is_none_or(|last| bar.open > last) {
2038 AggressorSide::Buy
2039 } else {
2040 AggressorSide::Sell
2041 };
2042
2043 if sizes.open.is_positive() || self.core.last.is_none_or(|last| bar.open != last) {
2045 self.fill_at_market = true;
2046
2047 if !self.process_bar_trade_tick(
2048 bar,
2049 bar.open,
2050 sizes.open,
2051 aggressor_side,
2052 "bar open trade tick",
2053 ) {
2054 return;
2055 }
2056 }
2057
2058 let high_first = self.bar_high_first(bar);
2061 if high_first {
2062 self.process_bar_high(bar, sizes.high);
2063 self.process_bar_low(bar, sizes.low);
2064 } else {
2065 self.process_bar_low(bar, sizes.low);
2066 self.process_bar_high(bar, sizes.high);
2067 }
2068
2069 if sizes.close.is_positive() || self.core.last.is_some_and(|last| bar.close != last) {
2070 let aggressor_side = if bar.close > self.core.last.unwrap() {
2071 AggressorSide::Buy
2072 } else {
2073 AggressorSide::Sell
2074 };
2075
2076 if !self.process_bar_trade_tick(
2077 bar,
2078 bar.close,
2079 sizes.close,
2080 aggressor_side,
2081 "bar close trade tick",
2082 ) {
2083 return;
2084 }
2085 }
2086
2087 self.collapse_bar_trades = false;
2088
2089 if let Some((price, size, aggressor_side)) = self.last_bar_trade.take() {
2090 let last = self.core.last;
2092 self.process_bar_trade_tick(bar, price, size, aggressor_side, "bar trade tick");
2093 self.core.last = last;
2094 }
2095
2096 self.fill_at_market = true;
2097 }
2098
2099 fn process_bar_high(&mut self, bar: &Bar, size: Quantity) {
2100 if size.is_positive() || self.core.last.is_some_and(|last| bar.high > last) {
2101 self.process_bar_trade_tick(
2102 bar,
2103 bar.high,
2104 size,
2105 AggressorSide::Buy,
2106 "bar high trade tick",
2107 );
2108 }
2109 }
2110
2111 fn process_bar_low(&mut self, bar: &Bar, size: Quantity) {
2112 if size.is_positive() || self.core.last.is_some_and(|last| bar.low < last) {
2113 self.process_bar_trade_tick(
2114 bar,
2115 bar.low,
2116 size,
2117 AggressorSide::Sell,
2118 "bar low trade tick",
2119 );
2120 }
2121 }
2122
2123 fn process_bar_trade_tick(
2124 &mut self,
2125 bar: &Bar,
2126 price: Price,
2127 size: Quantity,
2128 aggressor_side: AggressorSide,
2129 context: &str,
2130 ) -> bool {
2131 if price != bar.open {
2133 self.fill_at_market = false;
2134 }
2135
2136 if size.is_zero() {
2137 self.core.set_last_raw(price);
2138 return true;
2139 }
2140
2141 if self.collapse_bar_trades {
2142 if self.last_bar_trade.is_some() {
2144 self.ids_generator.skip_trade_id();
2145 }
2146 self.last_bar_trade = Some((price, size, aggressor_side));
2147 self.core.set_last_raw(price);
2148 return true;
2149 }
2150
2151 let trade_tick = TradeTick::new(
2152 bar.instrument_id(),
2153 price,
2154 size,
2155 aggressor_side,
2156 self.ids_generator.generate_trade_id(bar.ts_init),
2157 bar.ts_init,
2158 bar.ts_init,
2159 );
2160
2161 if !self.update_trade_tick_or_skip(&trade_tick, context) {
2162 return false;
2163 }
2164
2165 self.core.set_last_raw(price);
2167 self.iterate(trade_tick.ts_init, AggressorSide::NoAggressor);
2168 true
2169 }
2170
2171 fn process_quote_ticks_from_bar(&mut self) {
2172 let (Some(bid_bar), Some(ask_bar)) = (self.last_bar_bid, self.last_bar_ask) else {
2174 return;
2175 };
2176
2177 if bid_bar.ts_init != ask_bar.ts_init {
2178 return;
2179 }
2180
2181 let size_increment = self.instrument.size_increment();
2182 let bid_sizes = BarTickSizes::from_volume(bid_bar.volume, size_increment);
2183 let ask_sizes = BarTickSizes::from_volume(ask_bar.volume, size_increment);
2184 let mut has_current_bid = false;
2185 let mut has_current_ask = false;
2186
2187 let mut quote_tick = QuoteTick::new(
2188 self.book.instrument_id,
2189 bid_bar.open,
2190 ask_bar.open,
2191 bid_sizes.open,
2192 ask_sizes.open,
2193 bid_bar.ts_init,
2194 bid_bar.ts_init,
2195 );
2196
2197 self.fill_at_market = true;
2199
2200 if !self.process_bar_quote_tick(
2201 "e_tick,
2202 "bar open quote tick",
2203 &mut has_current_bid,
2204 &mut has_current_ask,
2205 ) {
2206 return;
2207 }
2208
2209 let high_first = self.bar_high_first(&bid_bar);
2212
2213 let high_leg = (
2214 bid_bar.high,
2215 ask_bar.high,
2216 bid_sizes.high,
2217 ask_sizes.high,
2218 "bar high quote tick",
2219 );
2220 let low_leg = (
2221 bid_bar.low,
2222 ask_bar.low,
2223 bid_sizes.low,
2224 ask_sizes.low,
2225 "bar low quote tick",
2226 );
2227
2228 let legs = if high_first {
2229 [high_leg, low_leg]
2230 } else {
2231 [low_leg, high_leg]
2232 };
2233
2234 for (bid_price, ask_price, bid_size, ask_size, context) in legs {
2236 self.fill_at_market = false;
2237 quote_tick.bid_price = bid_price;
2238 quote_tick.ask_price = ask_price;
2239 quote_tick.bid_size = bid_size;
2240 quote_tick.ask_size = ask_size;
2241
2242 if !self.process_bar_quote_tick(
2243 "e_tick,
2244 context,
2245 &mut has_current_bid,
2246 &mut has_current_ask,
2247 ) {
2248 return;
2249 }
2250 }
2251
2252 self.fill_at_market = false;
2254 quote_tick.bid_price = bid_bar.close;
2255 quote_tick.ask_price = ask_bar.close;
2256 quote_tick.bid_size = bid_sizes.close;
2257 quote_tick.ask_size = ask_sizes.close;
2258
2259 if !self.process_bar_quote_tick(
2260 "e_tick,
2261 "bar close quote tick",
2262 &mut has_current_bid,
2263 &mut has_current_ask,
2264 ) {
2265 return;
2266 }
2267
2268 self.last_bar_bid = None;
2269 self.last_bar_ask = None;
2270 self.fill_at_market = true;
2271 }
2272
2273 fn process_bar_quote_tick(
2274 &mut self,
2275 quote: &QuoteTick,
2276 context: &str,
2277 has_current_bid: &mut bool,
2278 has_current_ask: &mut bool,
2279 ) -> bool {
2280 let has_bid_size = quote.bid_size.non_zero();
2281 let has_ask_size = quote.ask_size.non_zero();
2282 let mut book_changed = false;
2283 let mut bid_cleared = false;
2284 let mut ask_cleared = false;
2285
2286 match (has_bid_size, has_ask_size) {
2287 (true, true) => {
2288 if !self.update_quote_tick_or_skip(quote, context) {
2289 return false;
2290 }
2291
2292 *has_current_bid = true;
2293 *has_current_ask = true;
2294 book_changed = true;
2295 }
2296 _ => {
2297 if has_bid_size {
2298 self.update_bar_quote_bid(quote);
2299 *has_current_bid = true;
2300 book_changed = true;
2301 } else if !*has_current_bid {
2302 self.clear_bar_quote_bid(quote);
2303 *has_current_bid = true;
2304 book_changed = true;
2305 bid_cleared = true;
2306 }
2307
2308 if has_ask_size {
2309 self.update_bar_quote_ask(quote);
2310 *has_current_ask = true;
2311 book_changed = true;
2312 } else if !*has_current_ask {
2313 self.clear_bar_quote_ask(quote);
2314 *has_current_ask = true;
2315 book_changed = true;
2316 ask_cleared = true;
2317 }
2318 }
2319 }
2320
2321 if book_changed
2322 && let (Some(best_bid), Some(best_ask)) =
2323 (self.book.best_bid_price(), self.book.best_ask_price())
2324 && best_bid > best_ask
2325 {
2326 if has_bid_size && !has_ask_size {
2327 self.clear_bar_quote_ask(quote);
2328 ask_cleared = true;
2329 } else if has_ask_size && !has_bid_size {
2330 self.clear_bar_quote_bid(quote);
2331 bid_cleared = true;
2332 }
2333 }
2334
2335 if has_bid_size {
2336 self.last_quote_bid = Some(quote.bid_price);
2337 } else if bid_cleared {
2338 self.last_quote_bid = None;
2339 }
2340
2341 if has_ask_size {
2342 self.last_quote_ask = Some(quote.ask_price);
2343 } else if ask_cleared {
2344 self.last_quote_ask = None;
2345 }
2346
2347 if !book_changed {
2348 return true;
2349 }
2350
2351 self.reset_trade_liquidity(quote.ts_event);
2352
2353 self.iterate(quote.ts_init, AggressorSide::NoAggressor);
2354 true
2355 }
2356
2357 fn bar_high_first(&self, bar: &Bar) -> bool {
2358 !self.config.bar_adaptive_high_low_ordering || bar.high - bar.open < bar.open - bar.low
2359 }
2360
2361 fn update_bar_quote_bid(&mut self, quote: &QuoteTick) {
2362 let bid = BookOrder::new(
2363 OrderSide::Buy,
2364 quote.bid_price,
2365 quote.bid_size,
2366 OrderSide::Buy as u64,
2367 );
2368 self.book
2369 .add(bid, 0, self.book.sequence.saturating_add(1), quote.ts_event);
2370 }
2371
2372 fn clear_bar_quote_bid(&mut self, quote: &QuoteTick) {
2373 self.book
2374 .clear_bids(self.book.sequence.saturating_add(1), quote.ts_event);
2375 }
2376
2377 fn update_bar_quote_ask(&mut self, quote: &QuoteTick) {
2378 let ask = BookOrder::new(
2379 OrderSide::Sell,
2380 quote.ask_price,
2381 quote.ask_size,
2382 OrderSide::Sell as u64,
2383 );
2384 self.book
2385 .add(ask, 0, self.book.sequence.saturating_add(1), quote.ts_event);
2386 }
2387
2388 fn clear_bar_quote_ask(&mut self, quote: &QuoteTick) {
2389 self.book
2390 .clear_asks(self.book.sequence.saturating_add(1), quote.ts_event);
2391 }
2392
2393 pub fn process_trade_tick(&mut self, trade: &TradeTick) {
2404 log::debug!("Processing {trade}");
2405
2406 if let Err(e) = self.check_price_precision(trade.price.precision, "trade price") {
2407 self.log_precision_mismatch("trade tick", trade.instrument_id, &e);
2408 return;
2409 }
2410
2411 if let Err(e) = self.check_size_precision(trade.size.precision, "trade size") {
2412 self.log_precision_mismatch("trade tick", trade.instrument_id, &e);
2413 return;
2414 }
2415
2416 self.precision_mismatch_streak = 0;
2417
2418 let price_raw = trade.price.raw();
2419
2420 if self.book_type == BookType::L1_MBP {
2421 if trade.ts_event < self.book.ts_last {
2423 log::warn!(
2424 "Skipping stale trade: ts_event {} < book.ts_last {} for {}",
2425 trade.ts_event,
2426 self.book.ts_last,
2427 self.book.instrument_id,
2428 );
2429 self.iterate(trade.ts_init, AggressorSide::NoAggressor);
2430 return;
2431 }
2432
2433 if !self.update_trade_tick_or_skip(trade, "trade tick") {
2434 return;
2435 }
2436 }
2437
2438 self.core.set_last_raw(trade.price);
2439
2440 if !self.config.trade_execution {
2441 if self.book_type == BookType::L1_MBP {
2442 if let Some(bid) = self.book.best_bid_price() {
2443 self.core.set_bid_raw(bid);
2444 }
2445
2446 if let Some(ask) = self.book.best_ask_price() {
2447 self.core.set_ask_raw(ask);
2448 }
2449 } else {
2450 self.iterate_with_mode(
2451 trade.ts_init,
2452 AggressorSide::NoAggressor,
2453 OrderMatchMode::StopTriggers(TriggerType::LastPrice),
2454 );
2455 }
2456
2457 return;
2458 }
2459
2460 let aggressor_side = trade.aggressor_side;
2461
2462 match aggressor_side {
2463 AggressorSide::Buy => {
2464 if self.core.ask.is_none_or(|ask| trade.price > ask) {
2467 self.core.set_ask_raw(trade.price);
2468 }
2469
2470 if self.core.bid.is_none() {
2472 self.core.set_bid_raw(trade.price);
2473 }
2474 }
2475 AggressorSide::Sell => {
2476 if self.core.bid.is_none_or(|bid| trade.price < bid) {
2479 self.core.set_bid_raw(trade.price);
2480 }
2481
2482 if self.core.ask.is_none() {
2484 self.core.set_ask_raw(trade.price);
2485 }
2486 }
2487 AggressorSide::NoAggressor => {
2488 if self.core.bid.is_none_or(|bid| trade.price <= bid) {
2489 self.core.set_bid_raw(trade.price);
2490 }
2491
2492 if self.core.ask.is_none_or(|ask| trade.price >= ask) {
2493 self.core.set_ask_raw(trade.price);
2494 }
2495 }
2496 }
2497
2498 let original_bid = self.core.bid;
2499 let original_ask = self.core.ask;
2500
2501 let is_l1 = self.book_type == BookType::L1_MBP;
2504
2505 match aggressor_side {
2506 AggressorSide::Sell => {
2507 if (is_l1 && self.last_quote_ask.is_none())
2508 || original_ask.is_some_and(|ask| trade.price < ask)
2509 {
2510 self.core.set_ask_raw(trade.price);
2511 }
2512 }
2513 AggressorSide::Buy => {
2514 if (is_l1 && self.last_quote_bid.is_none())
2515 || original_bid.is_some_and(|bid| trade.price > bid)
2516 {
2517 self.core.set_bid_raw(trade.price);
2518 }
2519 }
2520 AggressorSide::NoAggressor => {
2521 self.core.set_bid_raw(trade.price);
2523 self.core.set_ask_raw(trade.price);
2524 }
2525 }
2526
2527 self.start_trade_iteration(trade.size);
2528
2529 if self.config.liquidity_consumption && self.book_type != BookType::L1_MBP {
2530 self.seed_trade_consumption(
2531 price_raw,
2532 trade.size.raw(),
2533 trade.ts_event,
2534 aggressor_side,
2535 );
2536 }
2537
2538 self.iterate(trade.ts_init, aggressor_side);
2539
2540 self.finish_trade_iteration();
2541
2542 if self.book_type == BookType::L1_MBP {
2548 match aggressor_side {
2549 AggressorSide::Sell => {
2550 if let Some(ask) = self.last_quote_ask {
2551 self.core.ask = Some(ask);
2552 }
2553 }
2554 AggressorSide::Buy => {
2555 if let Some(bid) = self.last_quote_bid {
2556 self.core.bid = Some(bid);
2557 }
2558 }
2559 AggressorSide::NoAggressor => {}
2560 }
2561 } else {
2562 match aggressor_side {
2563 AggressorSide::Sell => {
2564 if let Some(ask) = original_ask
2565 && trade.price < ask
2566 {
2567 self.core.ask = Some(ask);
2568 }
2569 }
2570 AggressorSide::Buy => {
2571 if let Some(bid) = original_bid
2572 && trade.price > bid
2573 {
2574 self.core.bid = Some(bid);
2575 }
2576 }
2577 AggressorSide::NoAggressor => {}
2578 }
2579 }
2580 }
2581
2582 fn start_trade_iteration(&mut self, size: Quantity) {
2583 self.last_trade_size = Some(size);
2584 self.trade_consumption = 0;
2585 self.l1_trade_size = (self.book_type == BookType::L1_MBP
2586 && self.config.liquidity_consumption)
2587 .then_some(size.raw());
2588 }
2589
2590 fn finish_trade_iteration(&mut self) {
2591 self.last_trade_size = None;
2592
2593 if self.l1_trade_size.is_none() {
2595 self.trade_consumption = 0;
2596 }
2597 }
2598
2599 fn reset_trade_liquidity(&mut self, timestamp: UnixNanos) {
2600 if timestamp >= self.book.ts_last {
2601 self.l1_trade_size = None;
2602 self.trade_consumption = 0;
2603 }
2604 }
2605
2606 fn update_quote_tick_or_skip(&mut self, quote: &QuoteTick, context: &str) -> bool {
2607 if let Err(e) = self.book.update_quote_tick(quote) {
2608 log::warn!(
2609 "Skipping {context} for {}: update_quote_tick failed: {e}",
2610 quote.instrument_id,
2611 );
2612 return false;
2613 }
2614
2615 self.reset_trade_liquidity(quote.ts_event);
2616 true
2617 }
2618
2619 fn update_trade_tick_or_skip(&mut self, trade: &TradeTick, context: &str) -> bool {
2620 if let Err(e) = self.book.update_trade_tick(trade) {
2621 log::warn!(
2622 "Skipping {context} for {}: update_trade_tick failed: {e}",
2623 trade.instrument_id,
2624 );
2625 return false;
2626 }
2627
2628 self.reset_trade_liquidity(trade.ts_event);
2629 true
2630 }
2631
2632 pub fn process_status(&mut self, action: MarketStatusAction) {
2634 log::debug!("Processing {action}");
2635 let market_status = self
2636 .pending_resolution
2637 .as_mut()
2638 .unwrap_or(&mut self.market_status);
2639
2640 match action {
2641 MarketStatusAction::Trading | MarketStatusAction::PreOpen
2642 if matches!(
2643 *market_status,
2644 MarketStatus::Closed | MarketStatus::Paused | MarketStatus::Suspended
2645 ) =>
2646 {
2647 *market_status = MarketStatus::Open;
2648 }
2649 MarketStatusAction::Pause if *market_status == MarketStatus::Open => {
2650 *market_status = MarketStatus::Paused;
2651 }
2652 MarketStatusAction::Suspend if *market_status == MarketStatus::Open => {
2653 *market_status = MarketStatus::Suspended;
2654 }
2655 MarketStatusAction::Halt | MarketStatusAction::Close
2656 if *market_status == MarketStatus::Open =>
2657 {
2658 *market_status = MarketStatus::Closed;
2659 }
2660 _ => {}
2661 }
2662 }
2663
2664 pub fn process_instrument_close(&mut self, close: InstrumentClose) {
2670 if close.instrument_id != self.instrument.id() {
2671 log::warn!(
2672 "Received instrument close for unknown instrument_id: {}",
2673 close.instrument_id
2674 );
2675 return;
2676 }
2677
2678 if close.close_type == InstrumentCloseType::ContractExpired {
2679 self.instrument_close = Some(close);
2680 self.iterate(close.ts_init, AggressorSide::NoAggressor);
2681 }
2682 }
2683
2684 pub fn process_instrument_expiration(&mut self, timestamp_ns: UnixNanos) {
2689 self.check_instrument_expiration(timestamp_ns, false, &[]);
2690 }
2691
2692 #[must_use]
2694 pub const fn is_expiration_processed(&self) -> bool {
2695 self.expiration_processed
2696 }
2697
2698 pub fn has_pending_fills(&mut self) -> bool {
2700 self.purge_applied_fills();
2701 !self.pending_fills.is_empty()
2702 }
2703
2704 fn requires_pending_resolution(&self) -> bool {
2705 matches!(self.instrument, InstrumentAny::BinaryOption(_))
2706 }
2707
2708 fn cancel_open_orders_for_expiration(&mut self, excluded: &[ClientOrderId]) {
2709 let instrument_id = self.instrument.id();
2714
2715 let expiration_order_ids: IndexSet<ClientOrderId> = {
2716 let cache = self.cache.borrow();
2717 let mut order_ids = IndexSet::new();
2718 for order_info in self.get_open_orders() {
2719 order_ids.insert(order_info.client_order_id);
2720 }
2721
2722 for order in cache.orders(None, Some(&instrument_id), None, None, None) {
2723 if order.is_open() || order.is_inflight() {
2724 order_ids.insert(order.client_order_id());
2725 }
2726 }
2727
2728 order_ids.retain(|client_order_id| !excluded.contains(client_order_id));
2729 order_ids
2730 };
2731
2732 for client_order_id in expiration_order_ids {
2733 if let Some(order) = self.order_snapshot(client_order_id)
2734 && !self.contingent_order_is_closed(&order)
2735 {
2736 self.cancel_order_excluding(&order, None, excluded);
2737 }
2738 }
2739 }
2740
2741 fn enter_pending_resolution(&mut self, excluded: &[ClientOrderId]) {
2742 if self.pending_resolution.is_some() {
2743 return;
2744 }
2745
2746 self.pending_resolution = Some(self.market_status);
2747 self.market_status = MarketStatus::Closed;
2748 self.cancel_open_orders_for_expiration(excluded);
2749 log::info!(
2750 "{} expired and is now pending resolution; open orders canceled and new orders blocked",
2751 self.instrument.id()
2752 );
2753 }
2754
2755 fn check_instrument_expiration(
2756 &mut self,
2757 timestamp_ns: UnixNanos,
2758 defer_settlement: bool,
2759 excluded: &[ClientOrderId],
2760 ) {
2761 if self.expiration_processed || self.option_settlement_failed {
2762 return;
2763 }
2764
2765 let timestamp_triggered = self
2766 .instrument
2767 .expiration_ns()
2768 .is_some_and(|ns| ns != UnixNanos::default() && timestamp_ns >= ns);
2769
2770 if !timestamp_triggered && self.instrument_close.is_none() {
2771 return;
2772 }
2773
2774 if self.instrument_close.is_none()
2775 && timestamp_triggered
2776 && self.requires_pending_resolution()
2777 {
2778 self.enter_pending_resolution(excluded);
2779 return;
2780 }
2781
2782 self.enter_pending_resolution(excluded);
2783
2784 if self.has_pending_fills() {
2786 return;
2787 }
2788
2789 if matches!(
2790 self.instrument,
2791 InstrumentAny::OptionContract(_) | InstrumentAny::CryptoOption(_)
2792 ) {
2793 if defer_settlement
2796 && self.instrument_close.is_none()
2797 && self.instrument.expiration_ns() == Some(timestamp_ns)
2798 {
2799 return;
2800 }
2801
2802 match self.process_option_expiry(timestamp_ns) {
2803 Ok(true) => {
2804 self.expiration_processed = true;
2805 self.pending_resolution = None;
2806 self.instrument_close.take();
2807 self.option_settlement_warning = None;
2808 log::info!("{} reached expiration", self.instrument.id());
2809 }
2810 Ok(false) => {}
2811 Err(e) => {
2812 self.option_settlement_failed = true;
2813 log::error!(
2814 "Option settlement failed terminally for {}: {e}",
2815 self.instrument.id()
2816 );
2817 }
2818 }
2819
2820 return;
2821 }
2822
2823 self.expiration_processed = true;
2824 self.pending_resolution = None;
2825 let close = self.instrument_close.take();
2826 log::info!("{} reached expiration", self.instrument.id());
2827
2828 let instrument_id = self.instrument.id();
2829
2830 let positions: Vec<(
2831 TraderId,
2832 StrategyId,
2833 AccountId,
2834 PositionId,
2835 OrderSide,
2836 Quantity,
2837 )> = {
2838 let cache = self.cache.borrow();
2839 cache
2840 .positions_open(None, Some(&instrument_id), None, None, None)
2841 .into_iter()
2842 .filter_map(|pos| {
2843 OrderCore::closing_side(pos.side).map(|closing_side| {
2844 (
2845 pos.trader_id,
2846 pos.strategy_id,
2847 pos.account_id,
2848 pos.id,
2849 closing_side,
2850 pos.quantity,
2851 )
2852 })
2853 })
2854 .collect()
2855 };
2856
2857 let ts_now = self.clock.borrow().timestamp_ns();
2858 let close_price = close.as_ref().map(|close| close.close_price);
2859
2860 for (trader_id, strategy_id, account_id, position_id, closing_side, quantity) in positions {
2861 let client_order_id =
2862 ClientOrderId::from(format!("EXPIRATION-{}-{}", self.venue, UUID4::new()).as_str());
2863 let mut order = OrderAny::Market(MarketOrder::new(
2864 trader_id,
2865 strategy_id,
2866 instrument_id,
2867 client_order_id,
2868 closing_side,
2869 quantity,
2870 TimeInForce::Gtc,
2871 UUID4::new(),
2872 ts_now,
2873 true, false,
2875 None,
2876 None,
2877 None,
2878 None,
2879 None,
2880 None,
2881 None,
2882 Some(vec![Ustr::from(&format!(
2883 "EXPIRATION_{}_CLOSE",
2884 self.venue
2885 ))]),
2886 ));
2887 order.set_liquidity_side(LiquiditySide::Taker);
2888
2889 let add_result =
2890 self.cache
2891 .borrow_mut()
2892 .add_order(order.clone(), Some(position_id), None, false);
2893
2894 if add_result.is_err() {
2895 log::debug!("Expiration order already in cache: {client_order_id}");
2896 } else {
2897 self.publish_order_initialized(&order);
2898 }
2899
2900 let venue_order_id = self.ids_generator.get_venue_order_id(&order).unwrap();
2901
2902 self.account_ids.insert(trader_id, account_id);
2905 self.generate_order_accepted(&order, venue_order_id);
2906
2907 if let Some(fill_price) = close_price {
2908 if let Err(e) = self.apply_fills(
2909 &order,
2910 &[(fill_price, quantity)],
2911 LiquiditySide::Taker,
2912 Some(position_id),
2913 None,
2914 None,
2915 false,
2916 ) {
2917 log::error!("Cannot fill expiration order {client_order_id}: {e}");
2918 }
2919 } else {
2920 self.fill_market_order(client_order_id);
2921 }
2922 }
2923 }
2924
2925 pub fn liquidate_open_positions(
2940 &mut self,
2941 ts_now: UnixNanos,
2942 cancel_open_orders: bool,
2943 settlement_currency: Currency,
2944 ) {
2945 if self.instrument.settlement_currency() != settlement_currency {
2947 return;
2948 }
2949
2950 if cancel_open_orders {
2951 let open_orders: Vec<RestingOrder> = self.get_open_orders();
2952 for order_info in &open_orders {
2953 let order = {
2954 let cache = self.cache.borrow();
2955 cache.order_owned(&order_info.client_order_id)
2956 };
2957
2958 if let Some(order) = order {
2959 self.cancel_order(&order, None);
2960 }
2961 }
2962 }
2963
2964 let instrument_id = self.instrument.id();
2965
2966 let positions: Vec<(
2967 TraderId,
2968 StrategyId,
2969 AccountId,
2970 PositionId,
2971 OrderSide,
2972 Quantity,
2973 )> = {
2974 let cache = self.cache.borrow();
2975 cache
2976 .positions_open(None, Some(&instrument_id), None, None, None)
2977 .into_iter()
2978 .filter_map(|pos| {
2979 OrderCore::closing_side(pos.side).map(|closing_side| {
2980 (
2981 pos.trader_id,
2982 pos.strategy_id,
2983 pos.account_id,
2984 pos.id,
2985 closing_side,
2986 pos.quantity,
2987 )
2988 })
2989 })
2990 .collect()
2991 };
2992
2993 for (trader_id, strategy_id, account_id, position_id, closing_side, quantity) in positions {
2994 let has_price = if closing_side == OrderSide::Sell {
2996 self.best_bid_price().is_some()
2997 } else {
2998 self.best_ask_price().is_some()
2999 };
3000
3001 if !has_price {
3002 log::warn!(
3003 "LIQUIDATION: no price available for {instrument_id} position {position_id}, skipping"
3004 );
3005 continue;
3006 }
3007
3008 let client_order_id = ClientOrderId::from(
3009 format!("LIQUIDATION-{}-{}", self.venue, UUID4::new()).as_str(),
3010 );
3011 let order = OrderAny::Market(MarketOrder::new(
3012 trader_id,
3013 strategy_id,
3014 instrument_id,
3015 client_order_id,
3016 closing_side,
3017 quantity,
3018 TimeInForce::Ioc,
3019 UUID4::new(),
3020 ts_now,
3021 true, false,
3023 None,
3024 None,
3025 None,
3026 None,
3027 None,
3028 None,
3029 None,
3030 Some(vec![Ustr::from(&format!(
3031 "LIQUIDATION_{}_CLOSE",
3032 self.venue
3033 ))]),
3034 ));
3035
3036 let venue_order_id = self.ids_generator.get_venue_order_id(&order).unwrap();
3037 {
3038 let mut cache = self.cache.borrow_mut();
3039 if let Err(e) = cache.add_order(order.clone(), Some(position_id), None, false) {
3040 log::debug!("Liquidation order already in cache: {e}");
3041 } else {
3042 drop(cache);
3043 self.publish_order_initialized(&order);
3044 self.cache
3045 .borrow_mut()
3046 .add_venue_order_id(&client_order_id, &venue_order_id, false)
3047 .ok();
3048 }
3049 }
3050
3051 self.account_ids.insert(trader_id, account_id);
3054 self.generate_order_submitted(&order, account_id);
3055 self.generate_order_accepted(&order, venue_order_id);
3056 self.fill_market_order(client_order_id);
3057 }
3058 }
3059
3060 pub fn process_order(&mut self, order: &mut OrderAny, account_id: AccountId) {
3070 self.process_order_received(order, account_id, false);
3071 }
3072
3073 pub fn process_oto_command(&mut self, command: &OtoCommand) {
3081 match command {
3082 OtoCommand::Release {
3083 client_order_id,
3084 account_id,
3085 ..
3086 } => {
3087 if self
3088 .orders
3089 .closed_oto_order_ids
3090 .borrow()
3091 .contains(client_order_id)
3092 || self
3093 .cache
3094 .borrow()
3095 .venue_order_id(client_order_id)
3096 .is_some()
3097 {
3098 return;
3099 }
3100
3101 let Some(mut order) = self.order_snapshot(*client_order_id) else {
3102 return;
3103 };
3104
3105 if let Err(e) = self.apply_deferred_submission(&mut order, false) {
3106 log::error!("Cannot release OTO order {client_order_id}: {e}");
3107 return;
3108 }
3109
3110 if self.contingent_order_is_closed(&order)
3111 || self.inflight_orders.contains(*client_order_id)
3112 {
3113 return;
3114 }
3115
3116 self.process_order_received(&mut order, *account_id, true);
3117 }
3118 OtoCommand::Resize {
3119 parent_order_id,
3120 quantity,
3121 ..
3122 } => self.process_oto_resize(*parent_order_id, *quantity),
3123 OtoCommand::Cancel {
3124 client_order_id,
3125 cancel_contingencies,
3126 excluded,
3127 ..
3128 } => {
3129 let Some(mut order) = self.order_snapshot(*client_order_id) else {
3130 return;
3131 };
3132
3133 if self.contingent_order_is_closed(&order) {
3134 return;
3135 }
3136
3137 if let Err(e) = self.apply_deferred_submission(&mut order, false) {
3138 log::error!("Cannot cancel OTO order {client_order_id}: {e}");
3139 return;
3140 }
3141
3142 self.cancel_order_excluding(&order, Some(*cancel_contingencies), excluded);
3143 }
3144 }
3145 }
3146
3147 pub fn process_oto_resize(&mut self, parent_order_id: ClientOrderId, quantity: Quantity) {
3156 if let Some(parent) = self.order_snapshot(parent_order_id) {
3157 self.update_oto_children(&parent, Some(quantity), &[]);
3158 }
3159 }
3160
3161 fn process_order_received(
3162 &mut self,
3163 order: &mut OrderAny,
3164 account_id: AccountId,
3165 released: bool,
3166 ) {
3167 if self.core.order_exists(order.client_order_id()) {
3169 return;
3170 }
3171
3172 if !self.cache.borrow().order_exists(&order.client_order_id()) {
3173 log::error!(
3174 "Cannot process order {}: not found in cache",
3175 order.client_order_id()
3176 );
3177 return;
3178 }
3179
3180 let ts_now = self.clock.borrow().timestamp_ns();
3183 self.check_instrument_expiration(
3184 ts_now,
3185 self.config.defer_option_settlement,
3186 &[order.client_order_id()],
3187 );
3188
3189 if self.config.support_contingent_orders
3190 && order.parent_order_id().is_some()
3191 && !self.prepare_oto_submission(order, account_id)
3192 {
3193 return;
3194 }
3195
3196 self.account_ids.insert(order.trader_id(), account_id);
3197 if self.reject_spread_order(order) {
3198 return;
3199 }
3200
3201 self.process_order_internal(order, released);
3202 }
3203
3204 fn prepare_oto_submission(&mut self, order: &mut OrderAny, account_id: AccountId) -> bool {
3205 let id = order.client_order_id();
3206
3207 let Some(snapshot) = self.order_snapshot(id) else {
3208 return false;
3209 };
3210
3211 if self.contingent_order_is_closed(&snapshot) {
3212 return false;
3213 }
3214
3215 *order = snapshot;
3216 self.account_ids.insert(order.trader_id(), account_id);
3217 self.orders.pending_oto_order_ids.borrow_mut().insert(id);
3218
3219 if let Err(e) = self.apply_deferred_submission(order, false) {
3220 log::error!("Cannot process OTO submission {id}: {e}");
3221 return false;
3222 }
3223
3224 if let Some(command) = self.oto_submission_cancel(order) {
3225 self.process_oto_command(&command);
3226 return false;
3227 }
3228
3229 self.resize_oto_order(order)
3230 }
3231
3232 fn resize_oto_order(&mut self, order: &mut OrderAny) -> bool {
3233 let Some(parent) = self.full_trigger_oto_parent(order) else {
3234 return true;
3235 };
3236
3237 if let Err(e) = self.apply_deferred_submission(order, false) {
3238 log::error!("Cannot resize OTO order {}: {e}", order.client_order_id());
3239 return false;
3240 }
3241
3242 let ids = parent
3243 .linked_order_ids()
3244 .expect("OTO parent has linked children");
3245 let filled_qty = self.engine_filled_qty(&parent);
3246 let remaining = self.oto_child_remaining(order, ids, parent.quantity());
3247 if remaining.is_zero() {
3248 self.cancel_order(order, Some(false));
3249 return false;
3250 }
3251
3252 let parent_inverse = self
3253 .cache
3254 .borrow()
3255 .instrument(&parent.instrument_id())
3256 .is_some_and(Instrument::is_inverse);
3257
3258 let sizing = OtoSizing {
3259 quantity: parent.quantity(),
3260 filled_qty,
3261 quote: parent.is_quote_quantity() && !parent_inverse,
3262 reduced_to_filled: true,
3263 grew: false,
3264 };
3265
3266 self.resize_oto_child(order, &sizing, remaining);
3267 if let Some(snapshot) = self.order_snapshot(order.client_order_id()) {
3268 order.set_quantity(snapshot.quantity());
3269 order.set_leaves_qty(snapshot.leaves_qty());
3270 order.set_is_quote_quantity(snapshot.is_quote_quantity());
3271 }
3272
3273 true
3274 }
3275
3276 fn full_trigger_oto_parent(&self, order: &OrderAny) -> Option<OrderAny> {
3277 if !self.config.support_contingent_orders || !self.config.oto_full_trigger {
3278 return None;
3279 }
3280
3281 let parent = self.order_snapshot(order.parent_order_id()?)?;
3282 if parent.contingency_type() != Some(ContingencyType::Oto) {
3283 return None;
3284 }
3285
3286 let ids = parent.linked_order_ids()?;
3287 if self.engine_filled_qty(&parent) < parent.quantity()
3288 || !ids
3289 .iter()
3290 .filter_map(|id| self.order_snapshot(*id))
3291 .any(|child| child.instrument_id() != parent.instrument_id())
3292 {
3293 return None;
3294 }
3295
3296 Some(parent)
3297 }
3298
3299 fn process_order_internal(&mut self, order: &mut OrderAny, released: bool) {
3300 let reject_reason: Option<Ustr> = 'validate: {
3305 let cache_borrow = self.cache.as_ref().borrow();
3306
3307 if self.pending_resolution.is_some() {
3308 break 'validate Some(
3309 format!(
3310 "Contract {} has expired and is pending resolution",
3311 self.instrument.id()
3312 )
3313 .into(),
3314 );
3315 }
3316
3317 if self.instrument.has_expiration() {
3319 if let Some(activation_ns) = self.instrument.activation_ns()
3320 && self.clock.borrow().timestamp_ns() < activation_ns
3321 {
3322 break 'validate Some(
3323 format!(
3324 "Contract {} is not yet active, activation {activation_ns}",
3325 self.instrument.id(),
3326 )
3327 .into(),
3328 );
3329 }
3330
3331 if let Some(expiration_ns) = self.instrument.expiration_ns()
3332 && self.clock.borrow().timestamp_ns() >= expiration_ns
3333 {
3334 break 'validate Some(
3335 format!(
3336 "Contract {} has expired, expiration {expiration_ns}",
3337 self.instrument.id(),
3338 )
3339 .into(),
3340 );
3341 }
3342 }
3343
3344 if self.expiration_processed {
3346 break 'validate Some(
3347 format!("Contract {} has expired", self.instrument.id()).into(),
3348 );
3349 }
3350
3351 if self.market_status != MarketStatus::Open {
3352 break 'validate Some(
3353 format!(
3354 "Market {} is {}, cannot accept order {}",
3355 self.instrument.id(),
3356 self.market_status,
3357 order.client_order_id()
3358 )
3359 .into(),
3360 );
3361 }
3362
3363 if self.config.support_contingent_orders {
3365 if let Some(parent_order_id) = order.parent_order_id() {
3366 self.orders
3368 .pending_oto_order_ids
3369 .borrow_mut()
3370 .swap_remove(&order.client_order_id());
3371
3372 let parent_order = match self.order_snapshot(parent_order_id) {
3373 Some(o) if o.contingency_type() == Some(ContingencyType::Oto) => o,
3374 _ => panic!("OTO parent not found"),
3375 };
3376
3377 let parent_filled_qty = parent_order.filled_qty();
3378
3379 if parent_order.status() == OrderStatus::Rejected
3381 || self
3382 .orders
3383 .rejected_oto_parent_ids
3384 .borrow()
3385 .contains(&parent_order_id)
3386 {
3387 break 'validate Some(
3388 format!("Rejected OTO order from {parent_order_id}").into(),
3389 );
3390 } else if !released
3391 && (parent_filled_qty.is_zero()
3392 || (self.config.oto_full_trigger
3393 && parent_filled_qty < parent_order.quantity()))
3394 {
3395 log::info!(
3396 "Pending OTO order {} triggers from {parent_order_id}",
3397 order.client_order_id(),
3398 );
3399
3400 self.orders
3401 .pending_oto_order_ids
3402 .borrow_mut()
3403 .insert(order.client_order_id());
3404
3405 return;
3406 }
3407 }
3408
3409 if let Some(linked_order_ids) = order.linked_order_ids() {
3410 let contingency_type = order.contingency_type();
3411
3412 for client_order_id in linked_order_ids {
3413 match cache_borrow.order(client_order_id) {
3414 Some(contingent_order)
3415 if matches!(
3416 contingency_type,
3417 Some(ContingencyType::Oco | ContingencyType::Ouo)
3418 ) && !order.is_closed()
3419 && contingent_order.is_closed()
3420 && !Self::is_rejected_oto_sibling(order, &contingent_order) =>
3421 {
3422 break 'validate Some(
3423 format!("Contingent order {client_order_id} already closed")
3424 .into(),
3425 );
3426 }
3427 None => panic!("Cannot find contingent order for {client_order_id}"),
3428 _ => {}
3429 }
3430 }
3431 }
3432 }
3433
3434 if !order_precision_valid(order.quantity().precision, self.instrument.size_precision())
3436 {
3437 break 'validate Some(
3438 format!(
3439 "Invalid order quantity precision for order {}, was {} when {} size precision is {}",
3440 order.client_order_id(),
3441 order.quantity().precision,
3442 self.instrument.id(),
3443 self.instrument.size_precision()
3444 )
3445 .into(),
3446 );
3447 }
3448
3449 if let Some(display_qty) = order.display_qty()
3451 && !order_precision_valid(display_qty.precision, self.instrument.size_precision())
3452 {
3453 break 'validate Some(
3454 format!(
3455 "Invalid order display quantity precision for order {}, was {} when {} size precision is {}",
3456 order.client_order_id(),
3457 display_qty.precision,
3458 self.instrument.id(),
3459 self.instrument.size_precision()
3460 )
3461 .into(),
3462 );
3463 }
3464
3465 if let Some(reason) = order
3467 .price()
3468 .and_then(|price| self.order_price_rejection(order, "price", price))
3469 {
3470 break 'validate Some(reason);
3471 }
3472
3473 if let Some(reason) = order
3474 .trigger_price()
3475 .and_then(|price| self.order_price_rejection(order, "trigger price", price))
3476 {
3477 break 'validate Some(reason);
3478 }
3479
3480 if order.is_reduce_only() && !self.config.use_reduce_only {
3481 break 'validate Some(
3482 "Reduce-only orders are not supported by this matching engine".into(),
3483 );
3484 }
3485
3486 None
3487 };
3488
3489 if let Some(reason) = reject_reason {
3490 self.generate_order_rejected(order, reason);
3491 return;
3492 }
3493
3494 if let Some(reason) = self
3495 .order_position_rejection(order)
3496 .unwrap_or_else(|e| Some(e.to_string().into()))
3497 {
3498 self.generate_order_rejected(order, reason);
3499 return;
3500 }
3501
3502 if order.is_quote_quantity()
3510 && !self.instrument.is_inverse()
3511 && !matches!(
3512 order.order_type(),
3513 OrderType::TrailingStopLimit | OrderType::TrailingStopMarket,
3514 )
3515 && (order.price().is_some()
3516 || matches!(
3517 order.order_type(),
3518 OrderType::Market | OrderType::MarketToLimit,
3519 ))
3520 && !self.convert_quote_to_base_quantity(order)
3521 {
3522 return;
3523 }
3524
3525 match order.order_type() {
3526 OrderType::Market => self.process_market_order(order),
3527 OrderType::Limit => self.process_limit_order(order),
3528 OrderType::MarketToLimit => self.process_market_to_limit_order(order),
3529 OrderType::StopMarket => self.process_stop_market_order(order),
3530 OrderType::StopLimit => self.process_stop_limit_order(order),
3531 OrderType::MarketIfTouched => self.process_market_if_touched_order(order),
3532 OrderType::LimitIfTouched => self.process_limit_if_touched_order(order),
3533 OrderType::TrailingStopMarket => self.process_trailing_stop_order(order),
3534 OrderType::TrailingStopLimit => self.process_trailing_stop_order(order),
3535 }
3536 }
3537
3538 fn is_rejected_oto_sibling(order: &OrderAny, sibling: &OrderAny) -> bool {
3539 sibling.status() == OrderStatus::Rejected
3540 && order
3541 .parent_order_id()
3542 .is_some_and(|parent_id| sibling.parent_order_id() == Some(parent_id))
3543 }
3544
3545 fn order_position_rejection(&mut self, order: &OrderAny) -> anyhow::Result<Option<Ustr>> {
3546 let checks_reduce_only = self.config.use_reduce_only
3547 && order.is_reduce_only()
3548 && !order.is_closed()
3549 && !(self.restricts_short_selling() && order.is_sell());
3550
3551 if self.restricts_short_selling() || checks_reduce_only {
3552 self.purge_applied_fills();
3553 }
3554
3555 let cache = self.cache.borrow();
3556 let position = self.position_for_order_in_cache(&cache, order);
3557
3558 if let Some(reason) = self.cash_sell_rejection(&cache, order, position.as_ref())? {
3559 return Ok(Some(reason));
3560 }
3561
3562 if checks_reduce_only {
3563 let quantity = self.position_quantity(&cache, order, position.as_ref())?;
3566
3567 if (order.is_buy() && quantity >= Decimal::ZERO)
3568 || (order.is_sell() && quantity <= Decimal::ZERO)
3569 {
3570 return Ok(Some(
3571 format!(
3572 "Reduce-only order {} ({}-{}) would have increased position",
3573 order.client_order_id(),
3574 order.order_type().to_string().to_uppercase(),
3575 order.order_side().to_string().to_uppercase()
3576 )
3577 .into(),
3578 ));
3579 }
3580 }
3581
3582 Ok(None)
3583 }
3584
3585 fn restricts_short_selling(&self) -> bool {
3586 self.account_type != AccountType::Margin
3587 && matches!(
3588 self.instrument,
3589 InstrumentAny::Equity(_) | InstrumentAny::BinaryOption(_)
3590 )
3591 }
3592
3593 fn cash_sell_rejection(
3594 &self,
3595 cache: &Cache,
3596 order: &OrderAny,
3597 position: Option<&Position>,
3598 ) -> anyhow::Result<Option<Ustr>> {
3599 if !self.restricts_short_selling() || !order.is_sell() {
3600 return Ok(None);
3601 }
3602
3603 let quantity = if order.is_quote_quantity() {
3604 let reference_price = order.price().or(self.core.bid).ok_or_else(|| {
3605 anyhow::anyhow!(
3606 "No market for {} to convert quote quantity to base",
3607 order.instrument_id()
3608 )
3609 })?;
3610
3611 self.instrument
3612 .try_calculate_base_quantity(order.leaves_qty(), reference_price)?
3613 } else {
3614 order.leaves_qty()
3615 };
3616
3617 let position_quantity = self.position_quantity(cache, order, position)?;
3618
3619 if quantity.as_decimal() <= position_quantity {
3620 return Ok(None);
3621 }
3622
3623 let position_string = position.map_or("None".to_string(), |pos| pos.id.to_string());
3624 Ok(Some(
3625 format!(
3626 "Short selling not permitted on a CASH account with position {position_string} and order {order}",
3627 )
3628 .into(),
3629 ))
3630 }
3631
3632 fn order_price_rejection(&self, order: &OrderAny, field: &str, price: Price) -> Option<Ustr> {
3633 let price_precision = self.instrument.price_precision();
3634 if !order_precision_valid(price.precision, price_precision) {
3635 return Some(
3636 format!(
3637 "Invalid order {field} precision for order {}, was {} when {} price precision is {price_precision}",
3638 order.client_order_id(),
3639 price.precision,
3640 self.instrument.id(),
3641 )
3642 .into(),
3643 );
3644 }
3645
3646 let price_increment = self.instrument.price_increment();
3647 if !Self::price_matches_tick(price, price_increment) {
3648 return Some(
3649 format!(
3650 "Invalid order {field} {price} for order {}, not a multiple of {} price increment {price_increment}",
3651 order.client_order_id(),
3652 self.instrument.id(),
3653 )
3654 .into(),
3655 );
3656 }
3657
3658 None
3659 }
3660
3661 fn convert_quote_to_base_quantity(&self, order: &mut OrderAny) -> bool {
3662 let reference_price = if let Some(price) = order.price() {
3666 Some(price)
3667 } else {
3668 match order.order_side() {
3669 OrderSide::Buy => self.core.ask,
3670 OrderSide::Sell => self.core.bid,
3671 }
3672 };
3673
3674 let Some(reference_price) = reference_price else {
3675 self.generate_order_rejected(
3676 order,
3677 format!(
3678 "No market for {} to convert quote quantity to base",
3679 order.instrument_id(),
3680 )
3681 .into(),
3682 );
3683 return false;
3684 };
3685
3686 let base_quantity = self
3687 .instrument
3688 .calculate_base_quantity(order.quantity(), reference_price);
3689
3690 let ts_now = self.clock.borrow().timestamp_ns();
3691
3692 let update = OrderUpdated::new(
3693 order.trader_id(),
3694 order.strategy_id(),
3695 order.instrument_id(),
3696 order.client_order_id(),
3697 base_quantity,
3698 UUID4::new(),
3699 ts_now,
3700 ts_now,
3701 false,
3702 order.venue_order_id(),
3703 order.account_id(),
3704 None,
3705 None,
3706 None,
3707 false,
3708 );
3709 let event = OrderEventAny::Updated(update);
3710
3711 if let Err(e) = order.apply(event.clone()) {
3715 log::error!(
3716 "Failed to apply quote-to-base update for {}: {e}",
3717 order.client_order_id(),
3718 );
3719 return false;
3720 }
3721
3722 self.orders
3724 .pending_updates
3725 .borrow_mut()
3726 .entry(order.client_order_id())
3727 .or_default()
3728 .push(update);
3729 self.dispatch_order_event(event);
3730 true
3731 }
3732
3733 pub fn restore_open_order(&mut self, order: &OrderAny, account_id: AccountId) {
3747 if self.core.order_exists(order.client_order_id()) {
3748 return;
3749 }
3750
3751 if self.contingent_order_is_closed(order) {
3752 return;
3753 }
3754
3755 self.account_ids.insert(order.trader_id(), account_id);
3756 if self.reject_spread_order(order) {
3757 return;
3758 }
3759
3760 if let Err(e) = self.ids_generator.get_venue_order_id(order) {
3761 log::error!(
3762 "Failed to resolve venue order ID restoring {}: {e}",
3763 order.client_order_id(),
3764 );
3765 return;
3766 }
3767
3768 if let Some(mut cached) = self.cache.borrow_mut().order_mut(&order.client_order_id())
3772 && !matches!(
3773 cached.liquidity_side(),
3774 Some(LiquiditySide::Maker | LiquiditySide::Taker)
3775 )
3776 {
3777 cached.set_liquidity_side(LiquiditySide::Maker);
3778 }
3779
3780 let filled_qty = order.filled_qty();
3781 if !filled_qty.is_zero() {
3782 self.orders
3783 .cached_filled_qty
3784 .borrow_mut()
3785 .insert(order.client_order_id(), filled_qty);
3786 }
3787
3788 let match_info = Self::matching_core_entry(order);
3789 self.track_post_match_order(order);
3790 self.core.add_order(match_info);
3791 }
3792
3793 pub fn process_modify(&mut self, command: &ModifyOrder, account_id: AccountId) {
3795 if !self.core.order_exists(command.client_order_id) {
3796 self.generate_order_modify_rejected(
3797 command.trader_id,
3798 command.strategy_id,
3799 command.instrument_id,
3800 command.client_order_id,
3801 Ustr::from(format!("Order {} not found", command.client_order_id).as_str()),
3802 command.venue_order_id,
3803 Some(account_id),
3804 Some(command.command_id),
3805 );
3806 return;
3807 }
3808
3809 if self.market_status != MarketStatus::Open {
3813 self.generate_order_modify_rejected(
3814 command.trader_id,
3815 command.strategy_id,
3816 command.instrument_id,
3817 command.client_order_id,
3818 Ustr::from(
3819 format!(
3820 "Market {} is {}, cannot modify order {}",
3821 self.instrument.id(),
3822 self.market_status,
3823 command.client_order_id
3824 )
3825 .as_str(),
3826 ),
3827 command.venue_order_id,
3828 Some(account_id),
3829 Some(command.command_id),
3830 );
3831 return;
3832 }
3833
3834 let order = match self.order_snapshot(command.client_order_id) {
3835 Some(order) => order,
3836 None => {
3837 log::error!(
3838 "Cannot modify order: order {} not found in cache",
3839 command.client_order_id
3840 );
3841 return;
3842 }
3843 };
3844
3845 let update_success = self.update_order(
3846 &order,
3847 command.quantity,
3848 command.price,
3849 command.trigger_price,
3850 None,
3851 Some(command.command_id),
3852 );
3853
3854 if !update_success {
3855 return;
3856 }
3857
3858 if !self.core.order_exists(command.client_order_id) {
3859 return;
3860 }
3861
3862 let Some(refreshed) = self.order_snapshot(command.client_order_id) else {
3863 return;
3864 };
3865
3866 let price_changed = refreshed.price() != order.price()
3867 || refreshed.trigger_price() != order.trigger_price();
3868
3869 let reset_priority = match self.config.order_priority_reset_policy {
3870 OrderPriorityResetPolicy::PriceChange => false,
3871 OrderPriorityResetPolicy::PriceOrQuantityIncrease => {
3872 price_changed || refreshed.quantity() > order.quantity()
3873 }
3874 OrderPriorityResetPolicy::AnyModify => true,
3875 };
3876
3877 self.sync_core_entry(&refreshed, reset_priority);
3878 let reset_queue = match self.config.order_priority_reset_policy {
3879 OrderPriorityResetPolicy::PriceChange => price_changed && refreshed.is_open(),
3880 _ => reset_priority && !refreshed.is_closed(),
3881 };
3882
3883 if reset_queue
3884 && self.config.queue_position
3885 && let Some(new_price) = refreshed.price()
3886 {
3887 self.snapshot_queue_position(&refreshed, new_price);
3888 self.queue_excess.swap_remove(&refreshed.client_order_id());
3889 }
3890 }
3891
3892 pub fn process_cancel(&mut self, command: &CancelOrder, account_id: AccountId) {
3894 if !self.core.order_exists(command.client_order_id)
3896 && !self
3897 .orders
3898 .pending_oto_order_ids
3899 .borrow()
3900 .contains(&command.client_order_id)
3901 {
3902 let order = self
3905 .order_snapshot(command.client_order_id)
3906 .filter(|order| {
3907 order.account_id() == Some(account_id)
3908 && (order.is_inflight() || order.is_open())
3909 && !self.inflight_orders.contains(order.client_order_id())
3910 });
3911
3912 if let Some(order) = order {
3913 self.cancel_order(&order, None);
3914 return;
3915 }
3916
3917 self.generate_order_cancel_rejected(
3918 command.trader_id,
3919 command.strategy_id,
3920 account_id,
3921 command.instrument_id,
3922 command.client_order_id,
3923 command.venue_order_id,
3924 Ustr::from(format!("Order {} not found", command.client_order_id).as_str()),
3925 Some(command.command_id),
3926 );
3927 return;
3928 }
3929
3930 let mut order = match self.order_snapshot(command.client_order_id) {
3931 Some(order) => order,
3932 None => {
3933 log::error!(
3934 "Cannot cancel order: order {} not found in cache",
3935 command.client_order_id
3936 );
3937 return;
3938 }
3939 };
3940
3941 if let Err(e) = self.apply_deferred_submission(&mut order, false) {
3943 self.generate_order_cancel_rejected(
3944 command.trader_id,
3945 command.strategy_id,
3946 account_id,
3947 command.instrument_id,
3948 command.client_order_id,
3949 command.venue_order_id,
3950 Ustr::from(e.to_string().as_str()),
3951 Some(command.command_id),
3952 );
3953 return;
3954 }
3955
3956 if !order.is_inflight() && !order.is_open() {
3957 self.purge_stale_core_entry(command.client_order_id);
3958 return;
3959 }
3960
3961 self.cancel_order(&order, None);
3962 }
3963
3964 pub fn process_cancel_all(&mut self, command: &CancelAllOrders, account_id: AccountId) {
3968 self.process_cancel_all_excluding(command, account_id, &[]);
3969 }
3970
3971 pub fn process_cancel_all_excluding(
3974 &mut self,
3975 command: &CancelAllOrders,
3976 account_id: AccountId,
3977 excluded: &[ClientOrderId],
3978 ) {
3979 let instrument_id = command.instrument_id;
3980 let order_side = command.order_side;
3981
3982 let mut client_order_ids: Vec<ClientOrderId> = {
3983 let cache = self.cache.borrow();
3984 cache
3985 .orders_open_refs(
3986 None,
3987 Some(&instrument_id),
3988 None,
3989 Some(&account_id),
3990 order_side,
3991 )
3992 .into_iter()
3993 .chain(cache.orders_inflight_refs(
3994 None,
3995 Some(&instrument_id),
3996 None,
3997 Some(&account_id),
3998 order_side,
3999 ))
4000 .map(|order| order.client_order_id())
4001 .filter(|client_order_id| !excluded.contains(client_order_id))
4002 .collect()
4003 };
4004
4005 client_order_ids.sort_unstable();
4006 client_order_ids.dedup();
4007
4008 for client_order_id in client_order_ids {
4009 let order = match self
4010 .cache
4011 .borrow()
4012 .order(&client_order_id)
4013 .map(|o| o.clone())
4014 {
4015 Some(order) => order,
4016 None => continue,
4017 };
4018
4019 if !order.is_inflight() && !order.is_open() {
4020 self.purge_stale_core_entry(client_order_id);
4021 continue;
4022 }
4023
4024 self.cancel_order_excluding(&order, None, excluded);
4025 }
4026 }
4027
4028 fn purge_stale_core_entry(&mut self, client_order_id: ClientOrderId) {
4031 if self.core.order_exists(client_order_id) {
4032 self.delete_core_order(client_order_id);
4033 }
4034
4035 self.remove_queue_position(client_order_id);
4036 self.orders
4037 .cached_filled_qty
4038 .borrow_mut()
4039 .swap_remove(&client_order_id);
4040 }
4041
4042 fn resync_core_entry(&mut self, client_order_id: ClientOrderId) -> Option<OrderAny> {
4043 let order = self.order_snapshot(client_order_id)?;
4044 self.sync_core_entry(&order, false);
4045 Some(order)
4046 }
4047
4048 fn sync_core_entry(&mut self, order: &OrderAny, reset_priority: bool) {
4049 let client_order_id = order.client_order_id();
4050
4051 if order.is_closed() {
4054 self.delete_core_order(client_order_id);
4055 self.remove_queue_position(client_order_id);
4056 return;
4057 }
4058
4059 let new_match_info = Self::matching_core_entry(order);
4060 let unchanged = !reset_priority
4062 && self
4063 .core
4064 .get_order(client_order_id)
4065 .is_some_and(|existing| *existing == new_match_info);
4066
4067 if unchanged {
4068 self.track_post_match_order(order);
4069 return;
4070 }
4071
4072 self.delete_core_order(client_order_id);
4073 self.track_post_match_order(order);
4074 self.core.add_order(new_match_info);
4075 }
4076
4077 fn order_snapshot(&self, client_order_id: ClientOrderId) -> Option<OrderAny> {
4078 let mut order = self.cache.borrow().order(&client_order_id)?.clone();
4079 let mut pending = self.orders.pending_updates.borrow_mut();
4080 if order.is_closed() {
4081 pending.swap_remove(&client_order_id);
4082 return Some(order);
4083 }
4084
4085 if let Some(updates) = pending.get_mut(&client_order_id) {
4086 Self::retain_unapplied_updates(&order, updates);
4087 for update in updates.iter() {
4088 if let Err(e) = order.apply(OrderEventAny::Updated(*update)) {
4089 log::error!("Cannot apply pending update for {client_order_id}: {e}");
4090 return None;
4091 }
4092 }
4093
4094 if updates.is_empty() {
4095 pending.swap_remove(&client_order_id);
4096 }
4097 }
4098
4099 if let Some(filled_qty) = self
4100 .orders
4101 .cached_filled_qty
4102 .borrow()
4103 .get(&client_order_id)
4104 .copied()
4105 {
4106 write_filled_qty(&mut order, filled_qty);
4107 order.set_leaves_qty(order.quantity().saturating_sub(filled_qty));
4108 }
4109
4110 Some(order)
4111 }
4112
4113 fn purge_applied_updates(&self) {
4114 let cache = self.cache.borrow();
4115 self.orders
4116 .pending_updates
4117 .borrow_mut()
4118 .retain(|id, updates| {
4119 let Some(order) = cache.order(id) else {
4120 return false;
4121 };
4122
4123 Self::retain_unapplied_updates(&order, updates);
4124 !updates.is_empty()
4125 });
4126 }
4127
4128 fn purge_applied_rejections(&self) {
4129 let cache = self.cache.borrow();
4130 self.orders
4131 .rejected_oto_parent_ids
4132 .borrow_mut()
4133 .retain(|id| {
4134 cache
4135 .order(id)
4136 .is_some_and(|order| order.status() != OrderStatus::Rejected)
4137 });
4138 }
4139
4140 fn purge_applied_oto_terminals(&self) {
4141 let cache = self.cache.borrow();
4142 self.orders
4143 .closed_oto_order_ids
4144 .borrow_mut()
4145 .retain(|id| cache.order(id).is_some_and(|order| !order.is_closed()));
4146 }
4147
4148 fn retain_unapplied_updates(order: &OrderAny, updates: &mut Vec<OrderUpdated>) {
4149 if order.is_closed() {
4150 updates.clear();
4151 return;
4152 }
4153
4154 let events = order.events();
4155 updates.retain(|update| {
4156 !events.iter().any(|event| {
4157 matches!(event, OrderEventAny::Updated(applied) if applied.event_id == update.event_id)
4158 })
4159 });
4160 }
4161
4162 pub fn process_batch_cancel(&mut self, command: &BatchCancelOrders, account_id: AccountId) {
4164 for order in &command.cancels {
4165 self.process_cancel(order, account_id);
4166 }
4167 }
4168
4169 pub fn process_batch_modify(&mut self, command: &BatchModifyOrders, account_id: AccountId) {
4171 for order in &command.modifies {
4172 self.process_modify(order, account_id);
4173 }
4174 }
4175
4176 fn process_market_order(&mut self, order: &OrderAny) {
4177 if order.time_in_force() == TimeInForce::AtTheOpen
4178 || order.time_in_force() == TimeInForce::AtTheClose
4179 {
4180 self.generate_order_rejected(
4181 order,
4182 format!(
4183 "time in force {} is not currently supported",
4184 order.time_in_force()
4185 )
4186 .into(),
4187 );
4188 return;
4189 }
4190
4191 if (order.order_side() == OrderSide::Buy && self.core.ask.is_none())
4193 || (order.order_side() == OrderSide::Sell && self.core.bid.is_none())
4194 {
4195 self.generate_order_rejected(
4196 order,
4197 format!("No market for {}", order.instrument_id()).into(),
4198 );
4199 return;
4200 }
4201
4202 if self.config.use_market_order_acks {
4203 let venue_order_id = self.ids_generator.get_venue_order_id(order).unwrap();
4204 self.generate_order_accepted(order, venue_order_id);
4205 }
4206
4207 self.fill_market_order(order.client_order_id());
4208 }
4209
4210 fn process_limit_order(&mut self, order: &mut OrderAny) {
4211 if order.time_in_force() == TimeInForce::AtTheOpen
4212 || order.time_in_force() == TimeInForce::AtTheClose
4213 {
4214 self.generate_order_rejected(
4215 order,
4216 format!(
4217 "time in force {} is not currently supported",
4218 order.time_in_force()
4219 )
4220 .into(),
4221 );
4222 return;
4223 }
4224
4225 let limit_px = order.price().expect("Limit order must have a price");
4226 if order.is_post_only() && self.core.is_limit_matched(order.order_side(), limit_px) {
4227 self.generate_order_rejected(
4228 order,
4229 format!(
4230 "POST_ONLY {} {} order limit px of {} would have been a TAKER: bid={}, ask={}",
4231 order.order_type(),
4232 order.order_side(),
4233 order.price().unwrap(),
4234 self.core
4235 .bid
4236 .map_or_else(|| "None".to_string(), |p| p.to_string()),
4237 self.core
4238 .ask
4239 .map_or_else(|| "None".to_string(), |p| p.to_string())
4240 )
4241 .into(),
4242 );
4243 return;
4244 }
4245
4246 self.accept_order(order);
4248
4249 if self.core.is_limit_matched(order.order_side(), limit_px) {
4251 order.set_liquidity_side(LiquiditySide::Taker);
4253 self.fill_limit_order_with_snapshot(order.clone());
4254
4255 if self.core.order_exists(order.client_order_id())
4258 && let Some(mut order) = self.cache.borrow_mut().order_mut(&order.client_order_id())
4259 {
4260 order.set_liquidity_side(LiquiditySide::Maker);
4261 }
4262 } else if matches!(order.time_in_force(), TimeInForce::Fok | TimeInForce::Ioc) {
4263 self.cancel_order(order, None);
4264 } else {
4265 if let Some(price) = order.price() {
4266 self.snapshot_queue_position(order, price);
4267 }
4268
4269 if let Some(mut order) = self.cache.borrow_mut().order_mut(&order.client_order_id())
4271 && !matches!(
4272 order.liquidity_side(),
4273 Some(LiquiditySide::Maker | LiquiditySide::Taker)
4274 )
4275 {
4276 order.set_liquidity_side(LiquiditySide::Maker);
4277 }
4278 }
4279 }
4280
4281 fn process_market_to_limit_order(&mut self, order: &OrderAny) {
4282 if (order.order_side() == OrderSide::Buy && self.core.ask.is_none())
4284 || (order.order_side() == OrderSide::Sell && self.core.bid.is_none())
4285 {
4286 self.generate_order_rejected(
4287 order,
4288 format!("No market for {}", order.instrument_id()).into(),
4289 );
4290 return;
4291 }
4292
4293 if self.config.use_market_order_acks {
4294 let venue_order_id = self.ids_generator.get_venue_order_id(order).unwrap();
4295 self.generate_order_accepted(order, venue_order_id);
4296 }
4297
4298 let client_order_id = order.client_order_id();
4300 self.fill_market_order(client_order_id);
4301
4302 let filled_qty = self
4304 .orders
4305 .cached_filled_qty
4306 .borrow()
4307 .get(&client_order_id)
4308 .copied()
4309 .unwrap_or_default();
4310 let leaves_qty = order.quantity().saturating_sub(filled_qty);
4311 if leaves_qty.is_zero()
4312 || order.time_in_force() == TimeInForce::Fok
4313 || (order.time_in_force() == TimeInForce::Ioc && filled_qty.is_zero())
4314 {
4315 self.purge_cached_filled_qty_if_closed(client_order_id);
4316 return;
4317 }
4318
4319 if let Some(mut updated_order) = self.order_snapshot(client_order_id) {
4320 self.accept_order(&mut updated_order);
4321 }
4322 }
4323
4324 fn process_stop_market_order(&mut self, order: &mut OrderAny) {
4325 let stop_px = order
4326 .trigger_price()
4327 .expect("Stop order must have a trigger price");
4328
4329 if self.core.is_stop_matched_with_trigger_type(
4330 order.order_side(),
4331 stop_px,
4332 order.trigger_type().unwrap_or(TriggerType::Default),
4333 ) {
4334 if self.config.reject_stop_orders {
4335 self.generate_order_rejected(order, self.in_market_rejection(order, "stop"));
4336 return;
4337 }
4338
4339 self.fill_market_order(order.client_order_id());
4340 return;
4341 }
4342
4343 self.accept_order(order);
4345 }
4346
4347 fn process_stop_limit_order(&mut self, order: &mut OrderAny) {
4348 let stop_px = order
4349 .trigger_price()
4350 .expect("Stop order must have a trigger price");
4351
4352 if self.core.is_stop_matched_with_trigger_type(
4353 order.order_side(),
4354 stop_px,
4355 order.trigger_type().unwrap_or(TriggerType::Default),
4356 ) {
4357 if self.config.reject_stop_orders {
4358 self.generate_order_rejected(order, self.in_market_rejection(order, "stop"));
4359 return;
4360 }
4361
4362 self.accept_triggered_limit_style_order(order);
4363 return;
4364 }
4365
4366 self.accept_order(order);
4367 }
4368
4369 fn process_market_if_touched_order(&mut self, order: &mut OrderAny) {
4370 if self.core.is_touch_triggered_with_trigger_type(
4371 order.order_side(),
4372 order.trigger_price().unwrap(),
4373 order.trigger_type().unwrap_or(TriggerType::Default),
4374 ) {
4375 if self.config.reject_stop_orders {
4376 self.generate_order_rejected(order, self.in_market_rejection(order, "trigger"));
4377 return;
4378 }
4379
4380 self.fill_market_order(order.client_order_id());
4381 return;
4382 }
4383
4384 self.accept_order(order);
4386 }
4387
4388 fn process_limit_if_touched_order(&mut self, order: &mut OrderAny) {
4389 if self.core.is_touch_triggered_with_trigger_type(
4390 order.order_side(),
4391 order.trigger_price().unwrap(),
4392 order.trigger_type().unwrap_or(TriggerType::Default),
4393 ) {
4394 if self.config.reject_stop_orders {
4395 self.generate_order_rejected(order, self.in_market_rejection(order, "trigger"));
4396 return;
4397 }
4398
4399 self.accept_triggered_limit_style_order(order);
4400 return;
4401 }
4402
4403 self.accept_order(order);
4405 }
4406
4407 fn in_market_rejection(&self, order: &OrderAny, field: &str) -> Ustr {
4408 format!(
4409 "{} {} order {field} px of {} was in the market: bid={}, ask={}, but rejected because of configuration",
4410 order.order_type(),
4411 order.order_side(),
4412 order.trigger_price().expect("Triggered order must have a trigger price"),
4413 self.core.bid.map_or_else(|| "None".to_string(), |p| p.to_string()),
4414 self.core.ask.map_or_else(|| "None".to_string(), |p| p.to_string()),
4415 )
4416 .into()
4417 }
4418
4419 fn accept_triggered_limit_style_order(&mut self, order: &mut OrderAny) {
4420 self.accept_order(order);
4421 self.trigger_limit_style_stop_order(order.client_order_id(), order.clone());
4422 if let Some(cached_order) = self
4423 .cache
4424 .borrow()
4425 .order(&order.client_order_id())
4426 .map(|order| order.clone())
4427 {
4428 *order = cached_order;
4429 }
4430 }
4431
4432 fn process_trailing_stop_order(&mut self, order: &mut OrderAny) {
4433 let side = order.order_side();
4434 let trigger_type = order.trigger_type().unwrap_or(TriggerType::Default);
4435
4436 if let Some(activation_price) = order.activation_price()
4437 && self.trailing_stop_activates_now(order)
4438 && self.config.reject_stop_orders
4439 {
4440 self.generate_order_rejected(
4441 order,
4442 format!(
4443 "{} {} order activation px of {} was in the market: bid={}, ask={}, but rejected because of configuration",
4444 order.order_type(),
4445 side,
4446 activation_price,
4447 self.core
4448 .bid
4449 .map_or_else(|| "None".to_string(), |p| p.to_string()),
4450 self.core
4451 .ask
4452 .map_or_else(|| "None".to_string(), |p| p.to_string())
4453 )
4454 .into(),
4455 );
4456 return;
4457 }
4458
4459 if self.trailing_stop_activates_now(order)
4460 && let Some(trigger_price) = order.trigger_price()
4461 && self
4462 .core
4463 .is_stop_matched_with_trigger_type(side, trigger_price, trigger_type)
4464 {
4465 self.generate_order_rejected(
4466 order,
4467 format!(
4468 "{} {} order trigger px of {} was in the market: bid={}, ask={}, but rejected because of configuration",
4469 order.order_type(),
4470 side,
4471 trigger_price,
4472 self.core
4473 .bid
4474 .map_or_else(|| "None".to_string(), |p| p.to_string()),
4475 self.core
4476 .ask
4477 .map_or_else(|| "None".to_string(), |p| p.to_string())
4478 )
4479 .into(),
4480 );
4481 return;
4482 }
4483
4484 order.set_liquidity_side(LiquiditySide::Maker);
4488
4489 self.accept_order(order);
4490 }
4491
4492 fn trailing_stop_activates_now(&self, order: &OrderAny) -> bool {
4495 let side = order.order_side();
4496 match order.activation_price() {
4497 Some(activation_price) => self.core.is_touch_triggered_with_trigger_type(
4498 side,
4499 activation_price,
4500 if order.trigger_type() == Some(TriggerType::MarkPrice) {
4501 TriggerType::MarkPrice
4502 } else {
4503 TriggerType::BidAsk
4504 },
4505 ),
4506 None => self
4507 .get_trailing_activation_price(
4508 order.trigger_type().unwrap_or(TriggerType::Default),
4509 side,
4510 self.core.bid,
4511 self.core.ask,
4512 self.core.last,
4513 )
4514 .is_some(),
4515 }
4516 }
4517
4518 pub fn iterate(&mut self, timestamp_ns: UnixNanos, aggressor_side: AggressorSide) {
4525 self.iterate_with_mode(timestamp_ns, aggressor_side, OrderMatchMode::All);
4526 }
4527
4528 fn iterate_with_mode(
4529 &mut self,
4530 timestamp_ns: UnixNanos,
4531 aggressor_side: AggressorSide,
4532 match_mode: OrderMatchMode,
4533 ) {
4534 self.purge_closed_cached_filled_qty();
4536 self.purge_applied_updates();
4537 self.purge_applied_fills();
4538 self.purge_applied_rejections();
4539 self.purge_applied_oto_terminals();
4540
4541 self.expire_gtd_orders(timestamp_ns);
4542 self.process_trade_queue(aggressor_side);
4543
4544 if aggressor_side == AggressorSide::NoAggressor && self.last_trade_size.is_none() {
4550 if self.book_type == BookType::L1_MBP {
4551 if let Some(bid) = self.book.best_bid_price() {
4552 self.core.set_bid_raw(bid);
4553 }
4554
4555 if let Some(ask) = self.book.best_ask_price() {
4556 self.core.set_ask_raw(ask);
4557 }
4558 } else {
4559 self.core.bid = self.book.best_bid_price();
4563 self.core.ask = self.book.best_ask_price();
4564 }
4565 }
4566
4567 let mut matched_order = false;
4568
4569 if self.market_status == MarketStatus::Open {
4570 for action in self.core.iterate_bids() {
4573 if !self.should_process_match_action(action, match_mode) {
4574 continue;
4575 }
4576
4577 matched_order = true;
4578
4579 match action {
4580 MatchAction::FillLimit(id) => self.fill_resting_limit_order(id),
4581 MatchAction::TriggerStop(id) => self.trigger_stop_order(id),
4582 }
4583 }
4584
4585 for action in self.core.iterate_asks() {
4586 if !self.should_process_match_action(action, match_mode) {
4587 continue;
4588 }
4589
4590 matched_order = true;
4591
4592 match action {
4593 MatchAction::FillLimit(id) => self.fill_resting_limit_order(id),
4594 MatchAction::TriggerStop(id) => self.trigger_stop_order(id),
4595 }
4596 }
4597 }
4598
4599 let order_ids: Vec<ClientOrderId> = if matched_order {
4600 self.core.iter_orders().map(|m| m.client_order_id).collect()
4601 } else if self.post_match_order_ids.is_empty() {
4602 Vec::new()
4603 } else {
4604 self.core
4605 .iter_orders()
4606 .filter_map(|order| {
4607 self.post_match_order_ids
4608 .contains(&order.client_order_id)
4609 .then_some(order.client_order_id)
4610 })
4611 .collect()
4612 };
4613
4614 let support_gtd_orders = self.config.support_gtd_orders;
4615
4616 for client_order_id in order_ids {
4617 let (action, keep_tracking) = {
4618 let cache = self.cache.borrow();
4619
4620 let Some(order) = cache.order(&client_order_id) else {
4621 self.post_match_order_ids.swap_remove(&client_order_id);
4622 continue;
4623 };
4624
4625 (
4626 post_match_order_action(&order, support_gtd_orders, timestamp_ns, |order| {
4627 self.order_snapshot(client_order_id)
4628 .unwrap_or_else(|| order.clone())
4629 }),
4630 Self::requires_post_match_maintenance(&order),
4631 )
4632 };
4633
4634 match action {
4635 PostMatchOrderAction::RemoveClosed => {
4636 self.delete_core_order(client_order_id);
4637 self.remove_queue_position(client_order_id);
4638 self.orders
4639 .cached_filled_qty
4640 .borrow_mut()
4641 .swap_remove(&client_order_id);
4642 continue;
4643 }
4644 PostMatchOrderAction::Expire(order) => {
4645 self.expire_order(&order);
4646 continue;
4647 }
4648 PostMatchOrderAction::UpdateTrailing(mut order) => {
4649 if self.maybe_activate_trailing_stop(
4650 &mut order,
4651 self.core.bid,
4652 self.core.ask,
4653 self.core.last,
4654 ) {
4655 self.update_trailing_stop_order(&order);
4656 self.resync_core_entry(client_order_id);
4657 }
4658 }
4659 PostMatchOrderAction::NoMaintenance => {
4660 if !keep_tracking {
4661 self.post_match_order_ids.swap_remove(&client_order_id);
4662 }
4663 }
4664 }
4665
4666 if self.target_bid.is_some() || self.target_ask.is_some() || self.target_last.is_some()
4669 {
4670 if let Some(t) = self.target_bid.take() {
4671 self.core.bid = Some(t);
4672 }
4673
4674 if let Some(t) = self.target_ask.take() {
4675 self.core.ask = Some(t);
4676 }
4677
4678 if let Some(t) = self.target_last.take() {
4679 self.core.last = Some(t);
4680 }
4681 }
4682 }
4683
4684 if let Some(t) = self.target_bid.take() {
4688 self.core.bid = Some(t);
4689 }
4690
4691 if let Some(t) = self.target_ask.take() {
4692 self.core.ask = Some(t);
4693 }
4694
4695 if let Some(t) = self.target_last.take() {
4696 self.core.last = Some(t);
4697 }
4698
4699 self.core.bid = self.book.best_bid_price();
4702 self.core.ask = self.book.best_ask_price();
4703
4704 self.check_instrument_expiration(timestamp_ns, self.config.defer_option_settlement, &[]);
4707 self.purge_closed_cached_filled_qty();
4708 self.purge_applied_updates();
4709 self.purge_applied_fills();
4710 self.purge_applied_rejections();
4711 self.purge_applied_oto_terminals();
4712 }
4713
4714 fn expire_gtd_orders(&mut self, timestamp_ns: UnixNanos) {
4715 if !self.config.support_gtd_orders || self.post_match_order_ids.is_empty() {
4716 return;
4717 }
4718
4719 let expired_order_ids: Vec<ClientOrderId> = {
4721 let cache = self.cache.borrow();
4722 self.post_match_order_ids
4723 .iter()
4724 .filter_map(|id| {
4725 let order = cache.order_ref(id)?;
4726 (!order.is_closed()
4727 && order
4728 .expire_time()
4729 .is_some_and(|expiry| timestamp_ns > expiry))
4730 .then_some(*id)
4731 })
4732 .collect()
4733 };
4734
4735 for client_order_id in expired_order_ids {
4736 if !self.core.order_exists(client_order_id) {
4737 continue;
4738 }
4739
4740 let Some(order) = self.order_snapshot(client_order_id) else {
4741 continue;
4742 };
4743
4744 self.expire_order(&order);
4745 }
4746 }
4747
4748 fn process_trade_queue(&mut self, aggressor_side: AggressorSide) {
4749 let (Some(size), Some(price)) = (self.last_trade_size, self.core.last) else {
4750 return;
4751 };
4752
4753 self.resolve_pending_on_trade(price.raw());
4754 self.decrement_queue_on_trade(price.raw(), size.raw(), aggressor_side);
4755 }
4756
4757 fn fill_resting_limit_order(&mut self, client_order_id: ClientOrderId) {
4758 if self
4760 .core
4761 .get_order(client_order_id)
4762 .is_some_and(|order| order.order_type == OrderType::MarketToLimit)
4763 && let Some(mut order) = self.cache.borrow_mut().order_mut(&client_order_id)
4764 {
4765 order.set_liquidity_side(LiquiditySide::Maker);
4766 }
4767
4768 self.fill_limit_order(client_order_id);
4769 }
4770
4771 fn should_process_match_action(&self, action: MatchAction, match_mode: OrderMatchMode) -> bool {
4772 let client_order_id = match action {
4773 MatchAction::FillLimit(id) | MatchAction::TriggerStop(id) => id,
4774 };
4775
4776 if !self.core.order_exists(client_order_id) {
4777 return false;
4778 }
4779
4780 match match_mode {
4781 OrderMatchMode::All => true,
4782 OrderMatchMode::StopTriggers(trigger_type) => match action {
4783 MatchAction::TriggerStop(client_order_id) => self
4784 .core
4785 .get_order(client_order_id)
4786 .is_some_and(|order| order.trigger_type == Some(trigger_type)),
4787 MatchAction::FillLimit(_) => false,
4788 },
4789 }
4790 }
4791
4792 fn get_trailing_activation_price(
4793 &self,
4794 trigger_type: TriggerType,
4795 order_side: OrderSide,
4796 bid: Option<Price>,
4797 ask: Option<Price>,
4798 last: Option<Price>,
4799 ) -> Option<Price> {
4800 match trigger_type {
4801 TriggerType::LastPrice => last,
4802 TriggerType::MarkPrice => self.core.mark,
4803 TriggerType::LastOrBidAsk => last.or(match order_side {
4804 OrderSide::Buy => ask,
4805 OrderSide::Sell => bid,
4806 }),
4807
4808 _ => match order_side {
4810 OrderSide::Buy => ask,
4811 OrderSide::Sell => bid,
4812 },
4813 }
4814 }
4815
4816 fn maybe_activate_trailing_stop(
4817 &self,
4818 order: &mut OrderAny,
4819 bid: Option<Price>,
4820 ask: Option<Price>,
4821 last: Option<Price>,
4822 ) -> bool {
4823 let is_activated = match order {
4824 OrderAny::TrailingStopMarket(inner) => inner.is_activated,
4825 OrderAny::TrailingStopLimit(inner) => inner.is_activated,
4826 _ => return true,
4827 };
4828
4829 if is_activated {
4830 return true;
4831 }
4832
4833 let (bid, ask) = if order.trigger_type() == Some(TriggerType::MarkPrice) {
4834 (self.core.mark, self.core.mark)
4835 } else {
4836 (bid, ask)
4837 };
4838
4839 let activation_price = match order.activation_price() {
4840 Some(price) => {
4841 let hit = match order.order_side() {
4842 OrderSide::Buy => ask.is_some_and(|ask| ask <= price),
4843 OrderSide::Sell => bid.is_some_and(|bid| bid >= price),
4844 };
4845
4846 hit.then_some(price)
4847 }
4848 None => self.get_trailing_activation_price(
4849 order
4850 .trigger_type()
4851 .expect("Trailing order has a trigger type"),
4852 order.order_side(),
4853 bid,
4854 ask,
4855 last,
4856 ),
4857 };
4858
4859 let Some(activation_price) = activation_price else {
4860 return false;
4861 };
4862
4863 match order {
4864 OrderAny::TrailingStopMarket(inner) => {
4865 inner.activation_price = Some(activation_price);
4866 inner.set_activated();
4867 }
4868 OrderAny::TrailingStopLimit(inner) => {
4869 inner.activation_price = Some(activation_price);
4870 inner.set_activated();
4871 }
4872 _ => unreachable!("only trailing orders require activation"),
4873 }
4874
4875 store_trailing_stop_activation(&mut self.cache.borrow_mut(), order);
4876 true
4877 }
4878
4879 fn determine_limit_price_and_volume(
4880 &mut self,
4881 order: &OrderAny,
4882 leaves_qty: Quantity,
4883 journal: Option<&mut ConsumptionJournal>,
4884 ) -> Vec<(Price, Quantity)> {
4885 match order.price() {
4886 Some(order_price) => {
4887 let mut fills = if self.config.liquidity_consumption {
4892 let size_prec = self.instrument.size_precision();
4893 self.book
4894 .get_all_crossed_levels(order.order_side(), order_price, size_prec)
4895 } else {
4896 let book_order =
4897 BookOrder::new(order.order_side(), order_price, order.quantity(), 1);
4898 self.book.simulate_fills(&book_order)
4899 };
4900
4901 if let Some(trade_size) = self.last_trade_size
4903 && let Some(trade_price) = self.core.last
4904 {
4905 let fills_at_trade_price = fills.iter().any(|(px, _)| *px == trade_price);
4906
4907 if (self.book_type == BookType::L1_MBP || !fills_at_trade_price)
4908 && self.core.is_limit_matched(order.order_side(), order_price)
4909 {
4910 let available_qty = if self.config.liquidity_consumption {
4913 let remaining = trade_size.raw().saturating_sub(self.trade_consumption);
4914 Quantity::from_raw(remaining, trade_size.precision)
4915 } else {
4916 trade_size
4917 };
4918
4919 let fill_qty = min(leaves_qty, available_qty);
4920
4921 if fill_qty.non_zero() {
4922 let fill_price = if self.book_type == BookType::L1_MBP
4923 && fills_at_trade_price
4924 && order.liquidity_side() == Some(LiquiditySide::Taker)
4925 {
4926 trade_price
4927 } else {
4928 order_price
4929 };
4930
4931 log::debug!(
4932 "Trade execution fill: {} @ {} (trade_price={}, available: {}, book had {} fills)",
4933 fill_qty,
4934 fill_price,
4935 trade_price,
4936 available_qty,
4937 fills.len()
4938 );
4939
4940 if self.config.liquidity_consumption {
4941 self.trade_consumption += fill_qty.raw();
4942 }
4943
4944 return vec![(fill_price, fill_qty)];
4947 }
4948
4949 if self.book_type == BookType::L1_MBP {
4950 return Vec::new();
4951 }
4952 }
4953 }
4954
4955 if fills.is_empty() {
4957 return fills;
4958 }
4959
4960 let book_prices: Vec<Price> = if self.config.liquidity_consumption {
4964 fills.iter().map(|(px, _)| *px).collect()
4965 } else {
4966 Vec::new()
4967 };
4968
4969 let book_prices_ref: Option<&[Price]> = if book_prices.is_empty() {
4970 None
4971 } else {
4972 Some(&book_prices)
4973 };
4974
4975 if order
4977 .liquidity_side()
4978 .is_some_and(|liquidity_side| liquidity_side == LiquiditySide::Maker)
4979 {
4980 let trigger_price = order
4981 .trigger_price()
4982 .filter(|_| order.trigger_type() != Some(TriggerType::MarkPrice));
4983 match order.order_side() {
4984 OrderSide::Buy => {
4985 let target_price = if trigger_price
4986 .is_some_and(|trigger_price| order_price > trigger_price)
4987 {
4988 trigger_price.unwrap()
4989 } else {
4990 order_price
4991 };
4992
4993 for fill in &mut fills {
4994 let last_px = fill.0;
4995 if last_px < order_price {
4996 self.target_bid = self.core.bid;
4998 self.target_ask = self.core.ask;
4999 self.target_last = self.core.last;
5000 self.core.set_ask_raw(target_price);
5001 self.core.set_last_raw(target_price);
5002 fill.0 = target_price;
5003 }
5004 }
5005 }
5006 OrderSide::Sell => {
5007 let target_price = if trigger_price
5008 .is_some_and(|trigger_price| order_price < trigger_price)
5009 {
5010 trigger_price.unwrap()
5011 } else {
5012 order_price
5013 };
5014
5015 for fill in &mut fills {
5016 let last_px = fill.0;
5017 if last_px > order_price {
5018 self.target_bid = self.core.bid;
5020 self.target_ask = self.core.ask;
5021 self.target_last = self.core.last;
5022 self.core.set_bid_raw(target_price);
5023 self.core.set_last_raw(target_price);
5024 fill.0 = target_price;
5025 }
5026 }
5027 }
5028 }
5029 }
5030
5031 self.apply_liquidity_consumption(
5032 fills,
5033 order,
5034 leaves_qty,
5035 book_prices_ref,
5036 self.l1_trade_size,
5037 journal,
5038 )
5039 }
5040 None => panic!("Limit order must have a price"),
5041 }
5042 }
5043
5044 fn determine_market_price_and_volume(&self, order: &OrderAny) -> Vec<(Price, Quantity)> {
5045 let price = match order.order_side() {
5046 OrderSide::Buy => Price::max(FIXED_PRECISION),
5047 OrderSide::Sell => Price::min(FIXED_PRECISION),
5048 };
5049
5050 let mut fills = if self.config.liquidity_consumption {
5053 let size_prec = self.instrument.size_precision();
5054 self.book
5055 .get_all_crossed_levels(order.order_side(), price, size_prec)
5056 } else {
5057 let book_order = BookOrder::new(order.order_side(), price, order.quantity(), 0);
5058 self.book.simulate_fills(&book_order)
5059 };
5060
5061 if !self.fill_at_market
5064 && order.trigger_type() != Some(TriggerType::MarkPrice)
5065 && self.book_type == BookType::L1_MBP
5066 && !fills.is_empty()
5067 && matches!(
5068 order.order_type(),
5069 OrderType::StopMarket | OrderType::TrailingStopMarket | OrderType::MarketIfTouched
5070 )
5071 && let Some(trigger_price) = order.trigger_price()
5072 {
5073 fills[0] = (trigger_price, fills[0].1);
5074
5075 let mut remaining_qty = order.leaves_qty();
5077 let mut capped_fills = Vec::with_capacity(fills.len());
5078
5079 for (price, qty) in fills {
5080 if remaining_qty.is_zero() {
5081 break;
5082 }
5083
5084 let mut capped_qty = qty.min(remaining_qty);
5085 capped_qty.precision = qty.precision;
5086 if capped_qty.is_zero() {
5087 continue;
5088 }
5089
5090 remaining_qty = remaining_qty - capped_qty;
5091 capped_fills.push((price, capped_qty));
5092 }
5093
5094 return capped_fills;
5095 }
5096
5097 fills
5098 }
5099
5100 fn determine_market_fill_model_price_and_volume(
5101 &mut self,
5102 order: &OrderAny,
5103 ) -> anyhow::Result<(Vec<(Price, Quantity)>, bool)> {
5104 if let Some(book) = self.fill_model.get_orderbook_for_fill_simulation(
5105 &self.instrument,
5106 order,
5107 self.core.bid,
5108 self.core.ask,
5109 )? {
5110 let price = match order.order_side() {
5111 OrderSide::Buy => Price::max(FIXED_PRECISION),
5112 OrderSide::Sell => Price::min(FIXED_PRECISION),
5113 };
5114
5115 let book_order = BookOrder::new(order.order_side(), price, order.quantity(), 0);
5116 return Ok((book.simulate_fills(&book_order), true));
5117 }
5118
5119 Ok((self.determine_market_price_and_volume(order), false))
5120 }
5121
5122 fn determine_limit_fill_model_price_and_volume(
5123 &mut self,
5124 order: &OrderAny,
5125 leaves_qty: Quantity,
5126 journal: Option<&mut ConsumptionJournal>,
5127 ) -> anyhow::Result<Vec<(Price, Quantity)>> {
5128 if let Some(book) = self.fill_model.get_orderbook_for_fill_simulation(
5129 &self.instrument,
5130 order,
5131 self.core.bid,
5132 self.core.ask,
5133 )? && let Some(limit_price) = order.price()
5134 {
5135 let book_order = BookOrder::new(order.order_side(), limit_price, order.quantity(), 0);
5136 return Ok(book.simulate_fills(&book_order));
5137 }
5138
5139 Ok(self.determine_limit_price_and_volume(order, leaves_qty, journal))
5140 }
5141
5142 pub fn fill_market_order(&mut self, client_order_id: ClientOrderId) {
5147 let mut order = match self.order_snapshot(client_order_id) {
5148 Some(order) => order,
5149 None => {
5150 log::error!("Cannot fill market order: order {client_order_id} not found in cache");
5151 return;
5152 }
5153 };
5154
5155 if !self.prepare_order_fill(&mut order) {
5156 return;
5157 }
5158
5159 if order.is_quote_quantity()
5163 && !self.instrument.is_inverse()
5164 && !self.convert_quote_to_base_quantity(&mut order)
5165 {
5166 return;
5167 }
5168
5169 if let Some(filled_qty) = self
5170 .orders
5171 .cached_filled_qty
5172 .borrow()
5173 .get(&order.client_order_id())
5174 .copied()
5175 && filled_qty >= order.quantity()
5176 {
5177 log::debug!(
5178 "Ignoring fill as already filled pending application of events: {:?}, {:?}, {:?}, {:?}",
5179 filled_qty,
5180 order.quantity(),
5181 order.filled_qty(),
5182 order.quantity()
5183 );
5184 return;
5185 }
5186
5187 let (venue_position_id, position) = self.fill_position_for_order(&order, Some(true));
5188
5189 let Some(leaves_qty) = self.fill_leaves_qty(&order, position.as_ref()) else {
5190 return;
5191 };
5192
5193 order.set_liquidity_side(LiquiditySide::Taker);
5194
5195 let (mut fills, from_synthetic) =
5196 match self.determine_market_fill_model_price_and_volume(&order) {
5197 Ok(result) => result,
5198 Err(e) => {
5199 log::error!(
5200 "Cannot fill market order {}: fill model failed: {e}",
5201 order.client_order_id()
5202 );
5203 return;
5204 }
5205 };
5206
5207 let protection_price: Option<Price> = if let Some(protection_points) =
5209 self.config.price_protection_points
5210 && matches!(
5211 order.order_type(),
5212 OrderType::Market | OrderType::StopMarket
5213 ) {
5214 protection_price_calculate(
5215 self.instrument.price_increment(),
5216 &order,
5217 protection_points,
5218 self.core.bid,
5219 self.core.ask,
5220 )
5221 .ok()
5222 } else {
5223 None
5224 };
5225
5226 if let Some(protection_price) = protection_price {
5227 fills = self.filter_fills_by_protection(fills, &order, protection_price);
5228 }
5229
5230 let is_trigger_price_fill = !self.fill_at_market
5233 && order.trigger_type() != Some(TriggerType::MarkPrice)
5234 && self.book_type == BookType::L1_MBP
5235 && matches!(
5236 order.order_type(),
5237 OrderType::StopMarket | OrderType::TrailingStopMarket | OrderType::MarketIfTouched
5238 )
5239 && order.trigger_price().is_some();
5240 if !from_synthetic && !is_trigger_price_fill {
5241 let mut journal = self.fok_consumption_journal(&order);
5242
5243 fills = self.apply_liquidity_consumption(
5244 fills,
5245 &order,
5246 leaves_qty,
5247 None,
5248 None,
5249 journal.as_mut(),
5250 );
5251
5252 if let Some(journal) = journal
5253 && self.is_fok_unfillable(&order, &fills, leaves_qty)
5254 {
5255 self.revert_consumption_journal(journal);
5256 }
5257 }
5258
5259 if let Err(e) = self.apply_fills(
5260 &order,
5261 &fills,
5262 LiquiditySide::Taker,
5263 if self.config.use_reduce_only && order.is_reduce_only() {
5264 venue_position_id
5265 } else {
5266 None
5267 },
5268 position.as_ref(),
5269 protection_price,
5270 from_synthetic,
5271 ) {
5272 log::error!("Cannot fill market order {}: {e}", order.client_order_id());
5273 }
5274 }
5275
5276 fn filter_fills_by_protection(
5277 &self,
5278 fills: Vec<(Price, Quantity)>,
5279 order: &OrderAny,
5280 protection_price: Price,
5281 ) -> Vec<(Price, Quantity)> {
5282 fills
5283 .into_iter()
5284 .filter(|(fill_price, _)| {
5285 match order.order_side() {
5286 OrderSide::Buy => *fill_price <= protection_price,
5288
5289 OrderSide::Sell => *fill_price >= protection_price,
5291 }
5292 })
5293 .collect()
5294 }
5295
5296 pub fn fill_limit_order(&mut self, client_order_id: ClientOrderId) {
5305 let order = match self.order_snapshot(client_order_id) {
5306 Some(order) => order,
5307 None => {
5308 log::error!("Cannot fill limit order: order {client_order_id} not found in cache");
5309 return;
5310 }
5311 };
5312
5313 self.fill_limit_order_with_snapshot(order);
5314 }
5315
5316 fn fill_limit_order_with_snapshot(&mut self, mut order: OrderAny) {
5317 if !self.prepare_order_fill(&mut order) {
5318 return;
5319 }
5320
5321 if order.is_quote_quantity()
5325 && !self.instrument.is_inverse()
5326 && !self.convert_quote_to_base_quantity(&mut order)
5327 {
5328 return;
5329 }
5330
5331 match order.price() {
5332 Some(order_price) => {
5333 let cached_filled_qty = self
5334 .orders
5335 .cached_filled_qty
5336 .borrow()
5337 .get(&order.client_order_id())
5338 .copied();
5339
5340 if let Some(qty) = cached_filled_qty
5341 && qty >= order.quantity()
5342 {
5343 log::debug!(
5344 "Ignoring fill as already filled pending application of events: {}, {}, {}, {}",
5345 qty,
5346 order.quantity(),
5347 order.filled_qty(),
5348 order.leaves_qty(),
5349 );
5350 return;
5351 }
5352
5353 if order
5355 .liquidity_side()
5356 .is_some_and(|liquidity_side| liquidity_side == LiquiditySide::Maker)
5357 {
5358 let at_limit = if self.last_trade_size.is_some() && self.core.last.is_some() {
5361 self.core.last.is_some_and(|last| last == order_price)
5362 } else if order.order_side() == OrderSide::Buy {
5363 self.core.bid.is_some_and(|bid| bid == order_price)
5364 } else {
5365 self.core.ask.is_some_and(|ask| ask == order_price)
5366 };
5367
5368 if at_limit {
5369 let is_limit_filled = match self.fill_model.is_limit_filled() {
5370 Ok(value) => value,
5371 Err(e) => {
5372 log::error!(
5373 "Cannot fill limit order {}: fill model failed: {e}",
5374 order.client_order_id()
5375 );
5376 return;
5377 }
5378 };
5379
5380 if !is_limit_filled {
5381 return; }
5383 }
5384 }
5385
5386 let queue_allowed_raw = if self.config.queue_position {
5387 match self.determine_trade_fill_qty(&order) {
5388 None | Some(0) => {
5389 if matches!(order.time_in_force(), TimeInForce::Fok | TimeInForce::Ioc)
5390 {
5391 self.cancel_order(&order, None);
5392 }
5393
5394 return;
5395 }
5396 Some(allowed) => Some(allowed),
5397 }
5398 } else {
5399 None
5400 };
5401
5402 let (venue_position_id, position) = self.fill_position_for_order(&order, None);
5403
5404 let Some(leaves_qty) = self.fill_leaves_qty(&order, position.as_ref()) else {
5405 return;
5406 };
5407
5408 let required_qty = leaves_qty;
5409
5410 let leaves_qty = queue_allowed_raw.map_or(leaves_qty, |allowed| {
5411 Quantity::from_raw(
5412 leaves_qty.raw().min(allowed),
5413 self.instrument.size_precision(),
5414 )
5415 });
5416
5417 let mut journal = self.fok_consumption_journal(&order);
5418 let tc_before = self.trade_consumption;
5419
5420 let mut fills = match self.determine_limit_fill_model_price_and_volume(
5421 &order,
5422 leaves_qty,
5423 journal.as_mut(),
5424 ) {
5425 Ok(fills) => fills,
5426 Err(e) => {
5427 log::error!(
5428 "Cannot fill limit order {}: fill model failed: {e}",
5429 order.client_order_id()
5430 );
5431 return;
5432 }
5433 };
5434
5435 if let Some(allowed_raw) = queue_allowed_raw {
5436 let size_prec = self.instrument.size_precision();
5437 let mut remaining = allowed_raw;
5438 fills = fills
5439 .into_iter()
5440 .filter_map(|(price, qty)| {
5441 if remaining == 0 {
5442 return None;
5443 }
5444
5445 let capped = qty.raw().min(remaining);
5446 remaining -= capped;
5447 Some((price, Quantity::from_raw(capped, size_prec)))
5448 })
5449 .collect();
5450
5451 let consumed: QuantityRaw = fills.iter().map(|(_, qty)| qty.raw()).sum();
5453 if let Some(excess) = self.queue_excess.get_mut(&order.client_order_id()) {
5454 *excess = excess.saturating_sub(consumed);
5455 }
5456
5457 self.trade_consumption = tc_before + consumed;
5458 }
5459
5460 if let Some(journal) = journal
5461 && self.is_fok_unfillable(&order, &fills, required_qty)
5462 {
5463 self.revert_consumption_journal(journal);
5464 }
5465
5466 if fills.is_empty() {
5467 log::debug!(
5468 "Skipping fill for {}: no liquidity available",
5469 order.client_order_id()
5470 );
5471
5472 if matches!(order.time_in_force(), TimeInForce::Fok | TimeInForce::Ioc) {
5473 self.cancel_order(&order, None);
5474 }
5475
5476 return;
5477 }
5478
5479 let liquidity_side = order.liquidity_side().unwrap();
5480
5481 if let Err(e) = self.apply_fills(
5482 &order,
5483 &fills,
5484 liquidity_side,
5485 venue_position_id,
5486 position.as_ref(),
5487 None,
5488 false,
5489 ) {
5490 log::error!("Cannot fill limit order {}: {e}", order.client_order_id());
5491 }
5492 }
5493 None => panic!("Limit order must have a price"),
5494 }
5495 }
5496
5497 fn fill_leaves_qty(
5498 &mut self,
5499 order: &OrderAny,
5500 position: Option<&Position>,
5501 ) -> Option<Quantity> {
5502 if !self.config.liquidity_consumption && position.is_some() {
5503 return Some(order.leaves_qty());
5504 }
5505
5506 let leaves_qty = order
5507 .quantity()
5508 .saturating_sub(self.engine_filled_qty(order));
5509
5510 match self.reduce_only_remaining(order, position) {
5511 Ok(Some(remaining)) if remaining.is_zero() => {
5512 log::warn!(
5513 "Canceling REDUCE_ONLY {} as would increase position",
5514 order.order_type()
5515 );
5516 self.cancel_order(order, None);
5517 None
5518 }
5519 Ok(Some(remaining)) => Some(leaves_qty.min(remaining)),
5520 Ok(None) => Some(leaves_qty),
5521 Err(e) => {
5522 log::error!(
5523 "Cannot determine fill quantity for {}: {e}",
5524 order.client_order_id()
5525 );
5526 None
5527 }
5528 }
5529 }
5530
5531 fn prepare_order_fill(&mut self, order: &mut OrderAny) -> bool {
5532 if order.is_closed() {
5533 self.purge_stale_core_entry(order.client_order_id());
5534 return false;
5535 }
5536
5537 self.resize_oto_order(order)
5538 }
5539
5540 fn fill_position_for_order(
5541 &mut self,
5542 order: &OrderAny,
5543 generate: Option<bool>,
5544 ) -> (Option<PositionId>, Option<Position>) {
5545 if self.restricts_short_selling()
5546 && self.oms_type == OmsType::Hedging
5547 && let Some(position) = self.position_for_order_in_cache(&self.cache.borrow(), order)
5548 {
5549 return (Some(position.id), Some(position));
5550 }
5551
5552 if self.restricts_short_selling()
5553 && self.oms_type == OmsType::Hedging
5554 && order.parent_order_id().is_some()
5555 {
5556 let cache = self.cache.borrow();
5557 return (Self::position_id_for_order(&cache, order), None);
5558 }
5559
5560 if self.oms_type == OmsType::Hedging
5561 && self.config.use_reduce_only
5562 && order.is_reduce_only()
5563 {
5564 let cache = self.cache.as_ref().borrow();
5565 if let Some(position_id) = Self::position_id_for_order(&cache, order) {
5566 let position = cache
5567 .position(&position_id)
5568 .map(|position| position.clone_without_events());
5569 return (Some(position_id), position);
5570 }
5571
5572 if self.config.support_contingent_orders && order.parent_order_id().is_some() {
5573 return (None, None);
5574 }
5575
5576 if let Some(position) = Self::open_position_reduced_by_order(&cache, order) {
5577 return (Some(position.id), Some(position));
5578 }
5579 }
5580
5581 let pending_position_id = if self.oms_type == OmsType::Hedging {
5582 self.pending_fills.values().find_map(|fill| {
5583 (fill.client_order_id == order.client_order_id())
5584 .then_some(fill.position_id)
5585 .flatten()
5586 })
5587 } else {
5588 None
5589 };
5590
5591 let venue_position_id =
5592 pending_position_id.or_else(|| self.ids_generator.get_position_id(order, generate));
5593
5594 let position = {
5595 let cache = self.cache.as_ref().borrow();
5596 venue_position_id
5597 .as_ref()
5598 .and_then(|position_id| cache.position(position_id))
5599 .map(|position| position.clone_without_events())
5600 };
5601
5602 (venue_position_id, position)
5603 }
5604
5605 fn position_for_order_in_cache(&self, cache: &Cache, order: &OrderAny) -> Option<Position> {
5606 if let Some(position_id) = Self::position_id_for_order(cache, order) {
5607 return cache
5608 .position(&position_id)
5609 .map(|position| position.clone_without_events());
5610 }
5611
5612 if self.oms_type == OmsType::Netting {
5613 let position_id = PositionId::new(
5614 format!("{}-{}", order.instrument_id(), order.strategy_id()).as_str(),
5615 );
5616 return cache
5617 .position(&position_id)
5618 .map(|position| position.clone_without_events());
5619 }
5620
5621 if self.oms_type == OmsType::Hedging
5622 && self.config.use_reduce_only
5623 && order.is_reduce_only()
5624 {
5625 if self.config.support_contingent_orders && order.parent_order_id().is_some() {
5626 return None;
5627 }
5628
5629 return Self::open_position_reduced_by_order(cache, order);
5630 }
5631
5632 None
5633 }
5634
5635 fn position_id_for_order(cache: &Cache, order: &OrderAny) -> Option<PositionId> {
5636 cache
5637 .position_id(&order.client_order_id())
5638 .copied()
5639 .or_else(|| {
5640 order
5641 .parent_order_id()
5642 .filter(|parent_id| {
5643 cache
5644 .order(parent_id)
5645 .is_some_and(|parent| parent.instrument_id() == order.instrument_id())
5646 })
5647 .and_then(|parent_id| cache.position_id(&parent_id).copied())
5648 })
5649 }
5650
5651 fn open_position_reduced_by_order(cache: &Cache, order: &OrderAny) -> Option<Position> {
5652 cache
5653 .positions_open(
5654 None,
5655 Some(&order.instrument_id()),
5656 Some(&order.strategy_id()),
5657 None,
5658 None,
5659 )
5660 .into_iter()
5661 .find(|position| order.would_reduce_only(position.side, position.quantity))
5662 .map(|position| position.clone_without_events())
5663 }
5664
5665 #[allow(
5666 clippy::too_many_arguments,
5667 reason = "fill application needs order, position, pricing, and liquidity-source context"
5668 )]
5669 fn apply_fills(
5670 &mut self,
5671 order: &OrderAny,
5672 fills: &[(Price, Quantity)],
5673 liquidity_side: LiquiditySide,
5674 venue_position_id: Option<PositionId>,
5675 position: Option<&Position>,
5676 protection_price: Option<Price>,
5677 from_synthetic: bool,
5678 ) -> anyhow::Result<()> {
5679 if self.instrument.is_spread() {
5680 return self.apply_spread_fills(
5681 order,
5682 fills,
5683 liquidity_side,
5684 venue_position_id,
5685 position,
5686 protection_price,
5687 from_synthetic,
5688 );
5689 }
5690
5691 self.apply_order_fills(
5692 order,
5693 fills,
5694 liquidity_side,
5695 venue_position_id,
5696 position,
5697 protection_price,
5698 from_synthetic,
5699 )
5700 }
5701
5702 #[allow(
5703 clippy::too_many_arguments,
5704 reason = "fill application needs order, position, pricing, and liquidity-source context"
5705 )]
5706 fn apply_order_fills(
5707 &mut self,
5708 order: &OrderAny,
5709 fills: &[(Price, Quantity)],
5710 liquidity_side: LiquiditySide,
5711 venue_position_id: Option<PositionId>,
5712 position: Option<&Position>,
5713 protection_price: Option<Price>,
5714 from_synthetic: bool,
5715 ) -> anyhow::Result<()> {
5716 let mut reduce_only_remaining = self.reduce_only_remaining(order, position)?;
5717 let required_qty = reduce_only_remaining.map_or(order.leaves_qty(), |remaining| {
5718 order.leaves_qty().min(remaining)
5719 });
5720
5721 if self.is_fok_unfillable(order, fills, required_qty) {
5722 self.cancel_order(order, None);
5723 return Ok(());
5724 }
5725
5726 if fills.is_empty() {
5727 match (order.status(), order.time_in_force()) {
5728 (OrderStatus::Initialized | OrderStatus::Submitted, time_in_force)
5729 if time_in_force != TimeInForce::Ioc =>
5730 {
5731 self.generate_order_rejected(
5732 order,
5733 format!("No market for {}", order.instrument_id()).into(),
5734 );
5735 }
5736 _ => self.cancel_order(order, None),
5737 }
5738
5739 return Ok(());
5740 }
5741
5742 let venue_position_id = if self.oms_type == OmsType::Netting {
5744 None
5745 } else {
5746 venue_position_id
5747 };
5748
5749 let initial_market_to_limit =
5750 order.order_type() == OrderType::MarketToLimit && order.filled_qty().is_zero();
5751 let mut first_price = None;
5752 let mut total_filled = self.engine_filled_qty(order);
5753 let initial_total_filled = total_filled;
5754 let mut last_fill_px: Option<Price> = None;
5755 let mut reduce_only_filled = None;
5756
5757 if let Some(remaining) = reduce_only_remaining {
5758 if remaining.is_zero() {
5759 self.cancel_order(order, None);
5760 return Ok(());
5761 }
5762
5763 reduce_only_filled = Some(total_filled);
5764 }
5765
5766 for &(fill_px, fill_qty) in fills {
5767 let Some(mut fill_px) = self.normalize_fill_price(fill_px, order.client_order_id())
5768 else {
5769 continue;
5770 };
5771
5772 let Some(fill_qty) = self.normalize_fill_quantity(fill_qty, order.client_order_id())
5773 else {
5774 continue;
5775 };
5776
5777 if initial_market_to_limit {
5778 if fill_qty.is_zero() {
5779 continue;
5780 }
5781
5782 if first_price.is_some_and(|price| price != fill_px) {
5783 break;
5784 }
5785
5786 if first_price.is_none() {
5787 self.generate_order_updated(
5788 order,
5789 order.quantity(),
5790 Some(fill_px),
5791 None,
5792 None,
5793 None,
5794 );
5795 first_price = Some(fill_px);
5796 }
5797 }
5798
5799 if self.book_type == BookType::L1_MBP
5801 && self.fill_model.is_slipped()?
5802 && let Some(slipped_px) = self.slipped_price(fill_px, order.order_side())
5803 && !order
5804 .price()
5805 .into_iter()
5806 .chain(protection_price)
5807 .any(|bound| match order.order_side() {
5808 OrderSide::Buy => slipped_px > bound,
5809 OrderSide::Sell => slipped_px < bound,
5810 })
5811 {
5812 fill_px = slipped_px;
5813 }
5814
5815 let mut effective_fill_qty = fill_qty;
5816
5817 if let Some(remaining) = reduce_only_remaining {
5818 if remaining.is_zero() {
5819 return Ok(());
5820 }
5821
5822 if effective_fill_qty > remaining {
5823 let precision = effective_fill_qty.precision;
5824 effective_fill_qty = remaining;
5825 effective_fill_qty.precision = precision;
5826 }
5827 }
5828
5829 if fill_qty.is_zero() {
5830 if fills.len() == 1 && order.status() == OrderStatus::Submitted {
5831 self.generate_order_rejected(
5832 order,
5833 format!("No market for {}", order.instrument_id()).into(),
5834 );
5835 }
5836
5837 return Ok(());
5838 }
5839
5840 let capped_fill_qty = min(
5842 effective_fill_qty,
5843 order.quantity().saturating_sub(total_filled),
5844 );
5845 let reduce_only_exhausts_position =
5846 reduce_only_remaining.is_some_and(|remaining| capped_fill_qty >= remaining);
5847
5848 if reduce_only_exhausts_position {
5849 let mut reduce_only_target = reduce_only_filled
5850 .unwrap_or(initial_total_filled)
5851 .checked_add(capped_fill_qty)
5852 .expect("Overflow occurred when adding reduce-only target quantity");
5853 reduce_only_target.precision = self.instrument.size_precision();
5854 if order.quantity() != reduce_only_target {
5855 self.generate_order_updated(order, reduce_only_target, None, None, None, None);
5856 }
5857 }
5858
5859 total_filled = total_filled.add(capped_fill_qty);
5860 if let Some(remaining) = reduce_only_remaining.as_mut() {
5861 *remaining = *remaining - capped_fill_qty.min(*remaining);
5862 }
5863
5864 if let Some(filled) = reduce_only_filled.as_mut() {
5865 *filled = filled
5866 .checked_add(capped_fill_qty)
5867 .expect("Overflow occurred when adding reduce-only filled quantity");
5868 }
5869
5870 self.fill_order(
5871 order,
5872 fill_px,
5873 effective_fill_qty,
5874 liquidity_side,
5875 venue_position_id,
5876 position,
5877 )?;
5878 last_fill_px = Some(fill_px);
5879
5880 if initial_market_to_limit
5881 && (total_filled >= order.quantity() || reduce_only_exhausts_position)
5882 {
5883 return Ok(());
5884 }
5885
5886 if reduce_only_exhausts_position {
5887 self.purge_cached_filled_qty_if_closed(order.client_order_id());
5888 return Ok(());
5889 }
5890 }
5891
5892 let filled_in_loop = total_filled > initial_total_filled;
5893 if initial_market_to_limit && filled_in_loop {
5894 return Ok(());
5895 }
5896
5897 let leaves_remaining = total_filled < order.quantity();
5898
5899 if order.time_in_force() == TimeInForce::Ioc && leaves_remaining {
5900 self.cancel_order(order, None);
5901 return Ok(());
5902 }
5903
5904 if leaves_remaining
5907 && !from_synthetic
5908 && (order.is_open() || filled_in_loop)
5909 && self.book_type == BookType::L1_MBP
5910 && matches!(
5911 order.order_type(),
5912 OrderType::Market
5913 | OrderType::MarketIfTouched
5914 | OrderType::StopMarket
5915 | OrderType::TrailingStopMarket
5916 )
5917 {
5918 let Some(last_fill_px) = last_fill_px else {
5920 return Ok(());
5921 };
5922
5923 let side = order.order_side();
5924
5925 let Some(slip_fill_px) = self.slipped_price(last_fill_px, side) else {
5926 return Ok(());
5927 };
5928
5929 if let Some(protection_price) = protection_price {
5930 let exceeds_boundary = match side {
5931 OrderSide::Buy => slip_fill_px > protection_price,
5932 OrderSide::Sell => slip_fill_px < protection_price,
5933 };
5934
5935 if exceeds_boundary {
5936 return Ok(());
5937 }
5938 }
5939
5940 let mut leaves_qty = order.quantity().saturating_sub(total_filled);
5941
5942 if let Some(remaining) = reduce_only_remaining {
5943 if remaining.is_zero() {
5944 return Ok(());
5945 }
5946
5947 if leaves_qty > remaining {
5948 let precision = leaves_qty.precision;
5949 leaves_qty = remaining;
5950 leaves_qty.precision = precision;
5951 }
5952
5953 if leaves_qty >= remaining {
5954 let mut reduce_only_target = reduce_only_filled
5955 .unwrap_or(initial_total_filled)
5956 .checked_add(leaves_qty)
5957 .expect("Overflow occurred when adding reduce-only target quantity");
5958 reduce_only_target.precision = self.instrument.size_precision();
5959 if order.quantity() != reduce_only_target {
5960 self.generate_order_updated(
5961 order,
5962 reduce_only_target,
5963 None,
5964 None,
5965 None,
5966 None,
5967 );
5968 }
5969 }
5970 }
5971
5972 if leaves_qty.is_zero() {
5973 return Ok(());
5974 }
5975
5976 self.fill_order(
5977 order,
5978 slip_fill_px,
5979 leaves_qty,
5980 liquidity_side,
5981 venue_position_id,
5982 position,
5983 )?;
5984 self.purge_cached_filled_qty_if_closed(order.client_order_id());
5985 }
5986
5987 Ok(())
5988 }
5989
5990 fn slipped_price(&self, price: Price, side: OrderSide) -> Option<Price> {
5992 let price_increment = self.instrument.price_increment();
5993 let slipped = match side {
5994 OrderSide::Buy => price.add(price_increment),
5995 OrderSide::Sell => price.sub(price_increment),
5996 };
5997
5998 is_price_tradable(&self.instrument, slipped).then_some(slipped)
5999 }
6000
6001 fn normalize_fill_price(
6002 &self,
6003 fill_px: Price,
6004 client_order_id: ClientOrderId,
6005 ) -> Option<Price> {
6006 let normalized = self.normalize_price_for_current_instrument(fill_px);
6007 if normalized.is_none() {
6008 log::warn!(
6009 "Skipping fill for {client_order_id}: fill price {fill_px} is not compatible \
6010 with {} price_precision={} price_increment={}",
6011 self.instrument.id(),
6012 self.instrument.price_precision(),
6013 self.instrument.price_increment()
6014 );
6015 }
6016
6017 normalized
6018 }
6019
6020 fn normalize_fill_quantity(
6021 &self,
6022 fill_qty: Quantity,
6023 client_order_id: ClientOrderId,
6024 ) -> Option<Quantity> {
6025 let normalized = self.normalize_quantity_for_current_instrument(fill_qty);
6026 if normalized.is_none() {
6027 log::warn!(
6028 "Skipping fill for {client_order_id}: fill quantity {fill_qty} is not compatible \
6029 with {} size_precision={}",
6030 self.instrument.id(),
6031 self.instrument.size_precision()
6032 );
6033 }
6034
6035 normalized
6036 }
6037
6038 fn reduce_only_remaining(
6039 &mut self,
6040 order: &OrderAny,
6041 position: Option<&Position>,
6042 ) -> anyhow::Result<Option<Quantity>> {
6043 if self.config.use_reduce_only && order.is_reduce_only() {
6044 return Ok(Some(self.position_quantity_remaining(order, position)?));
6045 }
6046
6047 Ok(None)
6048 }
6049
6050 fn position_quantity_remaining(
6051 &mut self,
6052 order: &OrderAny,
6053 position: Option<&Position>,
6054 ) -> anyhow::Result<Quantity> {
6055 let precision = self.instrument.size_precision();
6056
6057 self.purge_applied_fills();
6058 let quantity = self.position_quantity(&self.cache.borrow(), order, position)?;
6059
6060 if (order.is_buy() && quantity >= Decimal::ZERO)
6061 || (order.is_sell() && quantity <= Decimal::ZERO)
6062 {
6063 return Ok(Quantity::zero(precision));
6064 }
6065
6066 Ok(Quantity::from_decimal_dp(quantity.abs(), precision)?)
6067 }
6068
6069 fn position_quantity(
6070 &self,
6071 cache: &Cache,
6072 order: &OrderAny,
6073 position: Option<&Position>,
6074 ) -> anyhow::Result<Decimal> {
6075 let position_id = position
6076 .map(|position| position.id)
6077 .or_else(|| Self::position_id_for_order(cache, order))
6078 .or_else(|| {
6079 (self.oms_type == OmsType::Netting).then(|| {
6080 PositionId::new(format!("{}-{}", order.instrument_id(), order.strategy_id()))
6081 })
6082 });
6083
6084 let cached_position = position_id.as_ref().and_then(|id| cache.position(id));
6085 let position = position.or(cached_position.as_deref());
6086 let splits_virtual_position = self.restricts_short_selling()
6087 && self.oms_type == OmsType::Hedging
6088 && position_id.is_some_and(|id| id.is_virtual());
6089
6090 let mut quantity = position.map_or(Decimal::ZERO, |position| match position.side {
6091 PositionSide::Long => position.quantity.as_decimal(),
6092 PositionSide::Short => -position.quantity.as_decimal(),
6093 PositionSide::Flat => Decimal::ZERO,
6094 });
6095
6096 let mut flipped_orders = IndexSet::new();
6097
6098 for fill in self.pending_fills.values() {
6099 let matches_position = match position_id {
6100 Some(position_id) => fill.position_id == Some(position_id),
6101 None => order.parent_order_id().is_some_and(|parent_id| {
6102 fill.client_order_id == parent_id
6103 || cache
6104 .order(&fill.client_order_id)
6105 .is_some_and(|order| order.parent_order_id() == Some(parent_id))
6106 }),
6107 };
6108
6109 if !matches_position || flipped_orders.contains(&fill.client_order_id) {
6110 continue;
6111 }
6112
6113 let remaining = quantity
6114 .checked_add(fill.quantity_change)
6115 .ok_or_else(|| anyhow::anyhow!("Pending position quantity overflow"))?;
6116
6117 quantity = if splits_virtual_position
6118 && !quantity.is_zero()
6119 && !remaining.is_zero()
6120 && quantity.is_sign_negative() != remaining.is_sign_negative()
6121 {
6122 flipped_orders.insert(fill.client_order_id);
6123 Decimal::ZERO
6124 } else {
6125 remaining
6126 };
6127 }
6128
6129 Ok(quantity)
6130 }
6131
6132 fn purge_applied_fills(&mut self) {
6133 let cache = self.cache.borrow();
6134 let cash_cache = self.restricts_short_selling().then_some(&*cache);
6135 self.pending_fills.retain(|trade_id, fill| {
6136 let previous_position_id = fill.position_id;
6137 fill.position_id = cache
6138 .position_id(&fill.client_order_id)
6139 .copied()
6140 .or_else(|| {
6141 fill.position_id
6142 .filter(|id| cache.position(id).is_some())
6143 })
6144 .or_else(|| {
6145 let cache = cash_cache?;
6146 let order = cache.order(&fill.client_order_id)?;
6147 Self::position_id_for_order(cache, &order)
6148 })
6149 .or(fill.position_id);
6150
6151 let Some(position_id) = fill.position_id else {
6152 return cache.order_exists(&fill.client_order_id);
6153 };
6154
6155 let Some(position) = cache.position(&position_id) else {
6156 return cache.order_exists(&fill.client_order_id);
6157 };
6158
6159 if previous_position_id
6160 .and_then(|id| cache.position(&id))
6161 .iter()
6162 .chain(std::iter::once(&position))
6163 .any(|position| position.trade_ids.contains(trade_id))
6164 {
6165 return false;
6166 }
6167
6168 let opening_trade_id = position.events.first().map(|event| event.trade_id);
6169 if opening_trade_id != fill.opening_trade_id {
6170 if position.replay_events.iter().any(|event| {
6172 matches!(event, PositionReplayEvent::Filled(event) if event.trade_id == *trade_id)
6173 }) || cache.position_snapshots(Some(&position_id), None).iter()
6174 .any(|snapshot| snapshot.trade_ids.contains(trade_id))
6175 || cash_cache
6176 .and_then(|cache| cache.order(&fill.client_order_id))
6177 .filter(|order| position.opening_order_id == order.client_order_id())
6178 .is_some_and(|order| {
6179 order
6180 .trade_ids()
6181 .into_iter()
6182 .take_while(|id| Some(**id) != opening_trade_id)
6183 .any(|id| id == trade_id)
6184 })
6185 {
6186 return false;
6187 }
6188
6189 fill.opening_trade_id = opening_trade_id;
6190 }
6191
6192 true
6193 });
6194 }
6195
6196 fn fill_order(
6197 &mut self,
6198 order: &OrderAny,
6199 last_px: Price,
6200 last_qty: Quantity,
6201 liquidity_side: LiquiditySide,
6202 venue_position_id: Option<PositionId>,
6203 position: Option<&Position>,
6204 ) -> anyhow::Result<()> {
6205 self.check_size_precision(last_qty.precision, "fill quantity")?;
6206
6207 let (last_qty, new_filled_qty) = if let Some(filled_qty) = self
6208 .orders
6209 .cached_filled_qty
6210 .borrow()
6211 .get(&order.client_order_id())
6212 .copied()
6213 {
6214 let leaves_qty = order.quantity().saturating_sub(filled_qty);
6215 let last_qty = min(last_qty, leaves_qty);
6216 (last_qty, filled_qty + last_qty)
6217 } else {
6218 let last_qty = min(last_qty, order.quantity());
6219 (last_qty, last_qty)
6220 };
6221
6222 if last_qty.is_zero() {
6223 return Ok(());
6224 }
6225
6226 let mut commission_order = order.clone();
6229 write_filled_qty(
6230 &mut commission_order,
6231 new_filled_qty.saturating_sub(last_qty),
6232 );
6233
6234 if order.liquidity_side() != Some(liquidity_side) {
6235 commission_order.set_liquidity_side(liquidity_side);
6236 }
6237
6238 let underlying_px = self.fee_underlying_price(&self.instrument)?;
6239 let commission = self.fee_model.get_commission_with_context(
6240 &commission_order,
6241 last_qty,
6242 last_px,
6243 &self.instrument,
6244 underlying_px,
6245 )?;
6246
6247 let reduce_only_order_ids = position
6249 .map(|position| self.reduce_only_order_ids(position.id))
6250 .unwrap_or_default();
6251
6252 self.orders
6253 .cached_filled_qty
6254 .borrow_mut()
6255 .insert(order.client_order_id(), new_filled_qty);
6256
6257 let venue_order_id = self.ids_generator.get_venue_order_id(order).unwrap();
6258 self.generate_order_filled(
6259 order,
6260 venue_order_id,
6261 venue_position_id,
6262 last_qty,
6263 last_px,
6264 self.instrument.quote_currency(),
6265 commission,
6266 liquidity_side,
6267 );
6268
6269 self.complete_order_fill(order, venue_position_id, position, reduce_only_order_ids)
6270 }
6271
6272 fn complete_order_fill(
6273 &mut self,
6274 order: &OrderAny,
6275 venue_position_id: Option<PositionId>,
6276 position: Option<&Position>,
6277 mut reduce_only_order_ids: Vec<ClientOrderId>,
6278 ) -> anyhow::Result<()> {
6279 let post_fill_filled_qty = self.engine_filled_qty(order);
6280
6281 let post_fill_quantity = self
6282 .orders
6283 .pending_updates
6284 .borrow()
6285 .get(&order.client_order_id())
6286 .and_then(|updates| updates.last())
6287 .map_or_else(
6288 || {
6289 self.cache
6290 .borrow()
6291 .order(&order.client_order_id())
6292 .map_or(order.quantity(), |order| order.quantity())
6293 },
6294 |update| update.quantity,
6295 );
6296
6297 let post_fill_leaves_qty = post_fill_quantity.saturating_sub(post_fill_filled_qty);
6298 let fully_filled = post_fill_leaves_qty.is_zero();
6299
6300 if order.is_closed() || fully_filled {
6301 self.delete_core_order(order.client_order_id());
6302 self.remove_queue_position(order.client_order_id());
6303
6304 if order.order_type() != OrderType::MarketToLimit {
6307 self.purge_cached_filled_qty_if_closed(order.client_order_id());
6308 }
6309 }
6310
6311 self.process_fill_contingencies(order, venue_position_id, post_fill_leaves_qty)?;
6312
6313 if let Some(position) = position {
6314 reduce_only_order_ids.extend(self.reduce_only_order_ids(position.id));
6315 }
6316
6317 reduce_only_order_ids.extend(self.reduce_only_linked_order_ids(
6318 order,
6319 venue_position_id.or(position.map(|position| position.id)),
6320 ));
6321 reduce_only_order_ids.sort_unstable();
6322 reduce_only_order_ids.dedup();
6323 self.sync_reduce_only_orders(order, position, &reduce_only_order_ids)?;
6324
6325 Ok(())
6326 }
6327
6328 fn process_fill_contingencies(
6329 &mut self,
6330 order: &OrderAny,
6331 position_id: Option<PositionId>,
6332 leaves_qty: Quantity,
6333 ) -> anyhow::Result<()> {
6334 if !self.config.support_contingent_orders {
6335 return Ok(());
6336 }
6337
6338 self.queue_oto_resize(order);
6339
6340 match order.contingency_type() {
6341 Some(ContingencyType::Oto) => {
6342 self.release_oto_children_after_fill(order, position_id, leaves_qty.is_zero())?;
6343 }
6344 Some(ContingencyType::Oco) => self.cancel_oco_after_fill(order)?,
6345 Some(ContingencyType::Ouo) => self.update_ouo_after_fill(order, leaves_qty)?,
6346 None => {}
6347 }
6348
6349 Ok(())
6350 }
6351
6352 fn queue_oto_resize(&self, order: &OrderAny) {
6353 let Some(parent) = self.full_trigger_oto_parent(order) else {
6354 return;
6355 };
6356
6357 let mut commands = self.orders.commands.borrow_mut();
6358 let index = commands
6359 .iter()
6360 .position(|command| !matches!(command, OtoCommand::Cancel { .. }))
6361 .unwrap_or(commands.len());
6362 commands.insert(
6363 index,
6364 OtoCommand::Resize {
6365 instrument_id: parent.instrument_id(),
6366 parent_order_id: parent.client_order_id(),
6367 quantity: parent.quantity(),
6368 },
6369 );
6370 }
6371
6372 fn release_oto_children_after_fill(
6373 &mut self,
6374 parent: &OrderAny,
6375 position_id: Option<PositionId>,
6376 fully_filled: bool,
6377 ) -> anyhow::Result<()> {
6378 let Some(ids) = parent.linked_order_ids() else {
6379 log::error!(
6380 "OTO order {} does not have linked orders",
6381 parent.client_order_id()
6382 );
6383 return Ok(());
6384 };
6385
6386 for id in ids {
6387 let mut child = self
6388 .order_snapshot(*id)
6389 .ok_or_else(|| anyhow::anyhow!("Order {id} not found in cache"))?;
6390 self.release_oto_child_after_fill(parent, &mut child, position_id, fully_filled)?;
6391 }
6392
6393 Ok(())
6394 }
6395
6396 fn release_oto_child_after_fill(
6397 &mut self,
6398 parent: &OrderAny,
6399 child: &mut OrderAny,
6400 position_id: Option<PositionId>,
6401 fully_filled: bool,
6402 ) -> anyhow::Result<()> {
6403 self.apply_deferred_submission(child, false)?;
6404 let id = child.client_order_id();
6405 if child.is_closed()
6406 || child.leaves_qty().is_zero()
6407 || child.is_active_local()
6408 || self.orders.closed_oto_order_ids.borrow().contains(&id)
6409 || self.inflight_orders.contains(id)
6410 {
6411 return Ok(());
6412 }
6413
6414 if child.instrument_id() == parent.instrument_id()
6415 && let (None, Some(position_id)) =
6416 (child.position_id(), parent.position_id().or(position_id))
6417 {
6418 self.cache
6419 .borrow_mut()
6420 .add_position_id(&position_id, &self.venue, &id, &child.strategy_id())
6421 .unwrap();
6422 log::debug!("Added position id {position_id} to cache for order {id}");
6423 }
6424
6425 if child.is_open()
6426 && !(matches!(child.status(), OrderStatus::PendingUpdate)
6427 && child
6428 .previous_status()
6429 .is_some_and(|s| matches!(s, OrderStatus::Submitted)))
6430 {
6431 return Ok(());
6432 }
6433
6434 let account_id = parent
6435 .account_id()
6436 .or_else(|| self.account_ids.get(&parent.trader_id()).copied())
6437 .ok_or_else(|| {
6438 anyhow::anyhow!("Account ID not found for trader {}", parent.trader_id())
6439 })?;
6440
6441 if !self.config.oto_full_trigger || fully_filled {
6442 self.release_oto_child(child, account_id, parent, None);
6443 }
6444
6445 Ok(())
6446 }
6447
6448 fn oto_submission_cancel(&self, order: &OrderAny) -> Option<OtoCommand> {
6449 let id = order.client_order_id();
6450
6451 if let Some(command) = self.orders.commands.borrow().iter().find(|command| {
6452 matches!(command, OtoCommand::Cancel { client_order_id, .. } if *client_order_id == id)
6453 }) {
6454 return Some(command.clone());
6455 }
6456
6457 let sibling_filled = order.contingency_type() == Some(ContingencyType::Oco)
6459 && order.linked_order_ids().is_some_and(|ids| {
6460 ids.iter().any(|id| {
6461 self.order_snapshot(*id)
6462 .is_some_and(|sibling| !self.engine_filled_qty(&sibling).is_zero())
6463 })
6464 });
6465
6466 sibling_filled.then(|| OtoCommand::Cancel {
6467 instrument_id: order.instrument_id(),
6468 client_order_id: id,
6469 cancel_contingencies: false,
6470 excluded: Vec::new(),
6471 })
6472 }
6473
6474 fn cancel_oco_after_fill(&mut self, order: &OrderAny) -> anyhow::Result<()> {
6475 let Some(ids) = order.linked_order_ids() else {
6476 log::error!(
6477 "OCO order {} does not have linked orders",
6478 order.client_order_id()
6479 );
6480 return Ok(());
6481 };
6482
6483 for id in ids {
6484 let child = self
6485 .order_snapshot(*id)
6486 .ok_or_else(|| anyhow::anyhow!("Order {id} not found in cache"))?;
6487
6488 if self.contingent_order_is_closed(&child) || child.is_active_local() {
6489 continue;
6490 }
6491
6492 self.cancel_order(&child, Some(false));
6493 }
6494
6495 Ok(())
6496 }
6497
6498 fn update_ouo_after_fill(
6499 &mut self,
6500 order: &OrderAny,
6501 leaves_qty: Quantity,
6502 ) -> anyhow::Result<()> {
6503 let Some(ids) = order.linked_order_ids() else {
6504 log::error!(
6505 "OUO order {} does not have linked orders",
6506 order.client_order_id()
6507 );
6508 return Ok(());
6509 };
6510
6511 let mut excluded = ids.to_vec();
6512 excluded.push(order.client_order_id());
6513
6514 for id in ids {
6515 let child = self
6516 .order_snapshot(*id)
6517 .ok_or_else(|| anyhow::anyhow!("Order {id} not found in cache"))?;
6518 self.update_ouo_child_after_fill(&child, leaves_qty, &excluded);
6519 }
6520
6521 Ok(())
6522 }
6523
6524 fn update_ouo_child_after_fill(
6525 &mut self,
6526 child: &OrderAny,
6527 leaves_qty: Quantity,
6528 excluded: &[ClientOrderId],
6529 ) {
6530 if child.is_active_local()
6531 || self.contingent_order_is_closed(child)
6532 || self.inflight_orders.contains(child.client_order_id())
6533 {
6534 return;
6535 }
6536
6537 let leaves_qty = self.quantity_for_order(child, leaves_qty);
6538 let child_filled_qty = self.engine_filled_qty(child);
6539 if leaves_qty.is_zero() && !child.is_closed() {
6540 self.cancel_order_excluding(child, None, excluded);
6541 } else if child_filled_qty >= leaves_qty {
6542 self.cancel_order(child, Some(false));
6543 } else if leaves_qty.non_zero() {
6544 self.update_contingent_quantity(child, leaves_qty, false);
6545 }
6546 }
6547
6548 fn reduce_only_linked_order_ids(
6549 &self,
6550 order: &OrderAny,
6551 position_id: Option<PositionId>,
6552 ) -> Vec<ClientOrderId> {
6553 if !self.config.support_contingent_orders || !self.config.use_reduce_only {
6554 return Vec::new();
6555 }
6556
6557 let Some(linked_order_ids) = order.linked_order_ids() else {
6558 return Vec::new();
6559 };
6560
6561 let cache = self.cache.borrow();
6562 let position_id = position_id
6563 .or_else(|| Self::position_id_for_order(&cache, order))
6564 .or_else(|| {
6565 self.position_for_order_in_cache(&cache, order)
6566 .map(|position| position.id)
6567 });
6568
6569 linked_order_ids
6570 .iter()
6571 .filter(|id| {
6572 cache.order(id).is_some_and(|linked| {
6573 linked.strategy_id() == order.strategy_id()
6574 && Self::position_id_for_order(&cache, &linked).or_else(|| {
6575 self.position_for_order_in_cache(&cache, &linked)
6576 .map(|position| position.id)
6577 }) == position_id
6578 })
6579 })
6580 .copied()
6581 .collect()
6582 }
6583
6584 fn reduce_only_order_ids(&self, position_id: PositionId) -> Vec<ClientOrderId> {
6585 if !self.config.use_reduce_only {
6586 return Vec::new();
6587 }
6588
6589 let cache = self.cache.borrow();
6590 let mut order_ids = Vec::new();
6591
6592 for resting in self.core.iter_orders() {
6593 let Some(order) = cache.order(&resting.client_order_id) else {
6594 continue;
6595 };
6596
6597 if !order.is_reduce_only() || !order.is_open() || !order.is_passive() {
6598 continue;
6599 }
6600
6601 let matches_position = match cache.position_id(&resting.client_order_id) {
6602 Some(id) => *id == position_id,
6603 None => self
6604 .position_for_order_in_cache(&cache, &order)
6605 .is_some_and(|position| position.id == position_id),
6606 };
6607
6608 if matches_position {
6609 order_ids.push(resting.client_order_id);
6610 }
6611 }
6612
6613 order_ids.sort_unstable();
6614 order_ids
6615 }
6616
6617 fn sync_reduce_only_orders(
6618 &mut self,
6619 filled_order: &OrderAny,
6620 position: Option<&Position>,
6621 order_ids: &[ClientOrderId],
6622 ) -> anyhow::Result<()> {
6623 for &client_order_id in order_ids {
6624 if client_order_id == filled_order.client_order_id()
6626 || !self.core.order_exists(client_order_id)
6627 {
6628 continue;
6629 }
6630
6631 let Some(mut order) = self.order_snapshot(client_order_id) else {
6632 continue;
6633 };
6634
6635 if !order.is_reduce_only() || order.is_closed() || !order.is_passive() {
6636 continue;
6637 }
6638
6639 let position = {
6642 let cache = self.cache.borrow();
6643 position.map_or_else(
6644 || self.position_for_order_in_cache(&cache, &order),
6645 |position| {
6646 Some(cache.position(&position.id).map_or_else(
6647 || position.clone_without_events(),
6648 |position| position.clone_without_events(),
6649 ))
6650 },
6651 )
6652 };
6653
6654 let remaining = self.position_quantity_remaining(&order, position.as_ref())?;
6655 if remaining.is_zero() {
6656 self.cancel_reduce_only_order(&order, filled_order.client_order_id())?;
6657 continue;
6658 }
6659
6660 let leaves = self.parent_capped_leaves(&order, remaining);
6661
6662 let target = order.filled_qty().checked_add(leaves).ok_or_else(|| {
6663 anyhow::anyhow!("Reduce-only quantity overflow for order {client_order_id}")
6664 })?;
6665
6666 if self.resize_order(&mut order, target) {
6667 if target == order.filled_qty() {
6668 self.cancel_reduce_only_order(&order, filled_order.client_order_id())?;
6669 } else if self.config.support_contingent_orders
6670 && order.contingency_type() == Some(ContingencyType::Ouo)
6671 {
6672 self.sync_ouo_leaves(&order, leaves, filled_order.client_order_id())?;
6673 }
6674 }
6675 }
6676
6677 Ok(())
6678 }
6679
6680 fn cancel_reduce_only_order(
6681 &mut self,
6682 order: &OrderAny,
6683 filled_order_id: ClientOrderId,
6684 ) -> anyhow::Result<()> {
6685 let propagate = self.config.support_contingent_orders
6686 && order.contingency_type() == Some(ContingencyType::Ouo);
6687 self.cancel_order(order, Some(!propagate));
6688
6689 if propagate {
6690 self.sync_ouo_leaves(
6691 order,
6692 Quantity::zero(order.quantity().precision),
6693 filled_order_id,
6694 )?;
6695 }
6696
6697 Ok(())
6698 }
6699
6700 fn parent_capped_leaves(&self, order: &OrderAny, leaves: Quantity) -> Quantity {
6701 let parent = if self.config.support_contingent_orders {
6702 order
6703 .parent_order_id()
6704 .and_then(|id| self.order_snapshot(id))
6705 } else {
6706 None
6707 };
6708
6709 parent.map_or(leaves, |parent| {
6710 min(
6711 leaves,
6712 parent.filled_qty().saturating_sub(order.filled_qty()),
6713 )
6714 })
6715 }
6716
6717 fn sync_ouo_leaves(
6718 &mut self,
6719 order: &OrderAny,
6720 leaves: Quantity,
6721 filled_order_id: ClientOrderId,
6722 ) -> anyhow::Result<()> {
6723 for &client_order_id in order.linked_order_ids().into_iter().flatten() {
6724 if client_order_id == filled_order_id || !self.core.order_exists(client_order_id) {
6725 continue;
6726 }
6727
6728 let Some(mut sibling) = self.order_snapshot(client_order_id) else {
6729 continue;
6730 };
6731
6732 if sibling.is_closed() || sibling.is_active_local() || !sibling.is_passive() {
6733 continue;
6734 }
6735
6736 if leaves.is_zero() {
6738 self.cancel_order(&sibling, Some(false));
6739 continue;
6740 }
6741
6742 if !sibling.is_open() {
6743 continue;
6744 }
6745
6746 let leaves = self.parent_capped_leaves(&sibling, leaves);
6747
6748 let target = sibling.filled_qty().checked_add(leaves).ok_or_else(|| {
6749 anyhow::anyhow!("OUO quantity overflow for order {client_order_id}")
6750 })?;
6751
6752 self.resize_order(&mut sibling, target);
6753 if leaves.is_zero() {
6754 self.cancel_order(&sibling, Some(false));
6755 }
6756 }
6757
6758 Ok(())
6759 }
6760
6761 fn resize_order(&self, order: &mut OrderAny, target: Quantity) -> bool {
6764 let quote = order.is_quote_quantity() && !self.instrument.is_inverse();
6765
6766 if order.quantity() == target && !quote {
6767 return false;
6768 }
6769
6770 if quote {
6771 order.set_is_quote_quantity(false);
6772 }
6773
6774 self.generate_order_updated(
6775 order,
6776 target,
6777 order.price(),
6778 order.trigger_price(),
6779 None,
6780 None,
6781 );
6782 true
6783 }
6784
6785 fn fee_underlying_price(&self, instrument: &InstrumentAny) -> CorrectnessResult<Option<Price>> {
6786 if !matches!(
6787 instrument,
6788 InstrumentAny::CryptoOption(_) | InstrumentAny::OptionContract(_)
6789 ) {
6790 return Ok(None);
6791 }
6792
6793 let Some(underlying) = instrument.underlying() else {
6794 return Ok(None);
6795 };
6796
6797 let underlying_id = InstrumentId::from(format!("{underlying}.{}", self.venue).as_str());
6798 let instrument_id = instrument.id();
6799
6800 let cache = self.cache.borrow();
6801 if let Some(price) = cache
6802 .price(&underlying_id, PriceType::Last)
6803 .or_else(|| cache.price(&underlying_id, PriceType::Mark))
6804 .or_else(|| cache.price(&underlying_id, PriceType::Mid))
6805 {
6806 return Ok(Some(price));
6807 }
6808
6809 cache
6810 .option_greeks(&instrument_id)
6811 .and_then(|greeks| greeks.underlying_price)
6812 .map(|price| Price::new_checked(price, FIXED_PRECISION))
6813 .transpose()
6814 }
6815
6816 fn cached_order_is_closed(&self, client_order_id: ClientOrderId) -> bool {
6817 self.cache
6818 .borrow()
6819 .order(&client_order_id)
6820 .is_none_or(|order| order.is_closed())
6821 }
6822
6823 fn purge_cached_filled_qty_if_closed(&self, client_order_id: ClientOrderId) {
6824 if self.cached_order_is_closed(client_order_id) {
6825 self.orders
6826 .cached_filled_qty
6827 .borrow_mut()
6828 .swap_remove(&client_order_id);
6829 }
6830 }
6831
6832 fn has_nothing_to_match(&self, timestamp_ns: UnixNanos) -> bool {
6834 self.core.iter_orders().next().is_none()
6835 && self.post_match_order_ids.is_empty()
6836 && self.pending_fills.is_empty()
6837 && self.orders.cached_filled_qty.borrow().is_empty()
6838 && self.orders.pending_updates.borrow().is_empty()
6839 && self.orders.rejected_oto_parent_ids.borrow().is_empty()
6840 && self.orders.closed_oto_order_ids.borrow().is_empty()
6841 && self.target_bid.is_none()
6842 && self.target_ask.is_none()
6843 && self.target_last.is_none()
6844 && self.instrument_close.is_none()
6845 && self
6846 .instrument
6847 .expiration_ns()
6848 .is_none_or(|expiration_ns| timestamp_ns < expiration_ns)
6849 }
6850
6851 fn purge_closed_cached_filled_qty(&self) {
6852 let client_order_ids: Vec<ClientOrderId> = self
6853 .orders
6854 .cached_filled_qty
6855 .borrow()
6856 .keys()
6857 .copied()
6858 .collect();
6859
6860 for client_order_id in client_order_ids {
6861 self.purge_cached_filled_qty_if_closed(client_order_id);
6862 }
6863 }
6864
6865 fn update_limit_order(
6866 &mut self,
6867 order: &OrderAny,
6868 quantity: Quantity,
6869 price: Price,
6870 causation_id: Option<UUID4>,
6871 ) -> ModifyOutcome {
6872 if self.core.is_limit_matched(order.order_side(), price) {
6873 if order.is_post_only() {
6874 self.generate_order_modify_rejected(
6875 order.trader_id(),
6876 order.strategy_id(),
6877 order.instrument_id(),
6878 order.client_order_id(),
6879 Ustr::from(
6880 format!(
6881 "POST_ONLY {} {} order with new limit px of {} would have been a TAKER: bid={}, ask={}",
6882 order.order_type(),
6883 order.order_side(),
6884 price,
6885 self.core.bid.map_or_else(|| "None".to_string(), |p| p.to_string()),
6886 self.core.ask.map_or_else(|| "None".to_string(), |p| p.to_string())
6887 )
6888 .as_str(),
6889 ),
6890 order.venue_order_id(),
6891 order.account_id(),
6892 causation_id,
6893 );
6894 return ModifyOutcome::Rejected;
6895 }
6896
6897 self.generate_order_updated(order, quantity, Some(price), None, None, causation_id);
6898
6899 let client_order_id = order.client_order_id();
6901 if let Some(mut order) = self.cache.borrow_mut().order_mut(&client_order_id) {
6902 order.set_liquidity_side(LiquiditySide::Taker);
6903 }
6904
6905 self.fill_limit_order(client_order_id);
6906 return ModifyOutcome::Applied;
6907 }
6908
6909 self.generate_order_updated(order, quantity, Some(price), None, None, causation_id);
6910 ModifyOutcome::Applied
6911 }
6912
6913 fn update_stop_market_order(
6914 &self,
6915 order: &OrderAny,
6916 quantity: Quantity,
6917 trigger_price: Price,
6918 causation_id: Option<UUID4>,
6919 ) -> ModifyOutcome {
6920 if self.core.is_stop_matched_with_trigger_type(
6921 order.order_side(),
6922 trigger_price,
6923 order.trigger_type().unwrap_or(TriggerType::Default),
6924 ) {
6925 self.generate_order_modify_rejected(
6926 order.trader_id(),
6927 order.strategy_id(),
6928 order.instrument_id(),
6929 order.client_order_id(),
6930 Ustr::from(
6931 format!(
6932 "{} {} order new stop px of {} was in the market: bid={}, ask={}",
6933 order.order_type(),
6934 order.order_side(),
6935 trigger_price,
6936 self.core
6937 .bid
6938 .map_or_else(|| "None".to_string(), |p| p.to_string()),
6939 self.core
6940 .ask
6941 .map_or_else(|| "None".to_string(), |p| p.to_string())
6942 )
6943 .as_str(),
6944 ),
6945 order.venue_order_id(),
6946 order.account_id(),
6947 causation_id,
6948 );
6949 return ModifyOutcome::Rejected;
6950 }
6951
6952 self.generate_order_updated(
6953 order,
6954 quantity,
6955 None,
6956 Some(trigger_price),
6957 None,
6958 causation_id,
6959 );
6960 ModifyOutcome::Applied
6961 }
6962
6963 fn update_stop_limit_order(
6964 &mut self,
6965 order: &OrderAny,
6966 quantity: Quantity,
6967 price: Price,
6968 trigger_price: Price,
6969 causation_id: Option<UUID4>,
6970 ) -> ModifyOutcome {
6971 if order.is_triggered().is_some_and(|t| t) {
6972 if self.core.is_limit_matched(order.order_side(), price) {
6973 return self.update_limit_order(order, quantity, price, causation_id);
6974 }
6975 } else {
6976 if self.core.is_stop_matched_with_trigger_type(
6978 order.order_side(),
6979 trigger_price,
6980 order.trigger_type().unwrap_or(TriggerType::Default),
6981 ) {
6982 self.generate_order_modify_rejected(
6983 order.trader_id(),
6984 order.strategy_id(),
6985 order.instrument_id(),
6986 order.client_order_id(),
6987 Ustr::from(
6988 format!(
6989 "{} {} order new stop px of {} was in the market: bid={}, ask={}",
6990 order.order_type(),
6991 order.order_side(),
6992 trigger_price,
6993 self.core
6994 .bid
6995 .map_or_else(|| "None".to_string(), |p| p.to_string()),
6996 self.core
6997 .ask
6998 .map_or_else(|| "None".to_string(), |p| p.to_string())
6999 )
7000 .as_str(),
7001 ),
7002 order.venue_order_id(),
7003 order.account_id(),
7004 causation_id,
7005 );
7006 return ModifyOutcome::Rejected;
7007 }
7008 }
7009
7010 self.generate_order_updated(
7011 order,
7012 quantity,
7013 Some(price),
7014 Some(trigger_price),
7015 None,
7016 causation_id,
7017 );
7018 ModifyOutcome::Applied
7019 }
7020
7021 fn update_market_if_touched_order(
7022 &self,
7023 order: &OrderAny,
7024 quantity: Quantity,
7025 trigger_price: Price,
7026 causation_id: Option<UUID4>,
7027 ) -> ModifyOutcome {
7028 if self.core.is_touch_triggered_with_trigger_type(
7029 order.order_side(),
7030 trigger_price,
7031 order.trigger_type().unwrap_or(TriggerType::Default),
7032 ) {
7033 self.generate_order_modify_rejected(
7034 order.trader_id(),
7035 order.strategy_id(),
7036 order.instrument_id(),
7037 order.client_order_id(),
7038 Ustr::from(
7039 format!(
7040 "{} {} order new trigger px of {} was in the market: bid={}, ask={}",
7041 order.order_type(),
7042 order.order_side(),
7043 trigger_price,
7044 self.core
7045 .bid
7046 .map_or_else(|| "None".to_string(), |p| p.to_string()),
7047 self.core
7048 .ask
7049 .map_or_else(|| "None".to_string(), |p| p.to_string())
7050 )
7051 .as_str(),
7052 ),
7053 order.venue_order_id(),
7054 order.account_id(),
7055 causation_id,
7056 );
7057
7058 return ModifyOutcome::Rejected;
7060 }
7061
7062 self.generate_order_updated(
7063 order,
7064 quantity,
7065 None,
7066 Some(trigger_price),
7067 None,
7068 causation_id,
7069 );
7070 ModifyOutcome::Applied
7071 }
7072
7073 fn update_limit_if_touched_order(
7074 &mut self,
7075 order: &OrderAny,
7076 quantity: Quantity,
7077 price: Price,
7078 trigger_price: Price,
7079 causation_id: Option<UUID4>,
7080 ) -> ModifyOutcome {
7081 if order.is_triggered().is_some_and(|t| t) {
7082 if self.core.is_limit_matched(order.order_side(), price) {
7083 return self.update_limit_order(order, quantity, price, causation_id);
7084 }
7085 } else {
7086 if self.core.is_touch_triggered_with_trigger_type(
7088 order.order_side(),
7089 trigger_price,
7090 order.trigger_type().unwrap_or(TriggerType::Default),
7091 ) {
7092 self.generate_order_modify_rejected(
7093 order.trader_id(),
7094 order.strategy_id(),
7095 order.instrument_id(),
7096 order.client_order_id(),
7097 Ustr::from(
7098 format!(
7099 "{} {} order new trigger px of {} was in the market: bid={}, ask={}",
7100 order.order_type(),
7101 order.order_side(),
7102 trigger_price,
7103 self.core
7104 .bid
7105 .map_or_else(|| "None".to_string(), |p| p.to_string()),
7106 self.core
7107 .ask
7108 .map_or_else(|| "None".to_string(), |p| p.to_string())
7109 )
7110 .as_str(),
7111 ),
7112 order.venue_order_id(),
7113 order.account_id(),
7114 causation_id,
7115 );
7116 return ModifyOutcome::Rejected;
7117 }
7118 }
7119
7120 self.generate_order_updated(
7121 order,
7122 quantity,
7123 Some(price),
7124 Some(trigger_price),
7125 None,
7126 causation_id,
7127 );
7128 ModifyOutcome::Applied
7129 }
7130
7131 fn update_trailing_stop_order(&self, order: &OrderAny) {
7132 let (new_trigger_price, new_price) = match trailing_stop_calculate(
7133 self.instrument.price_increment(),
7134 order.trigger_price(),
7135 order,
7136 self.core.bid,
7137 self.core.ask,
7138 if order.trigger_type() == Some(TriggerType::MarkPrice) {
7139 self.core.mark
7140 } else {
7141 self.core.last
7142 },
7143 ) {
7144 Ok(prices) => prices,
7145 Err(e) => {
7146 log::debug!("Cannot calculate trailing-stop update: {e}");
7148 return;
7149 }
7150 };
7151
7152 if new_trigger_price.is_none() && new_price.is_none() {
7153 return;
7154 }
7155
7156 self.generate_order_updated(
7157 order,
7158 order.quantity(),
7159 new_price,
7160 new_trigger_price,
7161 None,
7162 None,
7163 );
7164 }
7165
7166 fn accept_order(&mut self, order: &mut OrderAny) {
7167 if order.is_closed() {
7168 return;
7170 }
7171
7172 if order.status() != OrderStatus::Accepted {
7173 let venue_order_id = self.ids_generator.get_venue_order_id(order).unwrap();
7174 let event = self.create_order_accepted(order, venue_order_id);
7175
7176 if let Err(e) = order.apply(event.clone()) {
7179 log::warn!(
7180 "Skipping local apply of accepted event for {}: {e}",
7181 order.client_order_id(),
7182 );
7183 }
7184
7185 self.dispatch_order_event(event);
7186
7187 if matches!(
7190 order.order_type(),
7191 OrderType::TrailingStopLimit | OrderType::TrailingStopMarket
7192 ) && order.trigger_price().is_none()
7193 && self.maybe_activate_trailing_stop(
7194 order,
7195 self.core.bid,
7196 self.core.ask,
7197 self.core.last,
7198 )
7199 {
7200 self.update_trailing_stop_order(order);
7201 }
7202 }
7203
7204 let match_info = Self::matching_core_entry(order);
7205 self.track_post_match_order(order);
7206 self.core.add_order(match_info);
7207 }
7208
7209 fn track_post_match_order(&mut self, order: &OrderAny) {
7210 self.post_match_order_ids.insert(order.client_order_id());
7211 }
7212
7213 fn delete_core_order(&mut self, client_order_id: ClientOrderId) {
7214 self.post_match_order_ids.swap_remove(&client_order_id);
7215 let _ = self.core.delete_order(client_order_id);
7216 }
7217
7218 fn requires_post_match_maintenance(order: &OrderAny) -> bool {
7219 order.expire_time().is_some()
7220 || matches!(
7221 order.order_type(),
7222 OrderType::TrailingStopMarket | OrderType::TrailingStopLimit
7223 )
7224 }
7225
7226 fn matching_core_entry(order: &OrderAny) -> RestingOrder {
7227 let is_limit_style_stop = matches!(
7228 order.order_type(),
7229 OrderType::StopLimit | OrderType::LimitIfTouched | OrderType::TrailingStopLimit
7230 );
7231 let is_triggered = order.is_triggered().is_some_and(|triggered| triggered);
7232 let triggered_limit_style = is_limit_style_stop && is_triggered;
7233
7234 let limit_price = if is_limit_style_stop && !is_triggered && order.trigger_price().is_none()
7236 {
7237 None
7238 } else {
7239 order.price()
7240 };
7241
7242 RestingOrder::new_with_trigger_type(
7243 order.client_order_id(),
7244 order.order_side(),
7245 order.order_type(),
7246 Some(order.trigger_type().unwrap_or(TriggerType::Default)),
7247 if triggered_limit_style {
7248 None
7249 } else {
7250 order.trigger_price()
7251 },
7252 limit_price,
7253 match order {
7254 OrderAny::TrailingStopMarket(o) => o.is_activated,
7255 OrderAny::TrailingStopLimit(o) => o.is_activated,
7256 _ => true,
7257 },
7258 )
7259 }
7260
7261 fn expire_order(&mut self, order: &OrderAny) {
7262 self.delete_core_order(order.client_order_id());
7263 self.remove_queue_position(order.client_order_id());
7264 if self.config.support_contingent_orders && order.contingency_type().is_some() {
7265 self.cancel_contingent_orders(order, &[]);
7266 }
7267
7268 self.generate_order_expired(order);
7269 self.purge_cached_filled_qty_if_closed(order.client_order_id());
7270 }
7271
7272 fn cancel_order(&mut self, order: &OrderAny, cancel_contingencies: Option<bool>) {
7273 self.cancel_order_excluding(order, cancel_contingencies, &[]);
7274 }
7275
7276 fn cancel_order_excluding(
7279 &mut self,
7280 order: &OrderAny,
7281 cancel_contingencies: Option<bool>,
7282 excluded: &[ClientOrderId],
7283 ) {
7284 if self.inflight_orders.contains(order.client_order_id()) {
7285 return;
7286 }
7287
7288 let cancel_contingencies = cancel_contingencies.unwrap_or(true);
7289
7290 if order.instrument_id() != self.instrument.id() && order.parent_order_id().is_some() {
7291 let mut commands = self.orders.commands.borrow_mut();
7292 if !commands.iter().any(|command| matches!(command,
7293 OtoCommand::Cancel { client_order_id, .. } if *client_order_id == order.client_order_id()))
7294 {
7295 commands.push_front(OtoCommand::Cancel {
7297 instrument_id: order.instrument_id(), client_order_id: order.client_order_id(),
7298 cancel_contingencies, excluded: excluded.to_vec(),
7299 });
7300 }
7301
7302 return;
7303 }
7304
7305 if order.is_active_local()
7306 && !matches!(
7307 (order.status(), order.order_type()),
7308 (
7309 OrderStatus::Initialized | OrderStatus::Released,
7310 OrderType::Market
7311 )
7312 )
7313 {
7314 log::error!(
7315 "Cannot cancel an order with {} from the matching engine",
7316 order.status()
7317 );
7318 return;
7319 }
7320
7321 if self.core.order_exists(order.client_order_id()) {
7323 self.delete_core_order(order.client_order_id());
7324 }
7325
7326 self.orders
7327 .pending_oto_order_ids
7328 .borrow_mut()
7329 .swap_remove(&order.client_order_id());
7330 self.remove_queue_position(order.client_order_id());
7331
7332 let venue_order_id = self.ids_generator.get_venue_order_id(order).unwrap();
7333 self.generate_order_canceled(order, venue_order_id);
7334 if self.config.support_contingent_orders
7335 && order.contingency_type().is_some()
7336 && cancel_contingencies
7337 {
7338 self.cancel_contingent_orders(order, excluded);
7339 }
7340
7341 self.purge_cached_filled_qty_if_closed(order.client_order_id());
7344 }
7345
7346 fn update_order(
7347 &mut self,
7348 order: &OrderAny,
7349 quantity: Option<Quantity>,
7350 price: Option<Price>,
7351 trigger_price: Option<Price>,
7352 update_contingencies: Option<bool>,
7353 causation_id: Option<UUID4>,
7354 ) -> bool {
7355 if self.inflight_orders.contains(order.client_order_id()) {
7356 return false;
7357 }
7358
7359 let update_contingencies = update_contingencies.unwrap_or(true);
7360 let quantity = quantity.unwrap_or(order.quantity());
7361
7362 let size_prec = self.instrument.size_precision();
7363 let instrument_id = self.instrument.id();
7364
7365 if !order_precision_valid(quantity.precision, size_prec) {
7366 self.generate_order_modify_rejected(
7367 order.trader_id(),
7368 order.strategy_id(),
7369 order.instrument_id(),
7370 order.client_order_id(),
7371 Ustr::from(&format!(
7372 "Invalid update quantity precision {}, expected {size_prec} for {instrument_id}",
7373 quantity.precision
7374 )),
7375 order.venue_order_id(),
7376 order.account_id(),
7377 causation_id,
7378 );
7379 return false;
7380 }
7381
7382 let price_rejection = price
7385 .filter(|px| Some(*px) != order.price())
7386 .and_then(|px| self.update_price_rejection("price", px))
7387 .or_else(|| {
7388 trigger_price
7389 .filter(|tp| Some(*tp) != order.trigger_price())
7390 .and_then(|tp| self.update_price_rejection("trigger_price", tp))
7391 });
7392
7393 if let Some(reason) = price_rejection {
7394 self.generate_order_modify_rejected(
7395 order.trader_id(),
7396 order.strategy_id(),
7397 order.instrument_id(),
7398 order.client_order_id(),
7399 Ustr::from(&reason),
7400 order.venue_order_id(),
7401 order.account_id(),
7402 causation_id,
7403 );
7404 return false;
7405 }
7406
7407 let filled_qty = self.engine_filled_qty(order);
7409
7410 if quantity < filled_qty {
7411 self.generate_order_modify_rejected(
7412 order.trader_id(),
7413 order.strategy_id(),
7414 order.instrument_id(),
7415 order.client_order_id(),
7416 Ustr::from(&format!(
7417 "Cannot reduce order quantity {quantity} below filled quantity {filled_qty}",
7418 )),
7419 order.venue_order_id(),
7420 order.account_id(),
7421 causation_id,
7422 );
7423 return false;
7424 }
7425
7426 let outcome = match order {
7427 OrderAny::Limit(_) | OrderAny::MarketToLimit(_) => {
7428 let price = price.unwrap_or(order.price().unwrap());
7429 self.update_limit_order(order, quantity, price, causation_id)
7430 }
7431 OrderAny::StopMarket(_) => {
7432 let trigger_price = trigger_price.unwrap_or(order.trigger_price().unwrap());
7433 self.update_stop_market_order(order, quantity, trigger_price, causation_id)
7434 }
7435 OrderAny::StopLimit(_) => {
7436 let price = price.unwrap_or(order.price().unwrap());
7437 let trigger_price = trigger_price.unwrap_or(order.trigger_price().unwrap());
7438 self.update_stop_limit_order(order, quantity, price, trigger_price, causation_id)
7439 }
7440 OrderAny::MarketIfTouched(_) => {
7441 let trigger_price = trigger_price.unwrap_or(order.trigger_price().unwrap());
7442 self.update_market_if_touched_order(order, quantity, trigger_price, causation_id)
7443 }
7444 OrderAny::LimitIfTouched(_) => {
7445 let price = price.unwrap_or(order.price().unwrap());
7446 let trigger_price = trigger_price.unwrap_or(order.trigger_price().unwrap());
7447 self.update_limit_if_touched_order(
7448 order,
7449 quantity,
7450 price,
7451 trigger_price,
7452 causation_id,
7453 )
7454 }
7455 OrderAny::TrailingStopMarket(inner) => match trigger_price.or(order.trigger_price()) {
7459 Some(trigger_price)
7460 if inner.is_activated || self.trailing_stop_activates_now(order) =>
7461 {
7462 self.update_stop_market_order(order, quantity, trigger_price, causation_id)
7463 }
7464 trigger_price => {
7465 self.generate_order_updated(
7466 order,
7467 quantity,
7468 None,
7469 trigger_price,
7470 None,
7471 causation_id,
7472 );
7473 ModifyOutcome::Applied
7474 }
7475 },
7476 OrderAny::TrailingStopLimit(inner) => match (
7477 price.or(order.price()),
7478 trigger_price.or(order.trigger_price()),
7479 ) {
7480 (Some(price), Some(trigger_price))
7481 if inner.is_activated || self.trailing_stop_activates_now(order) =>
7482 {
7483 self.update_stop_limit_order(
7484 order,
7485 quantity,
7486 price,
7487 trigger_price,
7488 causation_id,
7489 )
7490 }
7491 (price, trigger_price) => {
7492 self.generate_order_updated(
7493 order,
7494 quantity,
7495 price,
7496 trigger_price,
7497 None,
7498 causation_id,
7499 );
7500 ModifyOutcome::Applied
7501 }
7502 },
7503 _ => {
7504 panic!(
7505 "Unsupported order type {} for update_order",
7506 order.order_type()
7507 );
7508 }
7509 };
7510
7511 if outcome == ModifyOutcome::Rejected {
7512 return false;
7513 }
7514
7515 if self.config.support_contingent_orders
7516 && order.contingency_type().is_some()
7517 && update_contingencies
7518 {
7519 self.update_contingent_order(order, quantity);
7520 }
7521
7522 let new_leaves_qty = quantity.saturating_sub(filled_qty);
7524 if new_leaves_qty.is_zero() {
7525 self.cancel_order(order, Some(false));
7527 return true;
7528 }
7529
7530 true
7531 }
7532
7533 fn update_price_rejection(&self, field: &str, price: Price) -> Option<String> {
7534 let price_precision = self.instrument.price_precision();
7535 let instrument_id = self.instrument.id();
7536
7537 if !order_precision_valid(price.precision, price_precision) {
7538 return Some(format!(
7539 "Invalid update {field} precision {}, expected {price_precision} for {instrument_id}",
7540 price.precision
7541 ));
7542 }
7543
7544 let price_increment = self.instrument.price_increment();
7545 if !Self::price_matches_tick(price, price_increment) {
7546 return Some(format!(
7547 "Invalid update {field} {price}, not a multiple of {instrument_id} price increment {price_increment}"
7548 ));
7549 }
7550
7551 None
7552 }
7553
7554 pub fn trigger_stop_order(&mut self, client_order_id: ClientOrderId) {
7556 let order = match self.order_snapshot(client_order_id) {
7557 Some(order) => order,
7558 None => {
7559 log::error!(
7560 "Cannot trigger stop order: order {client_order_id} not found in cache"
7561 );
7562 return;
7563 }
7564 };
7565
7566 if order.is_closed() {
7567 log::debug!("Cannot trigger stop order: {client_order_id} already closed");
7568 return;
7569 }
7570
7571 match order.order_type() {
7572 OrderType::StopLimit | OrderType::LimitIfTouched | OrderType::TrailingStopLimit => {
7573 self.trigger_limit_style_stop_order(client_order_id, order);
7574 }
7575 OrderType::StopMarket | OrderType::MarketIfTouched | OrderType::TrailingStopMarket => {
7576 self.fill_market_order(client_order_id);
7577 }
7578 _ => {
7579 log::error!(
7580 "Cannot trigger stop order: invalid order type {}",
7581 order.order_type()
7582 );
7583 }
7584 }
7585 }
7586
7587 fn trigger_limit_style_stop_order(&mut self, client_order_id: ClientOrderId, order: OrderAny) {
7588 if order.is_triggered().is_some_and(|triggered| triggered) {
7589 let liquidity_side = match (order.price(), order.trigger_price()) {
7590 (Some(price), Some(trigger_price)) => self.determine_triggered_limit_liquidity(
7591 order.order_side(),
7592 price,
7593 trigger_price,
7594 order.trigger_type(),
7595 ),
7596 _ => LiquiditySide::Maker,
7597 };
7598
7599 if let Some(mut cached_order) = self.cache.borrow_mut().order_mut(&client_order_id)
7600 && !matches!(
7601 cached_order.liquidity_side(),
7602 Some(LiquiditySide::Maker | LiquiditySide::Taker)
7603 )
7604 {
7605 cached_order.set_liquidity_side(liquidity_side);
7606 }
7607
7608 self.fill_limit_order(client_order_id);
7609 return;
7610 }
7611
7612 let event = self.create_order_triggered(&order);
7613
7614 let order = match self.cache.borrow_mut().update_order(&event) {
7615 Ok(order) => order,
7616 Err(e) => {
7617 log::debug!(
7618 "Failed to apply triggered event for {} before fill: {e}",
7619 order.client_order_id(),
7620 );
7621 order
7622 }
7623 };
7624
7625 let order = self.order_snapshot(client_order_id).unwrap_or(order);
7626 self.dispatch_order_event(event);
7627
7628 let trigger_price = order
7629 .trigger_price()
7630 .expect("Limit-style stop order must have a trigger price");
7631 let price = order
7632 .price()
7633 .expect("Limit-style stop order must have a price");
7634
7635 let liquidity_side = self.determine_triggered_limit_liquidity(
7636 order.order_side(),
7637 price,
7638 trigger_price,
7639 order.trigger_type(),
7640 );
7641
7642 let maker_inside = match order.order_side() {
7643 OrderSide::Buy => self
7644 .core
7645 .ask
7646 .is_some_and(|ask| liquidity_side == LiquiditySide::Maker && price > ask),
7647 OrderSide::Sell => self
7648 .core
7649 .bid
7650 .is_some_and(|bid| liquidity_side == LiquiditySide::Maker && price < bid),
7651 };
7652
7653 if maker_inside {
7654 if let Some(mut cached_order) = self.cache.borrow_mut().order_mut(&client_order_id) {
7655 cached_order.set_liquidity_side(LiquiditySide::Maker);
7656 }
7657
7658 self.resync_core_entry(client_order_id);
7659 self.fill_limit_order(client_order_id);
7660 return;
7661 }
7662
7663 if self.core.is_limit_matched(order.order_side(), price) {
7664 if order.is_post_only() {
7665 self.delete_core_order(client_order_id);
7666 self.orders
7667 .cached_filled_qty
7668 .borrow_mut()
7669 .swap_remove(&client_order_id);
7670 let event = self.create_order_rejected(
7671 &order,
7672 format!(
7673 "POST_ONLY {} {} order limit px of {} would have been a TAKER: bid={}, ask={}",
7674 order.order_type(),
7675 order.order_side(),
7676 price,
7677 self.core
7678 .bid
7679 .map_or_else(|| "None".to_string(), |p| p.to_string()),
7680 self.core
7681 .ask
7682 .map_or_else(|| "None".to_string(), |p| p.to_string())
7683 )
7684 .into(),
7685 );
7686
7687 if let Err(e) = self.cache.borrow_mut().update_order(&event) {
7688 log::debug!(
7689 "Failed to apply rejected event for {} after post-only trigger: {e}",
7690 order.client_order_id(),
7691 );
7692 }
7693
7694 self.dispatch_order_event(event);
7695 return;
7696 }
7697
7698 if let Some(mut cached_order) = self.cache.borrow_mut().order_mut(&client_order_id) {
7699 cached_order.set_liquidity_side(LiquiditySide::Taker);
7700 }
7701
7702 self.resync_core_entry(client_order_id);
7703 self.fill_limit_order(client_order_id);
7704 return;
7705 }
7706
7707 if let Some(mut cached_order) = self.cache.borrow_mut().order_mut(&client_order_id) {
7708 cached_order.set_liquidity_side(liquidity_side);
7709 }
7710
7711 if matches!(order.time_in_force(), TimeInForce::Fok | TimeInForce::Ioc) {
7712 self.cancel_order(&order, None);
7713 return;
7714 }
7715
7716 self.resync_core_entry(client_order_id);
7717 }
7718
7719 fn determine_triggered_limit_liquidity(
7720 &self,
7721 side: OrderSide,
7722 price: Price,
7723 trigger_price: Price,
7724 trigger_type: Option<TriggerType>,
7725 ) -> LiquiditySide {
7726 if trigger_type == Some(TriggerType::MarkPrice) {
7727 return if self.core.is_limit_matched(side, price) {
7728 LiquiditySide::Taker
7729 } else {
7730 LiquiditySide::Maker
7731 };
7732 }
7733
7734 if (side == OrderSide::Buy && trigger_price > price)
7735 || (side == OrderSide::Sell && trigger_price < price)
7736 {
7737 LiquiditySide::Maker
7738 } else {
7739 LiquiditySide::Taker
7740 }
7741 }
7742
7743 fn update_contingent_order(&mut self, order: &OrderAny, parent_quantity: Quantity) {
7744 log::debug!(
7745 "Updating contingent orders from {}",
7746 order.client_order_id()
7747 );
7748
7749 if order.contingency_type() == Some(ContingencyType::Oto) {
7750 self.update_oto_children(order, Some(parent_quantity), &[]);
7751 return;
7752 }
7753
7754 if let Some(linked_order_ids) = order.linked_order_ids() {
7755 let parent_filled_qty = self.engine_filled_qty(order);
7756 let parent_leaves_qty = parent_quantity.saturating_sub(parent_filled_qty);
7757
7758 for client_order_id in linked_order_ids {
7759 let child_order = match self.order_snapshot(*client_order_id) {
7760 Some(order) => order,
7761 None => panic!("Order {client_order_id} not found in cache."),
7762 };
7763
7764 if child_order.is_active_local() {
7765 continue;
7766 }
7767
7768 let child_filled_qty = self.engine_filled_qty(&child_order);
7769 if child_filled_qty >= parent_leaves_qty {
7770 self.cancel_order(&child_order, Some(false));
7772 } else {
7773 self.update_contingent_quantity(
7774 &child_order,
7775 parent_leaves_qty,
7776 order.is_quote_quantity() && !self.instrument.is_inverse(),
7777 );
7778 }
7779 }
7780 }
7781 }
7782
7783 fn update_contingent_quantity(
7784 &mut self,
7785 order: &OrderAny,
7786 quantity: Quantity,
7787 is_quote_quantity: bool,
7788 ) {
7789 if self.contingent_order_is_closed(order)
7790 || self.inflight_orders.contains(order.client_order_id())
7791 {
7792 return;
7793 }
7794
7795 let quantity = self.quantity_for_order(order, quantity);
7796 if quantity <= self.engine_filled_qty(order) {
7797 self.cancel_order(order, Some(false));
7798 return;
7799 }
7800
7801 let clear_quote = order.is_quote_quantity()
7802 && !is_quote_quantity
7803 && if order.instrument_id() == self.instrument.id() {
7804 !self.instrument.is_inverse()
7805 } else {
7806 self.cache
7807 .borrow()
7808 .instrument(&order.instrument_id())
7809 .is_some_and(|instrument| !instrument.is_inverse())
7810 };
7811
7812 if quantity == order.leaves_qty() && !clear_quote {
7813 return;
7814 }
7815
7816 let mut converted;
7817 let order = if clear_quote {
7818 converted = order.clone();
7819 converted.set_is_quote_quantity(false);
7820 &converted
7821 } else {
7822 order
7823 };
7824
7825 let price = order.price();
7826 let trigger_price = order.trigger_price();
7827 if order.instrument_id() == self.instrument.id() {
7828 self.update_order(
7829 order,
7830 Some(quantity),
7831 price,
7832 trigger_price,
7833 Some(false),
7834 None,
7835 );
7836 } else {
7837 self.generate_order_updated(order, quantity, price, trigger_price, None, None);
7838 }
7839 }
7840
7841 fn apply_deferred_submission(
7848 &mut self,
7849 order: &mut OrderAny,
7850 accepted_elsewhere: bool,
7851 ) -> anyhow::Result<()> {
7852 let client_order_id = order.client_order_id();
7853 let accepted = self.core.order_exists(client_order_id) || accepted_elsewhere;
7854
7855 if !order.is_active_local()
7856 || !(accepted
7857 || self
7858 .orders
7859 .pending_oto_order_ids
7860 .borrow()
7861 .contains(&client_order_id))
7862 {
7863 return Ok(());
7864 }
7865
7866 let account_id = match order.account_id() {
7867 Some(account_id) => account_id,
7868 None => *self
7869 .account_ids
7870 .get(&order.trader_id())
7871 .ok_or_else(|| anyhow::anyhow!("No account ID for {}", order.trader_id()))?,
7872 };
7873
7874 let event = self.create_order_submitted(order, account_id);
7875 order.apply(event)?;
7876 if accepted {
7877 let venue_order_id = self.ids_generator.get_venue_order_id(order)?;
7878 let event = self.create_order_accepted(order, venue_order_id);
7879 order.apply(event)?;
7880 }
7881
7882 Ok(())
7883 }
7884
7885 fn works_in_another_engine(&self, order: &OrderAny) -> bool {
7887 order.instrument_id() != self.instrument.id()
7888 && (self
7889 .orders
7890 .released_oto_order_ids
7891 .borrow()
7892 .contains(&order.client_order_id())
7893 || self
7894 .cache
7895 .borrow()
7896 .venue_order_id(&order.client_order_id())
7897 .is_some())
7898 }
7899
7900 fn update_oto_children(
7916 &mut self,
7917 parent: &OrderAny,
7918 parent_quantity: Option<Quantity>,
7919 excluded: &[ClientOrderId],
7920 ) {
7921 let Some(ids) = parent.linked_order_ids() else {
7922 return;
7923 };
7924
7925 let snapshot = self
7926 .order_snapshot(parent.client_order_id())
7927 .unwrap_or_else(|| parent.clone());
7928 let filled_qty = self.engine_filled_qty(&snapshot);
7929 let quantity = parent_quantity.unwrap_or(filled_qty);
7930 let sizing = OtoSizing {
7931 quantity,
7932 filled_qty,
7933 quote: snapshot.is_quote_quantity() && !self.instrument.is_inverse(),
7934 reduced_to_filled: parent_quantity.is_some_and(|q| q <= filled_qty),
7935 grew: quantity > parent.quantity(),
7937 };
7938
7939 let mut released = false;
7940
7941 for id in ids {
7942 if excluded.contains(id) {
7943 continue;
7945 }
7946
7947 released |= self.update_oto_child(parent, *id, ids, &sizing);
7948 }
7949
7950 if released {
7951 let not_resting: Vec<_> = ids
7953 .iter()
7954 .filter(|id| {
7955 excluded.contains(*id)
7956 || (!self.core.order_exists(**id)
7957 && !self
7958 .order_snapshot(**id)
7959 .is_some_and(|order| self.works_in_another_engine(&order)))
7960 })
7961 .copied()
7962 .collect();
7963
7964 self.update_oto_children(parent, Some(quantity), ¬_resting);
7965 }
7966 }
7967
7968 fn update_oto_child(
7969 &mut self,
7970 parent: &OrderAny,
7971 id: ClientOrderId,
7972 ids: &[ClientOrderId],
7973 sizing: &OtoSizing,
7974 ) -> bool {
7975 let mut child = self
7976 .order_snapshot(id)
7977 .unwrap_or_else(|| panic!("Cannot find contingent order for {id}"));
7978 let elsewhere = self.works_in_another_engine(&child);
7979 let accepted_elsewhere = elsewhere && self.cache.borrow().venue_order_id(&id).is_some();
7980 if let Err(e) = self.apply_deferred_submission(&mut child, accepted_elsewhere) {
7981 log::error!("Cannot update contingent order {id}: {e}");
7982 return false;
7983 }
7984
7985 if child.is_active_local()
7986 || self.contingent_order_is_closed(&child)
7987 || self.inflight_orders.contains(id)
7988 {
7989 return false;
7990 }
7991
7992 let remaining = self.oto_child_remaining(&child, ids, sizing.quantity);
7993 let released = self.core.order_exists(id) || elsewhere;
7994 if !released && !self.config.oto_full_trigger && !sizing.filled_qty.is_zero() {
7996 return false;
7997 }
7998
7999 let release = !released && sizing.reduced_to_filled && self.config.oto_full_trigger;
8000 let parent_closed = sizing.quantity <= sizing.filled_qty;
8001 if parent_closed && ((!released && !release) || remaining.is_zero()) {
8002 self.cancel_order(&child, Some(false));
8003 return false;
8004 }
8005
8006 if remaining.is_zero() {
8007 return false;
8008 }
8009
8010 self.resize_oto_child(&mut child, sizing, remaining);
8011
8012 if !release {
8013 return false;
8014 }
8015
8016 self.release_oto_child_after_resize(parent, id, sizing.quantity)
8017 }
8018
8019 fn contingent_order_is_closed(&self, order: &OrderAny) -> bool {
8020 order.is_closed()
8021 || order.leaves_qty().is_zero()
8022 || self
8023 .orders
8024 .closed_oto_order_ids
8025 .borrow()
8026 .contains(&order.client_order_id())
8027 }
8028
8029 fn oto_child_remaining(
8030 &self,
8031 child: &OrderAny,
8032 ids: &[ClientOrderId],
8033 quantity: Quantity,
8034 ) -> Quantity {
8035 let filled = ids
8037 .iter()
8038 .filter_map(|id| self.order_snapshot(*id))
8039 .fold(Quantity::zero(quantity.precision), |acc, order| {
8040 acc + self.engine_filled_qty(&order)
8041 });
8042
8043 self.quantity_for_order(child, quantity.saturating_sub(filled))
8044 }
8045
8046 fn quantity_for_order(&self, order: &OrderAny, quantity: Quantity) -> Quantity {
8047 if order.instrument_id() == self.instrument.id() {
8048 let precision = self.instrument.size_precision();
8049 if order_precision_valid(quantity.precision, precision) {
8051 return quantity;
8052 }
8053
8054 let rounded = quantity
8055 .as_decimal()
8056 .round_dp_with_strategy(u32::from(precision), RoundingStrategy::ToZero);
8057 return Quantity::from_decimal_dp(rounded, precision)
8058 .unwrap_or_else(|_| Quantity::zero(precision));
8059 }
8060
8061 let cache = self.cache.borrow();
8062 cache
8063 .instrument(&order.instrument_id())
8064 .map_or(quantity, |instrument| {
8065 if quantity.precision <= FIXED_PRECISION
8066 && quantity.precision == instrument.size_precision()
8067 && Self::quantity_matches_precision(quantity, 0)
8068 {
8069 return quantity;
8070 }
8071
8072 instrument
8073 .try_make_qty_from_decimal(quantity.as_decimal(), Some(true))
8074 .unwrap_or_else(|_| Quantity::zero(instrument.size_precision()))
8075 })
8076 }
8077
8078 fn resize_oto_child(&self, child: &mut OrderAny, sizing: &OtoSizing, remaining: Quantity) {
8079 let quote = child.is_quote_quantity();
8080 let other_instrument = child.instrument_id() != self.instrument.id();
8081 if !self.convert_to_parent_units(child, sizing.quote, other_instrument) {
8082 return;
8083 }
8084
8085 let converted = quote != child.is_quote_quantity();
8086 let parent_closed = sizing.quantity <= sizing.filled_qty;
8087 let mut quantity = self.engine_filled_qty(child) + remaining;
8088 if parent_closed || !sizing.grew {
8089 quantity = quantity.min(child.quantity());
8090 }
8091
8092 if quantity != child.quantity() || (parent_closed && converted) {
8094 self.generate_order_updated(
8096 child,
8097 quantity,
8098 child.price(),
8099 child.trigger_price(),
8100 None,
8101 None,
8102 );
8103 }
8104 }
8105
8106 fn release_oto_child_after_resize(
8107 &mut self,
8108 parent: &OrderAny,
8109 id: ClientOrderId,
8110 quantity: Quantity,
8111 ) -> bool {
8112 let account_id = parent
8113 .account_id()
8114 .or_else(|| self.account_ids.get(&parent.trader_id()).copied());
8115
8116 match (self.order_snapshot(id), account_id) {
8117 (Some(mut child), Some(account_id)) => {
8118 self.release_oto_child(&mut child, account_id, parent, Some(quantity));
8119 true
8120 }
8121 _ => {
8122 log::error!("Cannot release OTO order {id}");
8123 false
8124 }
8125 }
8126 }
8127
8128 fn release_oto_child(
8129 &mut self,
8130 child: &mut OrderAny,
8131 account_id: AccountId,
8132 parent: &OrderAny,
8133 parent_quantity: Option<Quantity>,
8134 ) {
8135 if child.instrument_id() == self.instrument.id() {
8136 self.process_order(child, account_id);
8137 } else if self
8138 .orders
8139 .released_oto_order_ids
8140 .borrow_mut()
8141 .insert(child.client_order_id())
8142 {
8143 self.orders
8144 .commands
8145 .borrow_mut()
8146 .push_back(OtoCommand::Release {
8147 instrument_id: child.instrument_id(),
8148 client_order_id: child.client_order_id(),
8149 account_id,
8150 parent_instrument_id: self.instrument.id(),
8151 parent_order_id: parent.client_order_id(),
8152 parent_quantity,
8153 });
8154 }
8155 }
8156
8157 fn convert_to_parent_units(
8167 &self,
8168 child: &mut OrderAny,
8169 parent_quote: bool,
8170 other_instrument: bool,
8171 ) -> bool {
8172 let cache = self.cache.borrow();
8173 let instrument = cache
8174 .instrument(&child.instrument_id())
8175 .filter(|_| other_instrument)
8176 .unwrap_or(&self.instrument);
8177 let child_quote = child.is_quote_quantity() && !instrument.is_inverse();
8178
8179 if child_quote == parent_quote {
8180 return true;
8181 }
8182
8183 if parent_quote {
8184 return false;
8185 }
8186
8187 let opposing_best = match child.order_side() {
8188 OrderSide::Buy => self.core.ask,
8189 OrderSide::Sell => self.core.bid,
8190 };
8191
8192 let reference_price = child
8193 .price()
8194 .or(child.trigger_price())
8195 .or(opposing_best.filter(|_| !other_instrument));
8196
8197 let base_quantity = reference_price.and_then(|price| {
8198 instrument
8199 .try_calculate_base_quantity(child.quantity(), price)
8200 .ok()
8201 });
8202
8203 let Some(base_quantity) = base_quantity else {
8204 return false;
8205 };
8206
8207 child.set_quantity(base_quantity);
8208 child.set_is_quote_quantity(false);
8209 true
8210 }
8211
8212 fn engine_filled_qty(&self, order: &OrderAny) -> Quantity {
8213 self.orders
8214 .cached_filled_qty
8215 .borrow()
8216 .get(&order.client_order_id())
8217 .copied()
8218 .unwrap_or(order.filled_qty())
8219 }
8220
8221 fn cancel_contingent_orders(&mut self, order: &OrderAny, excluded: &[ClientOrderId]) {
8222 if order.contingency_type() == Some(ContingencyType::Oto) {
8223 self.update_oto_children(order, None, excluded);
8224 return;
8225 }
8226
8227 if let Some(linked_order_ids) = order.linked_order_ids() {
8228 for client_order_id in linked_order_ids {
8229 if excluded.contains(client_order_id) {
8230 continue;
8231 }
8232
8233 let mut contingent_order = match self.order_snapshot(*client_order_id) {
8234 Some(order) => order,
8235 None => panic!("Cannot find contingent order for {client_order_id}"),
8236 };
8237
8238 if let Err(e) = self.apply_deferred_submission(&mut contingent_order, false) {
8239 log::error!("Cannot cancel contingent order {client_order_id}: {e}");
8240 continue;
8241 }
8242
8243 if contingent_order.is_active_local() {
8244 continue;
8246 }
8247
8248 if !self.contingent_order_is_closed(&contingent_order) {
8249 self.cancel_order(&contingent_order, Some(false));
8250 }
8251 }
8252 }
8253 }
8254
8255 fn create_order_submitted(&self, order: &OrderAny, account_id: AccountId) -> OrderEventAny {
8256 let ts_now = self.clock.borrow().timestamp_ns();
8257 OrderEventAny::Submitted(OrderSubmitted::new(
8258 order.trader_id(),
8259 order.strategy_id(),
8260 order.instrument_id(),
8261 order.client_order_id(),
8262 account_id,
8263 UUID4::new(),
8264 ts_now,
8265 ts_now,
8266 ))
8267 }
8268
8269 fn generate_order_submitted(&self, order: &OrderAny, account_id: AccountId) {
8270 let event = self.create_order_submitted(order, account_id);
8271 self.dispatch_order_event(event);
8272 }
8273
8274 fn create_order_rejected(&self, order: &OrderAny, reason: Ustr) -> OrderEventAny {
8275 let ts_now = self.clock.borrow().timestamp_ns();
8276 let account_id = order
8277 .account_id()
8278 .unwrap_or(self.account_ids.get(&order.trader_id()).unwrap().to_owned());
8279
8280 let due_post_only = reason.starts_with("POST_ONLY");
8281
8282 OrderEventAny::Rejected(OrderRejected::new(
8283 order.trader_id(),
8284 order.strategy_id(),
8285 order.instrument_id(),
8286 order.client_order_id(),
8287 account_id,
8288 reason,
8289 UUID4::new(),
8290 ts_now,
8291 ts_now,
8292 false,
8293 due_post_only,
8294 ))
8295 }
8296
8297 fn generate_order_rejected(&self, order: &OrderAny, reason: Ustr) {
8298 if order.contingency_type() == Some(ContingencyType::Oto) {
8299 self.orders
8300 .rejected_oto_parent_ids
8301 .borrow_mut()
8302 .insert(order.client_order_id());
8303 }
8304
8305 let event = self.create_order_rejected(order, reason);
8306 self.dispatch_oto_terminal(order, event);
8307 }
8308
8309 fn publish_order_initialized(&self, order: &OrderAny) {
8310 let event = OrderEventAny::Initialized(order.init_event().clone());
8311 let topic = msgbus::switchboard::get_event_order_topic(order.strategy_id());
8312 msgbus::publish_order_event(topic, &event);
8313 }
8314
8315 fn create_order_accepted(
8316 &self,
8317 order: &OrderAny,
8318 venue_order_id: VenueOrderId,
8319 ) -> OrderEventAny {
8320 let ts_now = self.clock.borrow().timestamp_ns();
8321 let account_id = order
8322 .account_id()
8323 .unwrap_or(self.account_ids.get(&order.trader_id()).unwrap().to_owned());
8324 OrderEventAny::Accepted(OrderAccepted::new(
8325 order.trader_id(),
8326 order.strategy_id(),
8327 order.instrument_id(),
8328 order.client_order_id(),
8329 venue_order_id,
8330 account_id,
8331 UUID4::new(),
8332 ts_now,
8333 ts_now,
8334 false,
8335 ))
8336 }
8337
8338 fn generate_order_accepted(&self, order: &OrderAny, venue_order_id: VenueOrderId) {
8339 let event = self.create_order_accepted(order, venue_order_id);
8340 self.dispatch_order_event(event);
8341 }
8342
8343 #[expect(clippy::too_many_arguments)]
8344 fn generate_order_modify_rejected(
8345 &self,
8346 trader_id: TraderId,
8347 strategy_id: StrategyId,
8348 instrument_id: InstrumentId,
8349 client_order_id: ClientOrderId,
8350 reason: Ustr,
8351 venue_order_id: Option<VenueOrderId>,
8352 account_id: Option<AccountId>,
8353 causation_id: Option<UUID4>,
8354 ) {
8355 let ts_now = self.clock.borrow().timestamp_ns();
8356
8357 let mut event = OrderModifyRejected::new(
8358 trader_id,
8359 strategy_id,
8360 instrument_id,
8361 client_order_id,
8362 reason,
8363 UUID4::new(),
8364 ts_now,
8365 ts_now,
8366 false,
8367 venue_order_id,
8368 account_id,
8369 );
8370 event.causation_id = causation_id;
8371 self.dispatch_order_event(OrderEventAny::ModifyRejected(event));
8372 }
8373
8374 #[expect(clippy::too_many_arguments)]
8375 fn generate_order_cancel_rejected(
8376 &self,
8377 trader_id: TraderId,
8378 strategy_id: StrategyId,
8379 account_id: AccountId,
8380 instrument_id: InstrumentId,
8381 client_order_id: ClientOrderId,
8382 venue_order_id: Option<VenueOrderId>,
8383 reason: Ustr,
8384 causation_id: Option<UUID4>,
8385 ) {
8386 let ts_now = self.clock.borrow().timestamp_ns();
8387
8388 let mut event = OrderCancelRejected::new(
8389 trader_id,
8390 strategy_id,
8391 instrument_id,
8392 client_order_id,
8393 reason,
8394 UUID4::new(),
8395 ts_now,
8396 ts_now,
8397 false,
8398 venue_order_id,
8399 Some(account_id),
8400 );
8401 event.causation_id = causation_id;
8402 self.dispatch_order_event(OrderEventAny::CancelRejected(event));
8403 }
8404
8405 fn generate_order_updated(
8406 &self,
8407 order: &OrderAny,
8408 quantity: Quantity,
8409 price: Option<Price>,
8410 trigger_price: Option<Price>,
8411 protection_price: Option<Price>,
8412 causation_id: Option<UUID4>,
8413 ) {
8414 let ts_now = self.clock.borrow().timestamp_ns();
8415
8416 let mut event = OrderUpdated::new(
8417 order.trader_id(),
8418 order.strategy_id(),
8419 order.instrument_id(),
8420 order.client_order_id(),
8421 quantity,
8422 UUID4::new(),
8423 ts_now,
8424 ts_now,
8425 false,
8426 order.venue_order_id(),
8427 order.account_id(),
8428 price,
8429 trigger_price,
8430 protection_price,
8431 order.is_quote_quantity(),
8432 );
8433
8434 event.causation_id = causation_id;
8435 self.orders
8436 .pending_updates
8437 .borrow_mut()
8438 .entry(order.client_order_id())
8439 .or_default()
8440 .push(event);
8441 self.dispatch_order_event(OrderEventAny::Updated(event));
8442 }
8443
8444 fn generate_order_canceled(&self, order: &OrderAny, venue_order_id: VenueOrderId) {
8445 let ts_now = self.clock.borrow().timestamp_ns();
8446 let event = OrderEventAny::Canceled(OrderCanceled::new(
8447 order.trader_id(),
8448 order.strategy_id(),
8449 order.instrument_id(),
8450 order.client_order_id(),
8451 UUID4::new(),
8452 ts_now,
8453 ts_now,
8454 false,
8455 Some(venue_order_id),
8456 order.account_id(),
8457 None,
8458 ));
8459 self.dispatch_oto_terminal(order, event);
8460 }
8461
8462 fn create_order_triggered(&self, order: &OrderAny) -> OrderEventAny {
8463 let ts_now = self.clock.borrow().timestamp_ns();
8464 OrderEventAny::Triggered(OrderTriggered::new(
8465 order.trader_id(),
8466 order.strategy_id(),
8467 order.instrument_id(),
8468 order.client_order_id(),
8469 UUID4::new(),
8470 ts_now,
8471 ts_now,
8472 false,
8473 order.venue_order_id(),
8474 order.account_id(),
8475 ))
8476 }
8477
8478 fn generate_order_expired(&self, order: &OrderAny) {
8479 let ts_now = self.clock.borrow().timestamp_ns();
8480 let event = OrderEventAny::Expired(OrderExpired::new(
8481 order.trader_id(),
8482 order.strategy_id(),
8483 order.instrument_id(),
8484 order.client_order_id(),
8485 UUID4::new(),
8486 ts_now,
8487 ts_now,
8488 false,
8489 order.venue_order_id(),
8490 order.account_id(),
8491 ));
8492 self.dispatch_oto_terminal(order, event);
8493 }
8494
8495 fn dispatch_oto_terminal(&self, order: &OrderAny, event: OrderEventAny) {
8496 if self.config.support_contingent_orders && order.parent_order_id().is_some() {
8497 self.orders
8498 .closed_oto_order_ids
8499 .borrow_mut()
8500 .insert(order.client_order_id());
8501 }
8502
8503 self.dispatch_order_event(event);
8504
8505 if self.cached_order_is_closed(order.client_order_id()) {
8506 self.orders
8507 .closed_oto_order_ids
8508 .borrow_mut()
8509 .swap_remove(&order.client_order_id());
8510 }
8511 }
8512
8513 #[expect(clippy::too_many_arguments)]
8514 fn generate_order_filled(
8515 &mut self,
8516 order: &OrderAny,
8517 venue_order_id: VenueOrderId,
8518 venue_position_id: Option<PositionId>,
8519 last_qty: Quantity,
8520 last_px: Price,
8521 quote_currency: Currency,
8522 commission: Money,
8523 liquidity_side: LiquiditySide,
8524 ) {
8525 debug_assert!(
8526 last_qty <= order.quantity(),
8527 "Fill quantity {last_qty} exceeds order quantity {order_qty} for {client_order_id}",
8528 order_qty = order.quantity(),
8529 client_order_id = order.client_order_id()
8530 );
8531
8532 let ts_now = self.clock.borrow().timestamp_ns();
8533 let account_id = order
8534 .account_id()
8535 .unwrap_or(self.account_ids.get(&order.trader_id()).unwrap().to_owned());
8536
8537 let fill = OrderFilled::new(
8538 order.trader_id(),
8539 order.strategy_id(),
8540 order.instrument_id(),
8541 order.client_order_id(),
8542 venue_order_id,
8543 account_id,
8544 self.ids_generator.generate_trade_id(ts_now),
8545 order.order_side(),
8546 order.order_type(),
8547 last_qty,
8548 last_px,
8549 quote_currency,
8550 liquidity_side,
8551 UUID4::new(),
8552 ts_now,
8553 ts_now,
8554 false,
8555 venue_position_id,
8556 Some(commission),
8557 None,
8558 );
8559
8560 self.record_pending_fill(&fill);
8561 self.dispatch_order_event(OrderEventAny::Filled(fill));
8562 }
8563
8564 fn record_pending_fill(&mut self, fill: &OrderFilled) {
8565 if (!self.config.use_reduce_only
8566 && !self.restricts_short_selling()
8567 && !self.instrument.has_expiration())
8568 || self.instrument.is_spread()
8569 {
8570 return;
8571 }
8572
8573 self.purge_applied_fills();
8574 let cache = self.cache.borrow();
8575
8576 let position_id = cache
8577 .position_id(&fill.client_order_id)
8578 .copied()
8579 .or(fill.position_id)
8580 .or_else(|| {
8581 (self.oms_type == OmsType::Netting).then(|| {
8582 PositionId::new(format!("{}-{}", fill.instrument_id, fill.strategy_id))
8583 })
8584 });
8585
8586 let opening_trade_id = position_id.and_then(|id| {
8587 cache
8588 .position(&id)
8589 .and_then(|position| position.events.first().map(|event| event.trade_id))
8590 });
8591
8592 let mut quantity_change = if fill.order_side == OrderSide::Buy {
8593 fill.last_qty.as_decimal()
8594 } else {
8595 -fill.last_qty.as_decimal()
8596 };
8597
8598 if matches!(
8599 self.instrument,
8600 InstrumentAny::CurrencyPair(_) | InstrumentAny::TokenizedAsset(_)
8601 ) && let Some(commission) = fill.commission
8602 && Some(commission.currency) == self.instrument.base_currency()
8603 {
8604 quantity_change -= commission.as_decimal();
8605 }
8606
8607 self.pending_fills.insert(
8608 fill.trade_id,
8609 PendingFill {
8610 client_order_id: fill.client_order_id,
8611 position_id,
8612 opening_trade_id,
8613 quantity_change,
8614 },
8615 );
8616 }
8617}
8618
8619struct OtoSizing {
8620 quantity: Quantity,
8621 filled_qty: Quantity,
8622 quote: bool,
8623 reduced_to_filled: bool,
8624 grew: bool,
8625}
8626
8627#[derive(Debug)]
8628struct PendingFill {
8629 client_order_id: ClientOrderId,
8630 position_id: Option<PositionId>,
8631 opening_trade_id: Option<TradeId>,
8632 quantity_change: Decimal,
8633}
8634
8635#[derive(Debug)]
8640struct ConsumptionJournal {
8641 order_side: OrderSide,
8642 trade_consumption: QuantityRaw,
8643 levels: Vec<(PriceRaw, Option<(QuantityRaw, QuantityRaw)>)>,
8644}
8645
8646#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8647enum ModifyOutcome {
8648 Applied,
8649 Rejected,
8650}
8651
8652#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8653enum OrderMatchMode {
8654 All,
8655 StopTriggers(TriggerType),
8656}
8657
8658#[derive(Debug)]
8659enum PostMatchOrderAction {
8660 RemoveClosed,
8661 Expire(OrderAny),
8662 UpdateTrailing(OrderAny),
8663 NoMaintenance,
8664}
8665
8666fn order_precision_valid(actual: u8, expected: u8) -> bool {
8667 actual <= expected && raw_scales_match(actual, expected)
8668}
8669
8670fn post_match_order_action<F>(
8671 order: &OrderAny,
8672 support_gtd_orders: bool,
8673 timestamp_ns: UnixNanos,
8674 clone_order: F,
8675) -> PostMatchOrderAction
8676where
8677 F: FnOnce(&OrderAny) -> OrderAny,
8678{
8679 if order.is_closed() {
8680 PostMatchOrderAction::RemoveClosed
8681 } else if support_gtd_orders
8682 && order
8683 .expire_time()
8684 .is_some_and(|expire_ns| timestamp_ns >= expire_ns)
8685 {
8686 PostMatchOrderAction::Expire(clone_order(order))
8687 } else if matches!(
8688 order.order_type(),
8689 OrderType::TrailingStopMarket | OrderType::TrailingStopLimit
8690 ) {
8691 PostMatchOrderAction::UpdateTrailing(clone_order(order))
8692 } else {
8693 PostMatchOrderAction::NoMaintenance
8694 }
8695}
8696
8697fn write_filled_qty(order: &mut OrderAny, filled_qty: Quantity) {
8702 match order {
8703 OrderAny::Limit(o) => o.filled_qty = filled_qty,
8704 OrderAny::LimitIfTouched(o) => o.filled_qty = filled_qty,
8705 OrderAny::Market(o) => o.filled_qty = filled_qty,
8706 OrderAny::MarketIfTouched(o) => o.filled_qty = filled_qty,
8707 OrderAny::MarketToLimit(o) => o.filled_qty = filled_qty,
8708 OrderAny::StopLimit(o) => o.filled_qty = filled_qty,
8709 OrderAny::StopMarket(o) => o.filled_qty = filled_qty,
8710 OrderAny::TrailingStopLimit(o) => o.filled_qty = filled_qty,
8711 OrderAny::TrailingStopMarket(o) => o.filled_qty = filled_qty,
8712 }
8713}
8714
8715#[derive(Debug, Clone, Copy)]
8716struct BarTickSizes {
8717 open: Quantity,
8718 high: Quantity,
8719 low: Quantity,
8720 close: Quantity,
8721}
8722
8723impl BarTickSizes {
8724 fn from_volume(volume: Quantity, size_increment: Quantity) -> Self {
8725 let precision_diff = FIXED_PRECISION.saturating_sub(volume.precision);
8726 let scale = QuantityRaw::pow(10, u32::from(precision_diff));
8727 let units = volume.raw() / scale;
8728 let increment_units = (size_increment.raw() / scale).max(1);
8729 let rounded_units = (units / increment_units) * increment_units;
8730 let increments = rounded_units / increment_units;
8731 let zero = Quantity::zero(volume.precision);
8732 let size =
8733 |increments| Quantity::from_raw(increments * increment_units * scale, volume.precision);
8734
8735 match increments {
8736 0 => Self {
8737 open: zero,
8738 high: zero,
8739 low: zero,
8740 close: zero,
8741 },
8742
8743 1 => Self {
8745 open: zero,
8746 high: zero,
8747 low: zero,
8748 close: size(1),
8749 },
8750 2 => Self {
8751 open: zero,
8752 high: size(1),
8753 low: size(1),
8754 close: zero,
8755 },
8756 3 => {
8757 let path_size = size(1);
8758
8759 Self {
8760 open: path_size,
8761 high: path_size,
8762 low: path_size,
8763 close: zero,
8764 }
8765 }
8766 _ => {
8767 let path_increments = increments / 4;
8768 let close_increments = increments - (path_increments * 3);
8769 let path_size = size(path_increments);
8770
8771 Self {
8772 open: path_size,
8773 high: path_size,
8774 low: path_size,
8775 close: size(close_increments),
8776 }
8777 }
8778 }
8779 }
8780}