Skip to main content

nautilus_execution/matching_engine/
mod.rs

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