Skip to main content

nautilus_execution/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//! Provides a generic `ExecutionEngine` for all environments.
17//!
18//! The execution engines primary responsibility is to orchestrate interactions
19//! between the `ExecutionClient` instances, and the rest of the platform. This
20//! includes sending commands to, and receiving events from, the trading venue
21//! endpoints via its registered execution clients.
22
23pub mod config;
24pub mod position;
25pub mod settlement;
26pub mod stubs;
27
28use std::{
29    cell::{Cell, RefCell, RefMut},
30    collections::{HashMap, HashSet},
31    fmt::{Debug, Display},
32    rc::Rc,
33    time::SystemTime,
34};
35
36use ahash::{AHashMap, AHashSet};
37use config::ExecutionEngineConfig;
38use futures::future::join_all;
39use indexmap::{IndexMap, IndexSet};
40use nautilus_common::{
41    cache::{Cache, PositionRef},
42    clients::ExecutionClient,
43    clock::Clock,
44    enums::LogColor,
45    generators::position_id::PositionIdGenerator,
46    log_info,
47    logging::{CMD, EVT, RECV, SEND},
48    messages::{
49        ExecutionReport,
50        execution::{
51            BatchCancelOrders, BatchModifyOrders, CancelAllOrders, CancelOrder, ModifyOrder,
52            QueryAccount, QueryOrder, SubmitOrder, SubmitOrderList, TradingCommand,
53        },
54    },
55    msgbus::{
56        self, MStr, MessagingSwitchboard, Pattern, TypedHandler, TypedIntoHandler, get_message_bus,
57        switchboard::{self},
58        typed_handler::ShareableMessageHandler,
59    },
60    runner::{
61        TradingCommandMessage, capture_trading_cmd, trading_cmd_is_dispatching,
62        try_get_trading_cmd_sender,
63    },
64    timer::{TimeEvent, TimeEventCallback},
65};
66use nautilus_core::{
67    DurationNanos, UUID4, UnixNanos, WeakCell,
68    datetime::{mins_to_secs, secs_to_nanos},
69};
70use nautilus_model::{
71    accounts::Account,
72    data::InstrumentClose,
73    enums::{
74        AccountType, ContingencyType, OmsType, OrderStatus, OrderType, PositionSide, TimeInForce,
75    },
76    events::{
77        OrderAccepted, OrderCancelDenied, OrderDenied, OrderDeniedReason, OrderEvent,
78        OrderEventAny, OrderFillVoided, OrderFilled, OrderInitialized, OrderModifyDenied,
79        OrderUpdated, PositionChanged, PositionClosed, PositionEvent, PositionOpened,
80    },
81    identifiers::{
82        AccountId, ClientId, ClientOrderId, ExecAlgorithmId, InstrumentId, PositionId, StrategyId,
83        TradeId, Venue, VenueOrderId,
84    },
85    instruments::{Instrument, InstrumentAny},
86    orderbook::own::{OwnBookOrder, OwnOrderBook, should_handle_own_book_order},
87    orders::{Order, OrderAny, OrderError},
88    position::{Position, PositionReplayEvent},
89    reports::{ExecutionMassStatus, FillReport, OrderStatusReport, PositionStatusReport},
90    types::{Money, Quantity},
91};
92use position::CorrectedPosition;
93pub use position::{PositionStateSnapshot, SnapshotAnchorer};
94use rust_decimal::Decimal;
95
96use crate::{
97    client::ExecutionClientAdapter,
98    reconciliation::{
99        check_position_reconciliation, fill_precedes_reconciled_position,
100        fill_precedes_snapshot_reconciled_position, generate_external_order_status_events,
101        generate_reconciliation_order_events, generate_reconciliation_order_pre_fill_events,
102        generate_reconciliation_order_snapshot_events, reconcile_fill_report as reconcile_fill,
103    },
104};
105
106const TIMER_SNAPSHOT_POSITIONS: &str = "ExecEngine_SNAPSHOT_POSITIONS";
107const TIMER_PURGE_CLOSED_ORDERS: &str = "ExecEngine_PURGE_CLOSED_ORDERS";
108const TIMER_PURGE_CLOSED_POSITIONS: &str = "ExecEngine_PURGE_CLOSED_POSITIONS";
109const TIMER_PURGE_ACCOUNT_EVENTS: &str = "ExecEngine_PURGE_ACCOUNT_EVENTS";
110
111/// Central execution engine responsible for orchestrating order routing and execution.
112///
113/// The execution engine manages the entire order lifecycle from submission to completion,
114/// handling routing to appropriate execution clients, position management, and event
115/// processing. It supports multiple execution venues through registered clients and
116/// provides sophisticated order management capabilities.
117///
118/// An order dispatched to a registered or external execution client keeps its `Initialized` (or
119/// `Released`) status until the client's first status event is applied, so cached status alone
120/// cannot distinguish it from an order that has not been routed yet. The engine records each
121/// dispatch until that first status transition, and a later submit command naming the order is
122/// stale for it: the engine neither routes the order to a client again nor denies it when the
123/// later command fails validation. The record is process-local: a reset clears it, and it is
124/// absent after a restart, where a still-`Initialized` dispatched order is treated like any other
125/// unrouted order until it is resolved by the client's events or a venue cancel or expiry report.
126pub struct ExecutionEngine {
127    clock: Rc<RefCell<dyn Clock>>,
128    cache: Rc<RefCell<Cache>>,
129    clients: IndexMap<ClientId, ExecutionClientAdapter>,
130    default_client_id: Option<ClientId>,
131    routing_map: AHashMap<Venue, ClientId>,
132    instrument_venues: AHashSet<Venue>,
133    instrument_close_venues: AHashSet<Venue>,
134    oms_overrides: AHashMap<StrategyId, OmsType>,
135    external_clients: HashSet<ClientId>,
136    pos_id_generator: PositionIdGenerator,
137    config: ExecutionEngineConfig,
138    command_count: Cell<u64>,
139    event_count: u64,
140    report_count: u64,
141    filtered_unclaimed_external_order_count: u64,
142    snapshot_anchorer: Option<SnapshotAnchorer>,
143}
144
145impl Debug for ExecutionEngine {
146    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147        f.debug_struct(stringify!(ExecutionEngine))
148            .field("client_count", &self.clients.len())
149            .finish()
150    }
151}
152
153fn fill_affects_quantity(apply_position: bool, restatement: bool) -> bool {
154    apply_position && !restatement
155}
156
157fn is_fill_price_restatement(order: &OrderAny, fill: &OrderFilled) -> bool {
158    order.events().iter().any(|event| {
159        matches!(
160            event,
161            OrderEventAny::Filled(existing)
162                if existing.trade_id == fill.trade_id && existing.last_px != fill.last_px
163        )
164    })
165}
166
167impl ExecutionEngine {
168    /// Creates a new [`ExecutionEngine`] instance.
169    pub fn new(
170        clock: Rc<RefCell<dyn Clock>>,
171        cache: Rc<RefCell<Cache>>,
172        config: Option<ExecutionEngineConfig>,
173    ) -> Self {
174        let trader_id = get_message_bus().borrow().trader_id;
175        let external_clients: HashSet<ClientId> = config
176            .as_ref()
177            .and_then(|c| c.external_clients.clone())
178            .unwrap_or_default()
179            .into_iter()
180            .collect();
181        {
182            let mut cache = cache.borrow_mut();
183            for client_id in &external_clients {
184                cache.add_external_exec_client(*client_id);
185            }
186        }
187
188        Self {
189            clock: clock.clone(),
190            cache,
191            clients: IndexMap::new(),
192            default_client_id: None,
193            routing_map: AHashMap::new(),
194            instrument_venues: AHashSet::new(),
195            instrument_close_venues: AHashSet::new(),
196            oms_overrides: AHashMap::new(),
197            external_clients,
198            pos_id_generator: PositionIdGenerator::new(trader_id, clock),
199            config: config.unwrap_or_default(),
200            command_count: Cell::new(0),
201            event_count: 0,
202            report_count: 0,
203            filtered_unclaimed_external_order_count: 0,
204            snapshot_anchorer: None,
205        }
206    }
207
208    /// Registers all message bus handlers for the execution engine.
209    pub fn register_msgbus_handlers(engine: &Rc<RefCell<Self>>) {
210        let weak = WeakCell::from(Rc::downgrade(engine));
211
212        let weak1 = weak.clone();
213        msgbus::register_trading_command_endpoint(
214            MessagingSwitchboard::exec_engine_execute(),
215            TypedIntoHandler::from(move |cmd: TradingCommand| {
216                if let Some(rc) = weak1.upgrade() {
217                    rc.borrow().execute(cmd);
218                }
219            }),
220        );
221
222        // Queued endpoint for deferred command execution (re-entrancy safe),
223        // with direct dispatch when no sender is installed.
224        msgbus::register_trading_command_endpoint(
225            MessagingSwitchboard::exec_engine_queue_execute(),
226            TypedIntoHandler::from(move |cmd: TradingCommand| {
227                let endpoint = MessagingSwitchboard::exec_engine_execute();
228                if trading_cmd_is_dispatching() {
229                    capture_trading_cmd(TradingCommandMessage::new(endpoint, cmd));
230                } else if let Some(sender) = try_get_trading_cmd_sender() {
231                    sender.execute(TradingCommandMessage::new(endpoint, cmd));
232                } else {
233                    msgbus::send_trading_command(endpoint, cmd);
234                }
235            }),
236        );
237
238        let weak2 = weak.clone();
239        msgbus::register_order_event_endpoint(
240            MessagingSwitchboard::exec_engine_process(),
241            TypedIntoHandler::from(move |event: OrderEventAny| {
242                if let Some(rc) = weak2.upgrade() {
243                    rc.borrow_mut().process(&event);
244                }
245            }),
246        );
247
248        let weak3 = weak;
249        msgbus::register_execution_report_endpoint(
250            MessagingSwitchboard::exec_engine_reconcile_execution_report(),
251            TypedIntoHandler::from(move |report: ExecutionReport| {
252                if let Some(rc) = weak3.upgrade() {
253                    rc.borrow_mut().reconcile_execution_report(&report);
254                }
255            }),
256        );
257    }
258
259    /// Returns the total count of trading commands received by the engine.
260    #[must_use]
261    pub fn command_count(&self) -> u64 {
262        self.command_count.get()
263    }
264
265    /// Returns the total count of order events received by the engine.
266    #[must_use]
267    pub const fn event_count(&self) -> u64 {
268        self.event_count
269    }
270
271    /// Returns the total count of execution reports received by the engine.
272    #[must_use]
273    pub const fn report_count(&self) -> u64 {
274        self.report_count
275    }
276
277    /// Returns the count of unclaimed external venue orders filtered by execution reconciliation.
278    #[must_use]
279    pub const fn filtered_unclaimed_external_order_count(&self) -> u64 {
280        self.filtered_unclaimed_external_order_count
281    }
282
283    /// Subscribes to instrument updates for a venue via the message bus.
284    ///
285    /// When instruments are published by the `DataEngine`, the handler routes
286    /// them to every client whose own venue matches, plus the client routed to that
287    /// venue, if any. Repeated subscriptions for the same venue are ignored.
288    pub fn subscribe_venue_instruments(engine: &Rc<RefCell<Self>>, venue: Venue) {
289        if !engine.borrow_mut().instrument_venues.insert(venue) {
290            return;
291        }
292
293        let weak = WeakCell::from(Rc::downgrade(engine));
294        let pattern = switchboard::get_instruments_pattern(venue);
295
296        let handler = TypedHandler::from(move |instrument: &InstrumentAny| {
297            if let Some(rc) = weak.upgrade() {
298                let venue = instrument.id().venue;
299                let mut engine = rc.borrow_mut();
300                let routed_client = engine.routing_map.get(&venue).copied();
301                for adapter in engine.clients.values_mut() {
302                    if adapter.venue == venue || Some(adapter.client_id) == routed_client {
303                        adapter.on_instrument(instrument.clone());
304                    }
305                }
306            }
307        });
308
309        msgbus::subscribe_instruments(pattern, handler, None);
310        log::info!("Subscribed to instrument updates for venue {venue}");
311    }
312
313    /// Subscribes to instrument closes for a venue via the message bus.
314    ///
315    /// A `ContractExpired` close for a binary option settles every open position in that
316    /// instrument at the close price, without an order or fill. The first close applied is
317    /// authoritative. After settlement, fills and fill voids for the instrument still update
318    /// their orders but no longer change positions. Repeated subscriptions for the same venue are
319    /// ignored.
320    pub fn subscribe_venue_instrument_closes(engine: &Rc<RefCell<Self>>, venue: Venue) {
321        if !engine.borrow_mut().instrument_close_venues.insert(venue) {
322            return;
323        }
324
325        let weak = WeakCell::from(Rc::downgrade(engine));
326        let pattern: MStr<Pattern> = format!("data.close.{venue}.*").into();
327
328        let handler = ShareableMessageHandler::from_typed(move |close: &InstrumentClose| {
329            if let Some(rc) = weak.upgrade() {
330                rc.borrow().settle_instrument_close(close);
331            }
332        });
333
334        msgbus::subscribe_instrument_close(pattern, handler, Some(10));
335        log::info!("Subscribed to instrument closes for venue {venue}");
336    }
337
338    #[must_use]
339    /// Returns the position ID count for the specified strategy.
340    pub fn position_id_count(&self, strategy_id: StrategyId) -> usize {
341        self.pos_id_generator.count(strategy_id)
342    }
343
344    #[must_use]
345    /// Returns a reference to the cache.
346    pub fn cache(&self) -> &Rc<RefCell<Cache>> {
347        &self.cache
348    }
349
350    #[must_use]
351    /// Returns a reference to the configuration.
352    pub const fn config(&self) -> &ExecutionEngineConfig {
353        &self.config
354    }
355
356    /// Sets the cache snapshot anchorer.
357    ///
358    /// The system event-store integration installs this while a run is open. Passing
359    /// `None` disables anchor recording for later cache snapshots.
360    pub fn set_snapshot_anchorer(&mut self, anchorer: Option<SnapshotAnchorer>) {
361        self.snapshot_anchorer = anchorer;
362    }
363
364    #[must_use]
365    /// Checks the integrity of cached execution data.
366    pub fn check_integrity(&self) -> bool {
367        self.cache.borrow_mut().check_integrity()
368    }
369
370    #[must_use]
371    /// Returns true if all registered execution clients are connected.
372    pub fn check_connected(&self) -> bool {
373        self.clients.values().all(|c| c.is_connected())
374    }
375
376    #[must_use]
377    /// Returns true if all registered execution clients are disconnected.
378    pub fn check_disconnected(&self) -> bool {
379        self.clients.values().all(|c| !c.is_connected())
380    }
381
382    /// Returns connection status for each registered client.
383    #[must_use]
384    pub fn client_connection_status(&self) -> Vec<(ClientId, bool)> {
385        self.clients
386            .values()
387            .map(|c| (c.client_id(), c.is_connected()))
388            .collect()
389    }
390
391    #[must_use]
392    /// Checks for residual positions and orders in the cache.
393    pub fn check_residuals(&self) -> bool {
394        self.cache.borrow().check_residuals()
395    }
396
397    #[must_use]
398    /// Returns the set of instruments that have external order claims.
399    pub fn get_external_order_claims_instruments(&self) -> HashSet<InstrumentId> {
400        self.cache
401            .borrow()
402            .external_order_claim_instrument_ids(None)
403            .into_iter()
404            .collect()
405    }
406
407    #[must_use]
408    /// Returns the configured external client IDs.
409    pub fn get_external_client_ids(&self) -> HashSet<ClientId> {
410        self.external_clients.clone()
411    }
412
413    #[must_use]
414    /// Returns any external order claim for the given instrument ID.
415    pub fn get_external_order_claim(&self, instrument_id: &InstrumentId) -> Option<StrategyId> {
416        self.cache.borrow().external_order_claim(instrument_id)
417    }
418
419    /// Registers a new execution client without assigning venue or default routing.
420    ///
421    /// Callers configure venue and fallback routing separately with
422    /// [`Self::register_venue_routing`] and [`Self::set_default_client`].
423    ///
424    /// # Errors
425    ///
426    /// Returns an error if a client with the same ID is already registered.
427    pub fn register_client(&mut self, client: Box<dyn ExecutionClient>) -> anyhow::Result<()> {
428        let client_id = client.client_id();
429
430        if self.clients.contains_key(&client_id) {
431            anyhow::bail!("Client already registered with ID {client_id}");
432        }
433
434        let adapter = ExecutionClientAdapter::new(client);
435        self.cache
436            .borrow_mut()
437            .add_client_account(client_id, adapter.account_id);
438
439        log::debug!("Registered client {client_id}");
440        self.clients.insert(client_id, adapter);
441        Ok(())
442    }
443
444    /// Registers a default execution client for fallback routing.
445    pub fn register_default_client(&mut self, client: Box<dyn ExecutionClient>) {
446        let client_id = client.client_id();
447        let adapter = ExecutionClientAdapter::new(client);
448        {
449            let mut cache = self.cache.borrow_mut();
450            cache.add_client_account(client_id, adapter.account_id);
451            cache.set_default_client(client_id);
452        }
453
454        self.clients.insert(client_id, adapter);
455        self.default_client_id = Some(client_id);
456        log::debug!("Registered default client {client_id}");
457    }
458
459    /// Marks an already-registered client as the default for fallback routing.
460    ///
461    /// # Errors
462    ///
463    /// Returns an error if no client is registered with the given ID, or a default
464    /// client has already been set.
465    pub fn set_default_client(&mut self, client_id: ClientId) -> anyhow::Result<()> {
466        if self.default_client_id.is_some() {
467            anyhow::bail!("default client already registered");
468        }
469
470        if !self.clients.contains_key(&client_id) {
471            anyhow::bail!("No client registered with ID {client_id}");
472        }
473
474        self.cache.borrow_mut().set_default_client(client_id);
475        self.default_client_id = Some(client_id);
476        log::debug!("Set client {client_id} as default");
477        Ok(())
478    }
479
480    #[must_use]
481    /// Returns a reference to the execution client registered with the given ID.
482    pub fn get_client(&self, client_id: &ClientId) -> Option<&dyn ExecutionClient> {
483        self.clients.get(client_id).map(|a| a.client.as_ref())
484    }
485
486    #[must_use]
487    /// Returns a mutable reference to the execution client adapter registered with the given ID.
488    pub fn get_client_adapter_mut(
489        &mut self,
490        client_id: &ClientId,
491    ) -> Option<&mut ExecutionClientAdapter> {
492        self.clients.get_mut(client_id)
493    }
494
495    /// Generates mass status for the given client.
496    ///
497    /// # Errors
498    ///
499    /// Returns an error if the client is not found or mass status generation fails.
500    pub async fn generate_mass_status(
501        &mut self,
502        client_id: &ClientId,
503        lookback_mins: Option<u64>,
504    ) -> anyhow::Result<Option<ExecutionMassStatus>> {
505        if let Some(client) = self.get_client_adapter_mut(client_id) {
506            client.generate_mass_status(lookback_mins).await
507        } else {
508            anyhow::bail!("Client {client_id} not found")
509        }
510    }
511
512    /// Registers an external order with the execution client for tracking.
513    ///
514    /// This is called after reconciliation creates an external order, allowing the
515    /// execution client to track it for subsequent events (e.g., cancellations).
516    pub fn register_external_order(
517        &self,
518        client_order_id: ClientOrderId,
519        venue_order_id: VenueOrderId,
520        instrument_id: InstrumentId,
521        strategy_id: StrategyId,
522        ts_init: UnixNanos,
523    ) {
524        let venue = instrument_id.venue;
525        // Prefer the cached origin over venue routing so tracking lands on the
526        // client whose stream materialized the order.
527        let client_id = self
528            .cache
529            .borrow()
530            .client_id(&client_order_id)
531            .copied()
532            .or_else(|| self.routing_map.get(&venue).copied())
533            .or(self.default_client_id);
534
535        if let Some(client_id) = client_id
536            && let Some(client) = self.clients.get(&client_id)
537        {
538            client.register_external_order(
539                client_order_id,
540                venue_order_id,
541                instrument_id,
542                strategy_id,
543                ts_init,
544            );
545        }
546    }
547
548    #[must_use]
549    /// Returns all registered execution client IDs.
550    pub fn client_ids(&self) -> Vec<ClientId> {
551        self.clients.keys().copied().collect()
552    }
553
554    #[must_use]
555    /// Returns mutable access to all registered execution clients.
556    pub fn get_clients_mut(&mut self) -> Vec<&mut ExecutionClientAdapter> {
557        self.clients.values_mut().collect()
558    }
559
560    /// Returns all registered execution clients.
561    #[must_use]
562    pub fn get_all_clients(&self) -> Vec<&dyn ExecutionClient> {
563        self.clients.values().map(|a| a.client.as_ref()).collect()
564    }
565
566    #[must_use]
567    /// Returns execution clients that would handle the given orders.
568    ///
569    /// This method first attempts to resolve each order's originating client from the cache,
570    /// then falls back to venue routing for any orders without a cached client.
571    pub fn get_clients_for_orders(&self, orders: &[OrderAny]) -> Vec<&dyn ExecutionClient> {
572        let mut client_ids: IndexSet<ClientId> = IndexSet::new();
573        let mut venues: IndexSet<Venue> = IndexSet::new();
574
575        // Collect client IDs from cache and venues for fallback
576        for order in orders {
577            venues.insert(order.instrument_id().venue);
578            if let Some(client_id) = self.cache.borrow().client_id(&order.client_order_id()) {
579                client_ids.insert(*client_id);
580            }
581        }
582
583        let mut clients: Vec<&dyn ExecutionClient> = Vec::new();
584
585        // Add clients for cached client IDs (orders go back to originating client)
586        for client_id in &client_ids {
587            if let Some(adapter) = self.clients.get(client_id)
588                && !clients.iter().any(|c| c.client_id() == adapter.client_id)
589            {
590                clients.push(adapter.client.as_ref());
591            }
592        }
593
594        // Add clients for venue routing (for orders not in cache)
595        for venue in &venues {
596            let resolved_id = self
597                .routing_map
598                .get(venue)
599                .copied()
600                .or(self.default_client_id);
601
602            if let Some(adapter) = resolved_id.and_then(|id| self.clients.get(&id))
603                && !clients.iter().any(|c| c.client_id() == adapter.client_id)
604            {
605                clients.push(adapter.client.as_ref());
606            }
607        }
608
609        clients
610    }
611
612    /// Sets routing for a specific venue to a given client ID.
613    ///
614    /// # Errors
615    ///
616    /// Returns an error if the client ID is not registered or the venue already
617    /// routes to a different client.
618    pub fn register_venue_routing(
619        &mut self,
620        client_id: ClientId,
621        venue: Venue,
622    ) -> anyhow::Result<()> {
623        if !self.clients.contains_key(&client_id) {
624            anyhow::bail!("No client registered with ID {client_id}");
625        }
626
627        if let Some(existing_client_id) = self.routing_map.get(&venue)
628            && *existing_client_id != client_id
629        {
630            anyhow::bail!(
631                "Venue {venue} already routed to {existing_client_id}, \
632                 cannot re-route to {client_id}"
633            );
634        }
635
636        self.cache.borrow_mut().add_client_route(client_id, venue);
637        self.routing_map.insert(venue, client_id);
638        log::info!("Set client {client_id} routing for {venue}");
639        Ok(())
640    }
641
642    /// Registers the OMS (Order Management System) type for a strategy.
643    ///
644    /// If an OMS type is already registered for this strategy, it will be overridden.
645    pub fn register_oms_type(&mut self, strategy_id: StrategyId, oms_type: OmsType) {
646        self.oms_overrides.insert(strategy_id, oms_type);
647        log::info!("Registered OMS::{oms_type:?} for {strategy_id}");
648    }
649
650    /// Registers external order claims for a strategy.
651    ///
652    /// Venue-sourced external orders, fills, and materialized reconciliation activity for matching
653    /// instruments will be associated with the strategy.
654    ///
655    /// This operation is atomic: either all instruments are registered or none are.
656    ///
657    /// # Errors
658    ///
659    /// Returns an error if any instrument already has a registered claim.
660    pub fn register_external_order_claims(
661        &mut self,
662        strategy_id: StrategyId,
663        instrument_ids: &HashSet<InstrumentId>,
664    ) -> anyhow::Result<()> {
665        let instrument_ids: Vec<_> = instrument_ids.iter().copied().collect();
666        self.cache
667            .borrow_mut()
668            .register_external_order_claims(strategy_id, &instrument_ids)?;
669
670        if !instrument_ids.is_empty() {
671            log::info!("Registered external order claims for {strategy_id}: {instrument_ids:?}");
672        }
673
674        Ok(())
675    }
676
677    /// Deregisters all external order claims owned by `strategy_id`.
678    ///
679    /// # Panics
680    ///
681    /// Panics if the shared cache is already borrowed.
682    pub fn deregister_external_order_claims(&mut self, strategy_id: StrategyId) {
683        self.cache
684            .borrow_mut()
685            .set_external_order_claims(strategy_id, &[])
686            .expect("clearing external order claims cannot fail");
687    }
688
689    /// # Errors
690    ///
691    /// Returns an error if no client is registered with the given ID.
692    pub fn deregister_client(&mut self, client_id: ClientId) -> anyhow::Result<()> {
693        if self.clients.shift_remove(&client_id).is_some() {
694            {
695                let mut cache = self.cache.borrow_mut();
696                cache.remove_client_account(&client_id);
697                cache.remove_client_routes(&client_id);
698            }
699
700            if self.default_client_id == Some(client_id) {
701                self.default_client_id = None;
702            }
703
704            // Remove from routing map if present
705            self.routing_map
706                .retain(|_, mapped_id| mapped_id != &client_id);
707            log::info!("Deregistered client {client_id}");
708            Ok(())
709        } else {
710            anyhow::bail!("No client registered with ID {client_id}")
711        }
712    }
713
714    /// Connects all registered execution clients concurrently.
715    ///
716    /// Successful clients remain connected if another client fails.
717    /// Logs identify failed clients without provider error text, which can contain credentials.
718    ///
719    /// # Errors
720    ///
721    /// Returns an error if any client fails to connect, listing failed client IDs without provider
722    /// error text.
723    pub async fn connect(&mut self) -> anyhow::Result<()> {
724        let futures: Vec<_> = self
725            .get_clients_mut()
726            .into_iter()
727            .map(|client| async move {
728                let client_id = client.client_id;
729                (client_id, client.connect().await)
730            })
731            .collect();
732
733        let results = join_all(futures).await;
734        let mut failed_clients = Vec::new();
735
736        for (client_id, result) in results {
737            if result.is_err() {
738                log::error!("Failed to connect execution client {client_id}: connection failed");
739                failed_clients.push(client_id.to_string());
740            }
741        }
742
743        if failed_clients.is_empty() {
744            Ok(())
745        } else {
746            anyhow::bail!(
747                "Failed to connect execution clients: {}",
748                failed_clients.join(", ")
749            )
750        }
751    }
752
753    /// Disconnects all registered execution clients concurrently.
754    ///
755    /// # Errors
756    ///
757    /// Returns an error if any client fails to disconnect.
758    pub async fn disconnect(&mut self) -> anyhow::Result<()> {
759        let futures: Vec<_> = self
760            .get_clients_mut()
761            .into_iter()
762            .map(|client| async move {
763                let client_id = client.client_id;
764                (client_id, client.disconnect().await)
765            })
766            .collect();
767
768        let results = join_all(futures).await;
769        let failed_clients: Vec<_> = results
770            .into_iter()
771            .filter_map(|(client_id, result)| result.err().map(|_| client_id.to_string()))
772            .collect();
773
774        if failed_clients.is_empty() {
775            Ok(())
776        } else {
777            anyhow::bail!(
778                "Failed to disconnect execution clients: {}",
779                failed_clients.join(", ")
780            )
781        }
782    }
783
784    /// Sets the `manage_own_order_books` configuration option.
785    pub fn set_manage_own_order_books(&mut self, value: bool) {
786        self.config.manage_own_order_books = value;
787    }
788
789    /// Starts the position snapshot timer if configured.
790    #[expect(
791        clippy::missing_panics_doc,
792        reason = "timer registration is not expected to fail"
793    )]
794    pub fn start_snapshot_timer(&mut self) {
795        if let Some(interval_secs) = self
796            .config
797            .snapshot_positions_interval_secs
798            .filter(|&secs| secs > 0.0)
799            && !self
800                .clock
801                .borrow()
802                .timer_names()
803                .contains(&TIMER_SNAPSHOT_POSITIONS)
804        {
805            let interval_ns = match secs_to_nanos(interval_secs) {
806                Ok(ns) => ns,
807                Err(e) => {
808                    log::error!("Cannot start position snapshots timer: {e}");
809                    return;
810                }
811            };
812            let clock = self.clock.clone();
813            let cache = self.cache.clone();
814            let debug = self.config.debug;
815
816            let callback_fn: Rc<dyn Fn(TimeEvent)> = Rc::new(move |_event| {
817                Self::snapshot_open_positions(&clock, &cache, debug);
818            });
819            let callback = TimeEventCallback::from(callback_fn);
820
821            log::info!("Starting position snapshots timer at {interval_secs} second intervals");
822            self.clock
823                .borrow_mut()
824                .set_timer_ns(
825                    TIMER_SNAPSHOT_POSITIONS,
826                    DurationNanos::new(interval_ns),
827                    None,
828                    None,
829                    Some(callback),
830                    None,
831                    None,
832                )
833                .expect("Failed to set position snapshots timer");
834        }
835    }
836
837    /// Stops the position snapshot timer if running.
838    pub fn stop_snapshot_timer(&mut self) {
839        let timer_registered = self
840            .clock
841            .borrow()
842            .timer_names()
843            .contains(&TIMER_SNAPSHOT_POSITIONS);
844
845        if timer_registered {
846            log::info!("Canceling position snapshots timer");
847            self.clock
848                .borrow_mut()
849                .cancel_timer(TIMER_SNAPSHOT_POSITIONS);
850        }
851    }
852
853    /// Starts the purge timers if configured.
854    pub fn start_purge_timers(&mut self) {
855        self.start_purge_timer(
856            TIMER_PURGE_CLOSED_ORDERS,
857            "purge_closed_orders_interval_mins",
858            "purge closed orders",
859            self.config.purge_closed_orders_interval_mins,
860            self.config.purge_closed_orders_buffer_mins,
861            Cache::purge_closed_orders,
862        );
863        self.start_purge_timer(
864            TIMER_PURGE_CLOSED_POSITIONS,
865            "purge_closed_positions_interval_mins",
866            "purge closed positions",
867            self.config.purge_closed_positions_interval_mins,
868            self.config.purge_closed_positions_buffer_mins,
869            Cache::purge_closed_positions,
870        );
871        self.start_purge_timer(
872            TIMER_PURGE_ACCOUNT_EVENTS,
873            "purge_account_events_interval_mins",
874            "purge account events",
875            self.config.purge_account_events_interval_mins,
876            self.config.purge_account_events_lookback_mins,
877            Cache::purge_account_events,
878        );
879    }
880
881    fn start_purge_timer(
882        &self,
883        name: &'static str,
884        field: &str,
885        description: &str,
886        interval_mins: Option<u32>,
887        buffer_mins: Option<u32>,
888        purge: fn(&mut Cache, UnixNanos, u64, bool) -> anyhow::Result<()>,
889    ) {
890        let Some(interval_mins) = interval_mins.filter(|&mins| mins > 0) else {
891            return;
892        };
893
894        if self.clock.borrow().timer_names().contains(&name) {
895            return;
896        }
897
898        let Ok(interval_ns) = DurationNanos::try_from_mins(u64::from(interval_mins)) else {
899            log::error!(
900                "Invalid {field} {interval_mins}: minutes to nanoseconds conversion overflow"
901            );
902            return;
903        };
904
905        let buffer_secs = mins_to_secs(u64::from(buffer_mins.unwrap_or(0)));
906        let purge_from_database = self.config.purge_from_database;
907        let cache = self.cache.clone();
908        let clock = self.clock.clone();
909        let callback_fn: Rc<dyn Fn(TimeEvent)> = Rc::new(move |_event| {
910            let ts_now = clock.borrow().timestamp_ns();
911
912            if let Err(e) = purge(
913                &mut cache.borrow_mut(),
914                ts_now,
915                buffer_secs,
916                purge_from_database,
917            ) {
918                log::error!("Failed to purge cached state for {name}: {e}");
919            }
920        });
921
922        let callback = TimeEventCallback::from(callback_fn);
923        log::info!("Starting {description} timer at {interval_mins} minute intervals");
924
925        if let Err(e) = self.clock.borrow_mut().set_timer_ns(
926            name,
927            interval_ns,
928            None,
929            None,
930            Some(callback),
931            None,
932            None,
933        ) {
934            log::error!("Failed to set {name} timer: {e}");
935        }
936    }
937
938    /// Stops the purge timers if running.
939    pub fn stop_purge_timers(&mut self) {
940        let timer_names: Vec<String> = self
941            .clock
942            .borrow()
943            .timer_names()
944            .into_iter()
945            .map(String::from)
946            .collect();
947
948        if timer_names.iter().any(|n| n == TIMER_PURGE_CLOSED_ORDERS) {
949            log::info!("Canceling purge closed orders timer");
950            self.clock
951                .borrow_mut()
952                .cancel_timer(TIMER_PURGE_CLOSED_ORDERS);
953        }
954
955        if timer_names
956            .iter()
957            .any(|n| n == TIMER_PURGE_CLOSED_POSITIONS)
958        {
959            log::info!("Canceling purge closed positions timer");
960            self.clock
961                .borrow_mut()
962                .cancel_timer(TIMER_PURGE_CLOSED_POSITIONS);
963        }
964
965        if timer_names.iter().any(|n| n == TIMER_PURGE_ACCOUNT_EVENTS) {
966            log::info!("Canceling purge account events timer");
967            self.clock
968                .borrow_mut()
969                .cancel_timer(TIMER_PURGE_ACCOUNT_EVENTS);
970        }
971    }
972
973    /// Creates snapshots of all open positions.
974    pub fn snapshot_open_position_states(&self) {
975        Self::snapshot_open_positions(&self.clock, &self.cache, self.config.debug);
976    }
977
978    fn snapshot_open_positions(
979        clock: &Rc<RefCell<dyn Clock>>,
980        cache: &Rc<RefCell<Cache>>,
981        debug: bool,
982    ) {
983        let positions: Vec<Position> = cache
984            .borrow()
985            .positions_open(None, None, None, None, None)
986            .into_iter()
987            .map(|p| p.cloned())
988            .collect();
989
990        for position in positions {
991            Self::publish_position_state_snapshot(clock, cache, debug, &position, true);
992        }
993    }
994
995    #[expect(clippy::await_holding_refcell_ref)]
996    /// Loads persistent state into cache and rebuilds indices.
997    ///
998    /// # Errors
999    ///
1000    /// Returns an error if any cache operation fails.
1001    pub async fn load_cache(&mut self) -> anyhow::Result<()> {
1002        let ts = SystemTime::now(); // dst-ok: init-time log timing, not on DST state path
1003
1004        {
1005            let mut cache = self.cache.borrow_mut();
1006            cache.clear_index();
1007            cache.cache_general()?;
1008        }
1009
1010        self.cache.borrow_mut().cache_all().await?;
1011
1012        // Snapshot before iterating: `get_or_init_own_order_book` re-enters `self.cache.borrow_mut()`.
1013        let own_book_entries: Vec<(InstrumentId, OwnBookOrder)> = {
1014            let mut cache = self.cache.borrow_mut();
1015            cache.build_index();
1016            let _ = cache.check_integrity();
1017
1018            if self.config.manage_own_order_books {
1019                cache
1020                    .orders(None, None, None, None, None)
1021                    .into_iter()
1022                    .filter(|o| !o.is_closed() && should_handle_own_book_order(o))
1023                    .map(|o| (o.instrument_id(), o.to_own_book_order()))
1024                    .collect()
1025            } else {
1026                Vec::new()
1027            }
1028        };
1029
1030        for (instrument_id, own_order) in own_book_entries {
1031            let mut own_book = self.get_or_init_own_order_book(&instrument_id);
1032            own_book.add(own_order);
1033        }
1034
1035        self.set_position_id_counts();
1036
1037        log::info!(
1038            "Loaded cache in {}ms",
1039            SystemTime::now() // dst-ok: init-time log timing, not on DST state path
1040                .duration_since(ts)
1041                .map_err(|e| anyhow::anyhow!("Failed to calculate duration: {e}"))?
1042                .as_millis()
1043        );
1044
1045        Ok(())
1046    }
1047
1048    /// Flushes the cache database, permanently removing the data the backing owns.
1049    ///
1050    /// # Errors
1051    ///
1052    /// Returns an error if flushing the database fails.
1053    pub fn flush_db(&self) -> anyhow::Result<()> {
1054        self.cache.borrow_mut().flush_db()
1055    }
1056
1057    /// Reconciles an execution report.
1058    pub fn reconcile_execution_report(&mut self, report: &ExecutionReport) {
1059        if !matches!(report, ExecutionReport::MassStatus(_)) {
1060            self.report_count += 1;
1061        }
1062
1063        match report {
1064            ExecutionReport::Order(order_report) => {
1065                self.reconcile_order_status_report(order_report);
1066            }
1067            ExecutionReport::Fill(fill_report) => {
1068                self.reconcile_fill_report(fill_report);
1069            }
1070            ExecutionReport::OrderWithFills(order_report, fills) => {
1071                self.reconcile_order_with_fills(order_report, fills);
1072            }
1073            ExecutionReport::Position(position_report) => {
1074                self.reconcile_position_report(position_report);
1075            }
1076            ExecutionReport::MassStatus(mass_status) => {
1077                self.reconcile_execution_mass_status(mass_status);
1078            }
1079        }
1080    }
1081
1082    /// Reconciles an order status report received at runtime.
1083    ///
1084    /// Handles order status transitions by generating appropriate events when the venue
1085    /// reports a different status than our local state. Supports all order states including
1086    /// fills with inferred fill generation when instruments are available. Clients requiring
1087    /// authoritative fills accept submitted orders but defer fill-dependent status transitions when
1088    /// the report has missing executions.
1089    ///
1090    /// When the order is not found in cache, creates an external order from the report.
1091    /// Orders requiring authoritative fills are created and accepted while their fills and dependent
1092    /// status transitions remain pending. This handles exchange-generated orders (liquidation, ADL,
1093    /// settlement) that were not submitted locally.
1094    pub fn reconcile_order_status_report(&mut self, report: &OrderStatusReport) {
1095        self.handle_order_status_report(report, false);
1096    }
1097
1098    fn handle_order_status_report(&mut self, report: &OrderStatusReport, is_snapshot: bool) {
1099        msgbus::publish_any(
1100            MessagingSwitchboard::reconciliation_raw_order_status_report_topic(),
1101            report,
1102        );
1103
1104        let cache = self.cache.borrow();
1105
1106        let order = report
1107            .client_order_id
1108            .and_then(|id| cache.order(&id).map(|o| o.clone()))
1109            .or_else(|| {
1110                cache
1111                    .client_order_id(&report.venue_order_id)
1112                    .and_then(|cid| cache.order(cid).map(|o| o.clone()))
1113            });
1114
1115        let instrument = cache.instrument(&report.instrument_id).cloned();
1116
1117        drop(cache);
1118
1119        if let Some(order) = order {
1120            self.reconcile_cached_order_status(&order, report, instrument.as_ref(), is_snapshot);
1121        } else if instrument.is_some() && self.order_report_has_missing_fills(report, None) {
1122            let _ = self.accept_external_order_from_status(report);
1123        } else {
1124            self.create_external_order(report, instrument.as_ref());
1125        }
1126    }
1127
1128    fn reconcile_cached_order_status(
1129        &mut self,
1130        order: &OrderAny,
1131        report: &OrderStatusReport,
1132        instrument: Option<&InstrumentAny>,
1133        is_snapshot: bool,
1134    ) {
1135        if self.order_report_has_missing_fills(report, Some(order)) {
1136            if order.status() == OrderStatus::Submitted {
1137                let ts_now = self.clock.borrow().timestamp_ns();
1138                for event in generate_reconciliation_order_pre_fill_events(order, report, ts_now) {
1139                    self.handle_event(&event);
1140                }
1141            }
1142
1143            log::debug!(
1144                "Deferring order status for {}: awaiting authoritative fills",
1145                report.venue_order_id,
1146            );
1147            return;
1148        }
1149
1150        let ts_now = self.clock.borrow().timestamp_ns();
1151        let events = if is_snapshot {
1152            generate_reconciliation_order_snapshot_events(order, report, instrument, ts_now)
1153        } else {
1154            generate_reconciliation_order_events(order, report, instrument, ts_now)
1155        };
1156
1157        for event in &events {
1158            self.handle_event(event);
1159        }
1160    }
1161
1162    fn order_report_has_missing_fills(
1163        &self,
1164        report: &OrderStatusReport,
1165        order: Option<&OrderAny>,
1166    ) -> bool {
1167        let filled_qty = order.map_or(
1168            Quantity::zero(report.filled_qty.precision),
1169            Order::filled_qty,
1170        );
1171
1172        if report.filled_qty <= filled_qty {
1173            return false;
1174        }
1175
1176        let client = order
1177            .and_then(|order| {
1178                self.cache
1179                    .borrow()
1180                    .client_id(&order.client_order_id())
1181                    .copied()
1182            })
1183            .and_then(|id| self.clients.get(&id));
1184
1185        client.map_or_else(
1186            || {
1187                self.clients.values().any(|client| {
1188                    client.account_id == report.account_id
1189                        && client.handles_order_venue(report.instrument_id.venue)
1190                        && client.requires_authoritative_fills()
1191                })
1192            },
1193            |client| client.requires_authoritative_fills(),
1194        )
1195    }
1196
1197    fn accept_external_order_from_status(
1198        &mut self,
1199        report: &OrderStatusReport,
1200    ) -> Option<OrderAny> {
1201        let order = self.materialize_external_order_from_status(report)?;
1202        let ts_now = self.clock.borrow().timestamp_ns();
1203
1204        let accepted = OrderAccepted::new(
1205            order.trader_id(),
1206            order.strategy_id(),
1207            order.instrument_id(),
1208            order.client_order_id(),
1209            report.venue_order_id,
1210            report.account_id,
1211            UUID4::new(),
1212            report.ts_accepted,
1213            ts_now,
1214            true,
1215        );
1216        self.handle_event(&OrderEventAny::Accepted(accepted));
1217        Some(
1218            self.cache
1219                .borrow()
1220                .order_owned(&order.client_order_id())
1221                .unwrap_or(order),
1222        )
1223    }
1224
1225    fn create_external_order(
1226        &mut self,
1227        report: &OrderStatusReport,
1228        instrument: Option<&InstrumentAny>,
1229    ) {
1230        let Some(instrument) = instrument else {
1231            log::warn!(
1232                "Cannot create external order for venue_order_id={}: instrument {} not found",
1233                report.venue_order_id,
1234                report.instrument_id
1235            );
1236            return;
1237        };
1238
1239        let Some(order) = self.materialize_external_order_from_status(report) else {
1240            return;
1241        };
1242
1243        let ts_now = self.clock.borrow().timestamp_ns();
1244        let events = generate_external_order_status_events(
1245            &order,
1246            report,
1247            &report.account_id,
1248            instrument,
1249            ts_now,
1250        );
1251
1252        for event in &events {
1253            self.handle_event(event);
1254        }
1255    }
1256
1257    /// Builds and registers an external order from an [`OrderStatusReport`] without
1258    /// emitting status events. Returns the registered order.
1259    fn materialize_external_order_from_status(
1260        &mut self,
1261        report: &OrderStatusReport,
1262    ) -> Option<OrderAny> {
1263        let strategy_id = self.resolve_external_strategy(&report.instrument_id);
1264        if self.should_filter_unclaimed_external_order(strategy_id) {
1265            self.filtered_unclaimed_external_order_count += 1;
1266
1267            if self.filtered_unclaimed_external_order_count == 1 {
1268                let external_order_id = report
1269                    .client_order_id
1270                    .map_or_else(|| report.venue_order_id.to_string(), |id| id.to_string());
1271                log::info!(
1272                    "Filtering unclaimed external orders; first filtered order {} ({}) for {}",
1273                    external_order_id,
1274                    report.venue_order_id,
1275                    report.instrument_id,
1276                );
1277            } else {
1278                let external_order_id = report
1279                    .client_order_id
1280                    .map_or_else(|| report.venue_order_id.to_string(), |id| id.to_string());
1281                log::debug!(
1282                    "Filtered unclaimed external order {} ({}) for {}",
1283                    external_order_id,
1284                    report.venue_order_id,
1285                    report.instrument_id,
1286                );
1287            }
1288
1289            return None;
1290        }
1291
1292        self.materialize_external_order_from_status_with_strategy(report, strategy_id)
1293    }
1294
1295    fn materialize_external_order_from_status_with_strategy(
1296        &self,
1297        report: &OrderStatusReport,
1298        strategy_id: StrategyId,
1299    ) -> Option<OrderAny> {
1300        let client_order_id = report
1301            .client_order_id
1302            .unwrap_or_else(|| ClientOrderId::from(report.venue_order_id.as_str()));
1303
1304        let trader_id = get_message_bus().borrow().trader_id;
1305        let ts_now = self.clock.borrow().timestamp_ns();
1306        let Some(order_side) = report.order_side else {
1307            log::error!(
1308                "Skipping external order {} ({}) for {}: order side is not specified",
1309                client_order_id,
1310                report.venue_order_id,
1311                report.instrument_id,
1312            );
1313            return None;
1314        };
1315
1316        let initialized = match OrderInitialized::new_checked(
1317            trader_id,
1318            strategy_id,
1319            report.instrument_id,
1320            client_order_id,
1321            order_side,
1322            report.order_type,
1323            report.quantity,
1324            report.time_in_force,
1325            report.post_only,
1326            report.reduce_only,
1327            false, // quote_quantity
1328            true,  // reconciliation
1329            UUID4::new(),
1330            ts_now,
1331            ts_now,
1332            report.price,
1333            report.activation_price,
1334            report.trigger_price,
1335            report.trigger_type,
1336            report.limit_offset,
1337            report.trailing_offset,
1338            report.trailing_offset_type,
1339            report.expire_time,
1340            report.display_qty,
1341            None, // emulation_trigger
1342            None, // trigger_instrument_id
1343            report.contingency_type,
1344            report.order_list_id,
1345            report.linked_order_ids.clone(),
1346            report.parent_order_id,
1347            None, // exec_algorithm_id
1348            None, // exec_algorithm_params
1349            None, // exec_spawn_id
1350            None, // tags
1351        ) {
1352            Ok(initialized) => initialized,
1353            Err(e) => {
1354                log::error!("Failed to create external order from report: {e}");
1355                return None;
1356            }
1357        };
1358
1359        self.materialize_external_order(
1360            initialized,
1361            report.venue_order_id,
1362            Some(report.order_status),
1363            self.source_client_id_for_account(report.account_id, &report.instrument_id),
1364        )
1365    }
1366
1367    /// Builds and registers an external order from a [`FillReport`] when no matching
1368    /// order exists in cache. The order is created with `OrderType::Market` and a
1369    /// quantity equal to the fill's `last_qty`, so the fill consumes the entire
1370    /// order on application.
1371    ///
1372    /// This handles venue-initiated fills (most commonly Hyperliquid liquidations)
1373    /// where the venue does not surface a user-level order on its order channel.
1374    fn materialize_external_order_from_fill(&mut self, report: &FillReport) -> Option<OrderAny> {
1375        let strategy_id = self.resolve_external_strategy(&report.instrument_id);
1376        if self.should_filter_unclaimed_external_order(strategy_id) {
1377            self.filtered_unclaimed_external_order_count += 1;
1378
1379            let external_order_id = report
1380                .client_order_id
1381                .map_or_else(|| report.venue_order_id.to_string(), |id| id.to_string());
1382
1383            if self.filtered_unclaimed_external_order_count == 1 {
1384                log::info!(
1385                    "Filtering unclaimed external orders; first filtered fill {} ({}) for {}",
1386                    external_order_id,
1387                    report.venue_order_id,
1388                    report.instrument_id,
1389                );
1390            } else {
1391                log::debug!(
1392                    "Filtered unclaimed external fill {} ({}) for {}",
1393                    external_order_id,
1394                    report.venue_order_id,
1395                    report.instrument_id,
1396                );
1397            }
1398
1399            return None;
1400        }
1401
1402        let client_order_id = report
1403            .client_order_id
1404            .unwrap_or_else(|| ClientOrderId::from(report.venue_order_id.as_str()));
1405
1406        let trader_id = get_message_bus().borrow().trader_id;
1407        let ts_now = self.clock.borrow().timestamp_ns();
1408
1409        let initialized = OrderInitialized::new(
1410            trader_id,
1411            strategy_id,
1412            report.instrument_id,
1413            client_order_id,
1414            report.order_side,
1415            OrderType::Market,
1416            report.last_qty,
1417            TimeInForce::Ioc,
1418            false, // post_only
1419            true,  // reduce_only: venue-initiated closes always reduce
1420            false, // quote_quantity
1421            true,  // reconciliation
1422            UUID4::new(),
1423            ts_now,
1424            ts_now,
1425            None, // price
1426            None, // activation_price
1427            None, // trigger_price
1428            None, // trigger_type
1429            None, // limit_offset
1430            None, // trailing_offset
1431            None,
1432            None, // expire_time
1433            None, // display_qty
1434            None, // emulation_trigger
1435            None, // trigger_instrument_id
1436            None,
1437            None, // order_list_id
1438            None, // linked_order_ids
1439            None, // parent_order_id
1440            None, // exec_algorithm_id
1441            None, // exec_algorithm_params
1442            None, // exec_spawn_id
1443            None, // tags
1444        );
1445
1446        self.materialize_external_order(
1447            initialized,
1448            report.venue_order_id,
1449            None,
1450            self.source_client_id_for_account(report.account_id, &report.instrument_id),
1451        )
1452    }
1453
1454    fn resolve_external_strategy(&self, instrument_id: &InstrumentId) -> StrategyId {
1455        self.cache
1456            .borrow()
1457            .external_order_claim(instrument_id)
1458            .unwrap_or_else(StrategyId::external)
1459    }
1460
1461    fn should_filter_unclaimed_external_order(&self, strategy_id: StrategyId) -> bool {
1462        self.config.filter_unclaimed_external_orders && strategy_id.is_external()
1463    }
1464
1465    /// Adds an external order to the cache and registers it for adapter routing.
1466    /// Returns the registered order on success.
1467    fn materialize_external_order(
1468        &self,
1469        initialized: OrderInitialized,
1470        venue_order_id: VenueOrderId,
1471        order_status: Option<OrderStatus>,
1472        source_client_id: Option<ClientId>,
1473    ) -> Option<OrderAny> {
1474        let client_order_id = initialized.client_order_id;
1475        let instrument_id = initialized.instrument_id;
1476        let strategy_id = initialized.strategy_id;
1477        let ts_init = initialized.ts_init;
1478        let initialized = OrderEventAny::Initialized(initialized);
1479
1480        let order = match OrderAny::from_events(vec![initialized.clone()]) {
1481            Ok(order) => order,
1482            Err(e) => {
1483                log::error!("Failed to create external order from report: {e}");
1484                return None;
1485            }
1486        };
1487
1488        {
1489            let mut cache = self.cache.borrow_mut();
1490            if let Err(e) = cache.add_venue_order_id(&client_order_id, &venue_order_id, false) {
1491                log::warn!("Failed to claim venue order ID for external order: {e}");
1492                return None;
1493            }
1494
1495            if let Err(e) = cache.add_order(order.clone(), None, source_client_id, false) {
1496                log::error!("Failed to add external order to cache: {e}");
1497                return None;
1498            }
1499        }
1500
1501        self.publish_order_event(&initialized);
1502
1503        match order_status {
1504            Some(status) => log::info!(
1505                "Created external order {client_order_id} ({venue_order_id}) for {instrument_id} [{status}]",
1506            ),
1507            None => log::info!(
1508                "Created external order {client_order_id} ({venue_order_id}) for {instrument_id}",
1509            ),
1510        }
1511
1512        self.register_external_order(
1513            client_order_id,
1514            venue_order_id,
1515            instrument_id,
1516            strategy_id,
1517            ts_init,
1518        );
1519
1520        Some(order)
1521    }
1522
1523    /// Resolves the execution client origin for a live-stream report by matching
1524    /// the report account against registered clients. A unique match stamps the
1525    /// materialized order's client origin; no match or an ambiguous match keeps
1526    /// the order origin-free.
1527    fn source_client_id_for_account(
1528        &self,
1529        account_id: AccountId,
1530        instrument_id: &InstrumentId,
1531    ) -> Option<ClientId> {
1532        let mut matches = self
1533            .clients
1534            .values()
1535            .filter(|adapter| {
1536                adapter.account_id == account_id && adapter.handles_order_venue(instrument_id.venue)
1537            })
1538            .map(|adapter| adapter.client_id);
1539
1540        let first = matches.next()?;
1541
1542        matches.next().is_none().then_some(first)
1543    }
1544
1545    /// Reconciles a fill report received at runtime.
1546    ///
1547    /// Finds the associated order, validates the fill, and generates an `OrderFilled` event
1548    /// if the fill is not a duplicate and won't cause an overfill. When `allow_overfills` is
1549    /// disabled and the execution client allows a reconciliation overfill, the engine raises
1550    /// the order quantity to the filled quantity plus this fill before applying it. An already
1551    /// filled order is not raised again. When the order is not in cache, an external order is
1552    /// bootstrapped from the fill so that venue-initiated closures (e.g. Hyperliquid
1553    /// liquidations) that arrive without a companion order status report still update the
1554    /// local position.
1555    ///
1556    /// Replayed fills update their orders only when a cached synthetic correction already covers
1557    /// them. Standalone reports check all strategies for the instrument and account.
1558    pub fn reconcile_fill_report(&mut self, report: &FillReport) {
1559        msgbus::publish_any(
1560            MessagingSwitchboard::reconciliation_raw_fill_report_topic(),
1561            report,
1562        );
1563
1564        if report.last_qty.is_zero() {
1565            log::warn!("Skipping zero-quantity fill report: {report}");
1566            return;
1567        }
1568
1569        let cache = self.cache.borrow();
1570
1571        let order = report
1572            .client_order_id
1573            .and_then(|id| cache.order(&id).map(|o| o.clone()))
1574            .or_else(|| {
1575                cache
1576                    .client_order_id(&report.venue_order_id)
1577                    .and_then(|cid| cache.order(cid).map(|o| o.clone()))
1578            });
1579
1580        let instrument = cache.instrument(&report.instrument_id).cloned();
1581
1582        drop(cache);
1583
1584        let Some(instrument) = instrument else {
1585            log::debug!(
1586                "Cannot reconcile fill report for venue_order_id={}: instrument {} not found",
1587                report.venue_order_id,
1588                report.instrument_id
1589            );
1590            return;
1591        };
1592
1593        let order = match order {
1594            Some(order) => order,
1595            None => {
1596                let Some(order) = self.materialize_external_order_from_fill(report) else {
1597                    return;
1598                };
1599                let ts_now = self.clock.borrow().timestamp_ns();
1600                let accepted = OrderAccepted::new(
1601                    order.trader_id(),
1602                    order.strategy_id(),
1603                    order.instrument_id(),
1604                    order.client_order_id(),
1605                    report.venue_order_id,
1606                    report.account_id,
1607                    UUID4::new(),
1608                    report.ts_event,
1609                    ts_now,
1610                    true, // reconciliation
1611                );
1612                self.handle_event(&OrderEventAny::Accepted(accepted));
1613                self.cache
1614                    .borrow()
1615                    .order(&order.client_order_id())
1616                    .map(|o| o.clone())
1617                    .unwrap_or(order)
1618            }
1619        };
1620
1621        let ts_now = self.clock.borrow().timestamp_ns();
1622        let order = self
1623            .raised_order_for_reconciliation_overfill(&order, report, ts_now)
1624            .unwrap_or(order);
1625
1626        if let Some(event) = reconcile_fill(
1627            &order,
1628            report,
1629            &instrument,
1630            ts_now,
1631            self.config.allow_overfills,
1632        ) {
1633            let apply_position =
1634                !fill_precedes_snapshot_reconciled_position(&self.cache.borrow(), report);
1635            self.handle_event_with_position_application(&event, apply_position);
1636        }
1637    }
1638
1639    fn raised_order_for_reconciliation_overfill(
1640        &mut self,
1641        order: &OrderAny,
1642        report: &FillReport,
1643        ts_now: UnixNanos,
1644    ) -> Option<OrderAny> {
1645        if self.config.allow_overfills
1646            || order.status() == OrderStatus::Filled
1647            || order.trade_ids().iter().any(|id| **id == report.trade_id)
1648        {
1649            return None;
1650        }
1651
1652        let raised_qty = order.filled_qty().checked_add(report.last_qty)?;
1653        if raised_qty <= order.quantity()
1654            || !self.client_allows_reconciliation_overfill(order, report)
1655        {
1656            return None;
1657        }
1658
1659        let updated = OrderUpdated::new(
1660            order.trader_id(),
1661            order.strategy_id(),
1662            order.instrument_id(),
1663            order.client_order_id(),
1664            raised_qty,
1665            UUID4::new(),
1666            report.ts_event,
1667            ts_now,
1668            true,
1669            order.venue_order_id(),
1670            order.account_id(),
1671            None,
1672            None,
1673            None,
1674            order.is_quote_quantity(),
1675        );
1676        self.handle_event(&OrderEventAny::Updated(updated));
1677        self.cache
1678            .borrow()
1679            .order(&order.client_order_id())
1680            .map(|order| order.clone())
1681    }
1682
1683    fn client_allows_reconciliation_overfill(&self, order: &OrderAny, report: &FillReport) -> bool {
1684        let client_id = self
1685            .cache
1686            .borrow()
1687            .client_id(&order.client_order_id())
1688            .copied()
1689            .or_else(|| self.routing_map.get(&order.instrument_id().venue).copied())
1690            .or(self.default_client_id);
1691        client_id
1692            .and_then(|client_id| self.clients.get(&client_id))
1693            .is_some_and(|client| client.allows_reconciliation_overfill(order, report))
1694    }
1695
1696    /// Reconciles a streamed [`OrderStatusReport`] paired with companion [`FillReport`]s
1697    /// for the same venue event.
1698    ///
1699    /// Real fills supplied by the adapter are applied first so their `trade_id` and
1700    /// `commission` are preserved; any residual quantity not covered by the fills is
1701    /// then synthesized as an inferred fill from the status report's `avg_px`, unless the client
1702    /// requires authoritative fills. In that case, residual quantity and dependent status transitions
1703    /// remain pending.
1704    /// Adapters use this to emit ADL / liquidation / settlement events without
1705    /// losing real fill metadata.
1706    ///
1707    /// A decrease in cumulative filled quantity voids retained fills only for
1708    /// [`OrderStatus::Voided`] reports. Authoritative snapshot corrections use
1709    /// [`Self::reconcile_execution_mass_status`].
1710    pub fn reconcile_order_with_fills(&mut self, report: &OrderStatusReport, fills: &[FillReport]) {
1711        self.handle_order_with_fills(report, fills, false);
1712    }
1713
1714    fn handle_order_with_fills(
1715        &mut self,
1716        report: &OrderStatusReport,
1717        fills: &[FillReport],
1718        is_snapshot: bool,
1719    ) {
1720        msgbus::publish_any(
1721            MessagingSwitchboard::reconciliation_raw_order_status_report_topic(),
1722            report,
1723        );
1724
1725        let fill_report_topic = MessagingSwitchboard::reconciliation_raw_fill_report_topic();
1726        for fill in fills {
1727            msgbus::publish_any(fill_report_topic, fill);
1728        }
1729
1730        let cache = self.cache.borrow();
1731        let order = report
1732            .client_order_id
1733            .and_then(|id| cache.order(&id).map(|o| o.clone()))
1734            .or_else(|| {
1735                cache
1736                    .client_order_id(&report.venue_order_id)
1737                    .and_then(|cid| cache.order(cid).map(|o| o.clone()))
1738            });
1739        let instrument = cache.instrument(&report.instrument_id).cloned();
1740        drop(cache);
1741
1742        let Some(instrument) = instrument else {
1743            log::debug!(
1744                "Cannot reconcile bundled report for venue_order_id={}: instrument {} not found",
1745                report.venue_order_id,
1746                report.instrument_id,
1747            );
1748
1749            if fills.is_empty()
1750                && let Some(order) = order
1751            {
1752                self.reconcile_cached_order_status(&order, report, None, is_snapshot);
1753            }
1754            return;
1755        };
1756
1757        // Bootstrap the external order with only OrderAccepted; defer fill events to
1758        // the per-fill loop so real fill metadata is preserved.
1759        let mut order = match order {
1760            Some(order) => {
1761                let ts_now = self.clock.borrow().timestamp_ns();
1762                let events = generate_reconciliation_order_pre_fill_events(&order, report, ts_now);
1763                for event in &events {
1764                    self.handle_event(event);
1765                }
1766                self.cache
1767                    .borrow()
1768                    .order(&order.client_order_id())
1769                    .map(|o| o.clone())
1770                    .unwrap_or(order)
1771            }
1772            None => {
1773                let Some(order) = self.accept_external_order_from_status(report) else {
1774                    return;
1775                };
1776
1777                order
1778            }
1779        };
1780
1781        let client_order_id = order.client_order_id();
1782
1783        for fill in fills {
1784            let ts_now = self.clock.borrow().timestamp_ns();
1785
1786            if let Some(event) = reconcile_fill(
1787                &order,
1788                fill,
1789                &instrument,
1790                ts_now,
1791                self.config.allow_overfills,
1792            ) {
1793                self.handle_event(&event);
1794            }
1795
1796            // Refresh order after fill to keep filled_qty accurate for the next iteration.
1797            if let Some(refreshed) = self
1798                .cache
1799                .borrow()
1800                .order(&client_order_id)
1801                .map(|o| o.clone())
1802            {
1803                order = refreshed;
1804            }
1805        }
1806
1807        self.reconcile_cached_order_status(&order, report, Some(&instrument), is_snapshot);
1808    }
1809
1810    /// Reconciles a position status report received at runtime.
1811    ///
1812    /// Compares the venue-reported position with cached positions and logs any discrepancies.
1813    /// Handles both hedging (with `venue_position_id`) and netting (without) modes.
1814    pub fn reconcile_position_report(&mut self, report: &PositionStatusReport) {
1815        msgbus::publish_any(
1816            MessagingSwitchboard::reconciliation_raw_position_status_report_topic(),
1817            report,
1818        );
1819
1820        let cache = self.cache.borrow();
1821
1822        let size_precision = cache
1823            .instrument(&report.instrument_id)
1824            .map(InstrumentAny::size_precision);
1825
1826        if report.venue_position_id.is_some() {
1827            self.reconcile_position_report_hedging(report, &cache);
1828        } else {
1829            self.reconcile_position_report_netting(report, &cache, size_precision);
1830        }
1831    }
1832
1833    fn reconcile_position_report_hedging(&self, report: &PositionStatusReport, cache: &Cache) {
1834        let venue_position_id = report.venue_position_id.as_ref().unwrap();
1835
1836        log::debug!(
1837            "Reconciling HEDGE position for {}, venue_position_id={}",
1838            report.instrument_id,
1839            venue_position_id
1840        );
1841
1842        let Some(position) = cache.position(venue_position_id) else {
1843            if report.signed_decimal_qty == Decimal::ZERO {
1844                return;
1845            }
1846
1847            log::error!("Cannot reconcile position: {venue_position_id} not found in cache");
1848            return;
1849        };
1850
1851        let cached_signed_qty = Self::position_signed_decimal_qty(&position);
1852        let venue_signed_qty = report.signed_decimal_qty;
1853
1854        if cached_signed_qty != venue_signed_qty {
1855            log::error!(
1856                "Position mismatch for {} {}: cached={}, venue={}",
1857                report.instrument_id,
1858                venue_position_id,
1859                cached_signed_qty,
1860                venue_signed_qty
1861            );
1862        }
1863    }
1864
1865    fn reconcile_position_report_netting(
1866        &self,
1867        report: &PositionStatusReport,
1868        cache: &Cache,
1869        size_precision: Option<u8>,
1870    ) {
1871        log::debug!("Reconciling NET position for {}", report.instrument_id);
1872
1873        let positions_open = Self::netting_positions_open_for_report(cache, report);
1874
1875        let position_refs = positions_open
1876            .iter()
1877            .map(|position| &**position)
1878            .collect::<Vec<_>>();
1879
1880        if let Some(message) =
1881            Self::netting_split_position_ownership_message(report, &position_refs)
1882        {
1883            log::warn!("{message}");
1884        }
1885
1886        // Sum up cached position quantities using domain types to avoid f64 precision loss
1887        let cached_signed_qty: Decimal = positions_open
1888            .iter()
1889            .map(|position| Self::position_signed_decimal_qty(position))
1890            .sum();
1891
1892        log::debug!(
1893            "Position report: venue_signed_qty={}, cached_signed_qty={}",
1894            report.signed_decimal_qty,
1895            cached_signed_qty
1896        );
1897
1898        let _ = check_position_reconciliation(report, cached_signed_qty, size_precision);
1899    }
1900
1901    fn netting_positions_open_for_report<'a>(
1902        cache: &'a Cache,
1903        report: &PositionStatusReport,
1904    ) -> Vec<PositionRef<'a>> {
1905        cache.positions_open(
1906            None,
1907            Some(&report.instrument_id),
1908            None,
1909            Some(&report.account_id),
1910            None,
1911        )
1912    }
1913
1914    fn netting_split_position_ownership_message(
1915        report: &PositionStatusReport,
1916        positions_open: &[&Position],
1917    ) -> Option<String> {
1918        let mut strategy_ids = positions_open
1919            .iter()
1920            .map(|position| position.strategy_id.to_string())
1921            .collect::<Vec<_>>();
1922        strategy_ids.sort();
1923        strategy_ids.dedup();
1924
1925        if strategy_ids.len() <= 1 {
1926            return None;
1927        }
1928
1929        let position_details = Self::position_details(positions_open.iter().copied());
1930
1931        Some(format!(
1932            "NETTING reconciliation found split ownership for account_id={}, instrument_id={}: \
1933             strategies=[{}], positions=[{}]",
1934            report.account_id,
1935            report.instrument_id,
1936            strategy_ids.join(", "),
1937            position_details
1938        ))
1939    }
1940
1941    /// Reconciles an execution mass status report.
1942    ///
1943    /// Processes all order reports, fill reports, and position reports contained
1944    /// in the mass status. Order reports are paired with their companion fills so
1945    /// real trade IDs and commissions are applied before any residual inferred fill.
1946    /// Filled-quantity decreases generate fill voids even when no companion fills are present.
1947    /// Order snapshots are skipped when cached fill activity is initialized at or after
1948    /// collection starts (`mass_status.ts_init`); companion trades still reconcile.
1949    pub fn reconcile_execution_mass_status(&mut self, mass_status: &ExecutionMassStatus) {
1950        self.report_count += 1;
1951
1952        log::info!(
1953            "Reconciling mass status for client={}, account={}, venue={}",
1954            mass_status.client_id,
1955            mass_status.account_id,
1956            mass_status.venue
1957        );
1958
1959        let order_reports = mass_status.order_reports();
1960        let fill_reports = mass_status.fill_reports();
1961        let mut paired_venue_ids = AHashSet::new();
1962
1963        for order_report in order_reports.values() {
1964            if self.is_order_snapshot_stale(order_report, mass_status.ts_init) {
1965                msgbus::publish_any(
1966                    MessagingSwitchboard::reconciliation_raw_order_status_report_topic(),
1967                    order_report,
1968                );
1969
1970                log::debug!(
1971                    "Skipping snapshot for {} after concurrent fill activity",
1972                    order_report.venue_order_id,
1973                );
1974                continue;
1975            }
1976
1977            if let Some(fills) = fill_reports.get(&order_report.venue_order_id)
1978                && !fills.is_empty()
1979            {
1980                self.handle_order_with_fills(order_report, fills, true);
1981                paired_venue_ids.insert(order_report.venue_order_id);
1982            } else {
1983                self.handle_order_status_report(order_report, true);
1984            }
1985        }
1986
1987        for fill_reports in fill_reports.values() {
1988            for fill_report in fill_reports {
1989                if paired_venue_ids.contains(&fill_report.venue_order_id) {
1990                    continue;
1991                }
1992
1993                self.reconcile_fill_report(fill_report);
1994            }
1995        }
1996
1997        for position_reports in mass_status.position_reports().values() {
1998            for position_report in position_reports {
1999                self.reconcile_position_report(position_report);
2000            }
2001        }
2002
2003        log::info!(
2004            "Mass status reconciliation complete: {} orders, {} fills, {} positions",
2005            mass_status.order_reports().len(),
2006            mass_status
2007                .fill_reports()
2008                .values()
2009                .map(Vec::len)
2010                .sum::<usize>(),
2011            mass_status
2012                .position_reports()
2013                .values()
2014                .map(Vec::len)
2015                .sum::<usize>()
2016        );
2017    }
2018
2019    fn is_order_snapshot_stale(&self, report: &OrderStatusReport, ts_snapshot: UnixNanos) -> bool {
2020        let cache = self.cache.borrow();
2021
2022        let order = report
2023            .client_order_id
2024            .and_then(|id| cache.order(&id))
2025            .or_else(|| {
2026                cache
2027                    .client_order_id(&report.venue_order_id)
2028                    .and_then(|id| cache.order(id))
2029            });
2030
2031        order.is_some_and(|order| {
2032            order.events().into_iter().any(|event| match event {
2033                OrderEventAny::Filled(fill) => fill.ts_init >= ts_snapshot,
2034                OrderEventAny::FillVoided(void) => void.ts_init >= ts_snapshot,
2035                _ => false,
2036            })
2037        })
2038    }
2039
2040    /// Executes a trading command by routing it to the appropriate execution client.
2041    pub fn execute(&self, command: TradingCommand) {
2042        self.execute_command(command);
2043    }
2044
2045    /// Processes an order event, updating internal state and routing as needed.
2046    ///
2047    /// # Replayed Fills
2048    ///
2049    /// A reconciliation fill updates its order but no position when a cached position for its
2050    /// instrument and account:
2051    /// - Has a synthetic reconciliation fill later than the execution's `ts_event`.
2052    /// - Does not hold the fill's trade.
2053    ///
2054    /// The venue position report behind that correction already includes the fill, so this stops
2055    /// a venue that replays executions after a restart from doubling the position.
2056    /// NETTING fills check all strategies; HEDGING fills check the routed position.
2057    /// Ordinary private fills and price restatements still apply to positions.
2058    pub fn process(&mut self, event: &OrderEventAny) {
2059        self.handle_event(event);
2060    }
2061
2062    /// Projects a reconciled fill onto its order without applying position or portfolio economics.
2063    pub fn project_reconciliation_fill(&mut self, fill: &OrderFilled) {
2064        self.handle_event_with_position_application(&OrderEventAny::Filled(fill.clone()), false);
2065    }
2066
2067    /// Returns a cached position ID for a reconciliation fill without changing routing state.
2068    ///
2069    /// Requires a cached order and resolves indexed orders, explicit HEDGING IDs, and NETTING
2070    /// routing. Returns `None` for HEDGING routing conflicts, missing positions, or unindexed
2071    /// HEDGING orders whose fill has no `position_id`.
2072    /// The destination can change before application.
2073    #[must_use]
2074    pub fn reconciliation_position_id(&self, fill: &OrderFilled) -> Option<PositionId> {
2075        let oms_type = self.determine_oms_type(fill);
2076        let indexed = self.cached_fill_position_id(fill, oms_type).ok()?;
2077        let cache = self.cache.borrow();
2078        let order = cache.order(&fill.client_order_id)?;
2079
2080        let position_id = match (indexed, oms_type) {
2081            (Some(id), _) => id,
2082            (None, OmsType::Hedging) => fill.position_id?,
2083            (None, _) => self.determine_netting_position_id(fill, Some(&order)),
2084        };
2085
2086        cache.position_ref(&position_id).map(|position| position.id)
2087    }
2088
2089    /// Starts the execution engine and all registered execution clients.
2090    pub fn start(&mut self) {
2091        for client in self.get_clients_mut() {
2092            if client.start().is_err() {
2093                log::error!("Failed to start execution client {}", client.client_id());
2094            }
2095        }
2096
2097        self.start_snapshot_timer();
2098        self.start_purge_timers();
2099
2100        log::info!("Started");
2101    }
2102
2103    /// Stops the execution engine and all registered execution clients.
2104    ///
2105    /// Adapters are expected to be idempotent on repeated `stop()` calls
2106    /// (e.g. via an internal `is_stopped` guard); the backtest teardown
2107    /// sequence calls `stop()` more than once per run.
2108    pub fn stop(&mut self) {
2109        self.stop_clients();
2110
2111        self.stop_snapshot_timer();
2112        self.stop_purge_timers();
2113
2114        log::info!("Stopped");
2115    }
2116
2117    /// Stops all registered execution clients without stopping the engine itself.
2118    pub fn stop_clients(&mut self) {
2119        for client in self.get_clients_mut() {
2120            if client.stop().is_err() {
2121                log::error!("Failed to stop execution client {}", client.client_id());
2122            }
2123        }
2124    }
2125
2126    /// Resets the execution engine and all registered execution clients to initial state.
2127    ///
2128    /// Cancels engine-owned timers (snapshot, purge) but leaves timers owned by
2129    /// other components on the shared clock untouched.
2130    pub fn reset(&mut self) {
2131        for client in self.get_clients_mut() {
2132            if client.reset().is_err() {
2133                log::error!("Failed to reset execution client {}", client.client_id());
2134            }
2135        }
2136
2137        self.cache.borrow_mut().reset();
2138        self.pos_id_generator.reset();
2139
2140        self.stop_snapshot_timer();
2141        self.stop_purge_timers();
2142
2143        self.command_count.set(0);
2144        self.event_count = 0;
2145        self.report_count = 0;
2146        self.filtered_unclaimed_external_order_count = 0;
2147        log::info!("Reset");
2148    }
2149
2150    /// Disposes of the execution engine, releasing resources from all clients and timers.
2151    ///
2152    /// Cancels engine-owned timers (snapshot, purge) but leaves timers owned by
2153    /// other components on the shared clock untouched.
2154    pub fn dispose(&mut self) {
2155        for client in self.get_clients_mut() {
2156            if client.dispose().is_err() {
2157                log::error!("Failed to dispose execution client {}", client.client_id());
2158            }
2159        }
2160
2161        self.stop_snapshot_timer();
2162        self.stop_purge_timers();
2163
2164        log::info!("Disposed");
2165    }
2166
2167    fn execute_command(&self, command: TradingCommand) {
2168        self.command_count.set(self.command_count.get() + 1);
2169
2170        if self.config.debug {
2171            log::debug!("{RECV}{CMD} {command}");
2172        }
2173
2174        match self.validate_submission(&command) {
2175            SubmissionValidationResult::Valid => {}
2176            SubmissionValidationResult::StaleOrder {
2177                client_order_id,
2178                status,
2179            } => {
2180                log::warn!(
2181                    "Skipping stale submit command for {client_order_id} in status {status}"
2182                );
2183                return;
2184            }
2185            SubmissionValidationResult::Dispatched { client_order_id } => {
2186                log::warn!(
2187                    "Skipping duplicate submit command for {client_order_id} already dispatched to an execution client"
2188                );
2189                return;
2190            }
2191            SubmissionValidationResult::Deny(reason) => {
2192                self.deny_submission(&command, &reason);
2193                return;
2194            }
2195        }
2196
2197        if let Some(cid) = command.client_id()
2198            && self.external_clients.contains(&cid)
2199        {
2200            let topic = format!("commands.trading.{cid}");
2201            msgbus::publish_any(topic.into(), &command);
2202
2203            // The external client now owns the submitted orders, exactly like a registered client
2204            match &command {
2205                TradingCommand::SubmitOrder(cmd) => {
2206                    self.cache
2207                        .borrow_mut()
2208                        .mark_orders_dispatched([cmd.client_order_id]);
2209                }
2210                TradingCommand::SubmitOrderList(cmd) => {
2211                    self.cache
2212                        .borrow_mut()
2213                        .mark_orders_dispatched(cmd.order_list.client_order_ids.iter().copied());
2214                }
2215                _ => {}
2216            }
2217
2218            if self.config.debug {
2219                log::debug!("Skipping execution command for external client {cid}: {command}");
2220            }
2221            return;
2222        }
2223
2224        let client = if let Some(adapter) = self.find_client_for_command(&command) {
2225            adapter.client.as_ref()
2226        } else {
2227            self.deny_unroutable_command(command);
2228
2229            return;
2230        };
2231
2232        match command {
2233            TradingCommand::SubmitOrder(cmd) => self.handle_submit_order(client, cmd),
2234            TradingCommand::SubmitOrderList(cmd) => self.handle_submit_order_list(client, cmd),
2235            TradingCommand::ModifyOrder(cmd) => self.handle_modify_order(client, cmd),
2236            TradingCommand::ModifyOrders(cmd) => self.handle_batch_modify_orders(client, cmd),
2237            TradingCommand::CancelOrder(cmd) => self.handle_cancel_order(client, cmd),
2238            TradingCommand::CancelOrders(cmd) => self.handle_batch_cancel_orders(client, cmd),
2239            TradingCommand::CancelAllOrders(cmd) => self.handle_cancel_all_orders(client, &cmd),
2240            TradingCommand::QueryOrder(cmd) => self.handle_query_order(client, cmd),
2241            TradingCommand::QueryAccount(cmd) => self.handle_query_account(client, cmd),
2242        }
2243    }
2244
2245    fn deny_unroutable_command(&self, command: TradingCommand) {
2246        let routing_context = Self::routing_context_for_command(&command);
2247
2248        log::error!(
2249            "No execution client found for command: client_id={:?}, {routing_context}, command={command}",
2250            command.client_id(),
2251        );
2252
2253        let reason = OrderDeniedReason::NoExecutionClient {
2254            client_id: command.client_id(),
2255            routing_context,
2256        }
2257        .to_string();
2258
2259        match command {
2260            TradingCommand::SubmitOrder(cmd) => {
2261                let order = self
2262                    .cache
2263                    .borrow()
2264                    .order(&cmd.client_order_id)
2265                    .map(|o| o.clone());
2266
2267                if let Some(order) = order {
2268                    self.deny_order(&order, &reason);
2269                }
2270            }
2271            TradingCommand::SubmitOrderList(cmd) => {
2272                let orders: Vec<OrderAny> = self
2273                    .cache
2274                    .borrow()
2275                    .orders_for_ids(&cmd.order_list.client_order_ids, &cmd);
2276
2277                for order in &orders {
2278                    self.deny_order(order, &reason);
2279                }
2280            }
2281            TradingCommand::ModifyOrder(cmd) => self.deny_modify_command(&cmd, &reason),
2282            TradingCommand::ModifyOrders(cmd) => {
2283                for modify in &cmd.modifies {
2284                    self.deny_modify_command(modify, &reason);
2285                }
2286            }
2287            TradingCommand::CancelOrder(cmd) => self.deny_cancel_command(&cmd, &reason),
2288            TradingCommand::CancelOrders(cmd) => {
2289                for cancel in &cmd.cancels {
2290                    self.deny_cancel_command(cancel, &reason);
2291                }
2292            }
2293            _ => {}
2294        }
2295    }
2296
2297    fn validate_submission(&self, command: &TradingCommand) -> SubmissionValidationResult {
2298        match command {
2299            TradingCommand::SubmitOrder(cmd) => {
2300                let client_order_id = cmd.client_order_id;
2301                let cache = self.cache.borrow();
2302
2303                if let Some(order) = cache.order(&client_order_id)
2304                    && !Self::has_submittable_status(&order)
2305                {
2306                    return SubmissionValidationResult::StaleOrder {
2307                        client_order_id,
2308                        status: order.status(),
2309                    };
2310                }
2311
2312                if self.is_dispatched(client_order_id) {
2313                    return SubmissionValidationResult::Dispatched { client_order_id };
2314                }
2315
2316                SubmissionValidationResult::Valid
2317            }
2318            TradingCommand::SubmitOrderList(cmd) => {
2319                let cache = self.cache.borrow();
2320                let client_order_ids = &cmd.order_list.client_order_ids;
2321                let has_ineligible_order = client_order_ids.iter().any(|client_order_id| {
2322                    self.is_dispatched(*client_order_id)
2323                        || cache
2324                            .order(client_order_id)
2325                            .is_some_and(|order| !Self::has_submittable_status(&order))
2326                });
2327
2328                if !has_ineligible_order {
2329                    return SubmissionValidationResult::Valid;
2330                }
2331
2332                SubmissionValidationResult::Deny(OrderDeniedReason::OrderListDenied {
2333                    order_list_id: cmd.order_list.id,
2334                })
2335            }
2336            _ => SubmissionValidationResult::Valid,
2337        }
2338    }
2339
2340    fn has_submittable_status(order: &OrderAny) -> bool {
2341        matches!(
2342            order.status(),
2343            OrderStatus::Initialized | OrderStatus::Released
2344        )
2345    }
2346
2347    // External client dispatches are recorded even when their orders are not cached
2348    fn is_dispatched(&self, client_order_id: ClientOrderId) -> bool {
2349        self.cache.borrow().is_order_dispatched(&client_order_id)
2350    }
2351
2352    // A cached order accepts a submit command only while it has a submittable status and has not
2353    // already been dispatched to an execution client.
2354    fn is_eligible_for_submission(&self, order: &OrderAny) -> bool {
2355        Self::has_submittable_status(order) && !self.is_dispatched(order.client_order_id())
2356    }
2357
2358    fn deny_submission(&self, command: &TradingCommand, reason: &OrderDeniedReason) {
2359        let TradingCommand::SubmitOrderList(cmd) = command else {
2360            return;
2361        };
2362
2363        let cache = self.cache.borrow();
2364        let mut orders: Vec<OrderAny> = cmd
2365            .order_list
2366            .client_order_ids
2367            .iter()
2368            .filter_map(|client_order_id| cache.order_owned(client_order_id))
2369            .collect();
2370        drop(cache);
2371
2372        for client_order_id in &cmd.order_list.client_order_ids {
2373            if orders
2374                .iter()
2375                .any(|order| order.client_order_id() == *client_order_id)
2376            {
2377                continue;
2378            }
2379
2380            let Some(order_init) = cmd
2381                .order_inits
2382                .iter()
2383                .find(|init| init.client_order_id == *client_order_id)
2384            else {
2385                continue;
2386            };
2387
2388            if let Some(order) = self.add_order_from_init(order_init, cmd.position_id, cmd) {
2389                orders.push(order);
2390            }
2391        }
2392
2393        let mut eligible_orders = Vec::with_capacity(orders.len());
2394
2395        for order in &orders {
2396            if self.is_eligible_for_submission(order) {
2397                eligible_orders.push(order);
2398            } else if Self::has_submittable_status(order) {
2399                log::warn!(
2400                    "Preserving {} already dispatched to an execution client, not denying for order list {}",
2401                    order.client_order_id(),
2402                    cmd.order_list.id,
2403                );
2404            }
2405        }
2406
2407        if eligible_orders.is_empty() {
2408            log::warn!(
2409                "Skipping stale submit command for order list {}",
2410                cmd.order_list.id
2411            );
2412            return;
2413        }
2414
2415        let reason = reason.to_string();
2416        for order in eligible_orders {
2417            self.deny_order(order, &reason);
2418        }
2419    }
2420
2421    fn routing_context_for_command(command: &TradingCommand) -> String {
2422        match command {
2423            TradingCommand::QueryAccount(cmd) => {
2424                let issuer = cmd.account_id.get_issuer();
2425                format!("account_id={}, issuer={issuer}", cmd.account_id)
2426            }
2427            _ => format!("venue={}", command.instrument_id().venue),
2428        }
2429    }
2430
2431    /// Returns the execution client selected by the command routing rules.
2432    pub fn find_client_for_command(
2433        &self,
2434        command: &TradingCommand,
2435    ) -> Option<&ExecutionClientAdapter> {
2436        if let Some(client_id) = command.client_id()
2437            && let Some(adapter) = self.clients.get(&client_id)
2438        {
2439            return Some(adapter);
2440        }
2441
2442        if let Some(account_id) = self.account_id_for_command(command) {
2443            let issuer = account_id.get_issuer();
2444            let issuer_client_id = ClientId::from(issuer.as_str());
2445
2446            if let Some(adapter) = self.clients.get(&issuer_client_id) {
2447                return Some(adapter);
2448            }
2449
2450            if let Some(client_id) = self.routing_map.get(&issuer)
2451                && let Some(adapter) = self.clients.get(client_id)
2452            {
2453                return Some(adapter);
2454            }
2455        }
2456
2457        if let Some(instrument_id) = Self::instrument_id_for_command(command)
2458            && let Some(client_id) = self.routing_map.get(&instrument_id.venue)
2459            && let Some(adapter) = self.clients.get(client_id)
2460        {
2461            return Some(adapter);
2462        }
2463
2464        self.default_client_id.and_then(|id| self.clients.get(&id))
2465    }
2466
2467    fn account_id_for_command(&self, command: &TradingCommand) -> Option<AccountId> {
2468        match command {
2469            TradingCommand::QueryAccount(cmd) => Some(cmd.account_id),
2470            TradingCommand::SubmitOrder(cmd) => self
2471                .cache
2472                .borrow()
2473                .order(&cmd.client_order_id)
2474                .and_then(|order| order.account_id()),
2475            TradingCommand::ModifyOrder(cmd) => self
2476                .cache
2477                .borrow()
2478                .order(&cmd.client_order_id)
2479                .and_then(|order| order.account_id()),
2480            TradingCommand::CancelOrder(cmd) => self
2481                .cache
2482                .borrow()
2483                .order(&cmd.client_order_id)
2484                .and_then(|order| order.account_id()),
2485            TradingCommand::SubmitOrderList(_)
2486            | TradingCommand::ModifyOrders(_)
2487            | TradingCommand::CancelOrders(_)
2488            | TradingCommand::CancelAllOrders(_)
2489            | TradingCommand::QueryOrder(_) => None,
2490        }
2491    }
2492
2493    const fn instrument_id_for_command(command: &TradingCommand) -> Option<InstrumentId> {
2494        match command {
2495            TradingCommand::SubmitOrder(cmd) => Some(cmd.instrument_id),
2496            TradingCommand::SubmitOrderList(cmd) => Some(cmd.instrument_id),
2497            TradingCommand::ModifyOrder(cmd) => Some(cmd.instrument_id),
2498            TradingCommand::ModifyOrders(cmd) => Some(cmd.instrument_id),
2499            TradingCommand::CancelOrder(cmd) => Some(cmd.instrument_id),
2500            TradingCommand::CancelOrders(cmd) => Some(cmd.instrument_id),
2501            TradingCommand::CancelAllOrders(cmd) => Some(cmd.instrument_id),
2502            TradingCommand::QueryOrder(cmd) => Some(cmd.instrument_id),
2503            TradingCommand::QueryAccount(_) => None,
2504        }
2505    }
2506
2507    fn handle_submit_order(&self, client: &dyn ExecutionClient, cmd: SubmitOrder) {
2508        let client_order_id = cmd.client_order_id;
2509        let cached_order = { self.cache.borrow().order_owned(&client_order_id) };
2510
2511        let (order, added_to_cache) = match cached_order {
2512            Some(order) => (order, false),
2513            None => {
2514                let Some(order) = self.add_order_from_init(&cmd.order_init, cmd.position_id, &cmd)
2515                else {
2516                    return;
2517                };
2518
2519                (order, true)
2520            }
2521        };
2522
2523        if added_to_cache && self.config.snapshot_orders {
2524            self.create_order_state_snapshot(&order);
2525        }
2526
2527        let order_venue = order.instrument_id().venue;
2528        let client_venue = client.venue();
2529        if !client.handles_order_venue(order_venue) {
2530            let client_id = client.client_id();
2531            let reason = OrderDeniedReason::ClientVenueMismatch {
2532                client_id,
2533                order_venue,
2534                client_venue,
2535            }
2536            .to_string();
2537            self.deny_order(&order, &reason);
2538            return;
2539        }
2540
2541        if let Some(reason) = self.check_position_id_against_oms(
2542            cmd.instrument_id,
2543            cmd.strategy_id,
2544            cmd.position_id,
2545            client,
2546        ) {
2547            self.deny_order(&order, &reason.to_string());
2548            return;
2549        }
2550
2551        let instrument_id = order.instrument_id();
2552
2553        if !added_to_cache && self.config.snapshot_orders {
2554            self.create_order_state_snapshot(&order);
2555        }
2556
2557        {
2558            let cache = self.cache.borrow();
2559            if cache.instrument(&instrument_id).is_none() {
2560                log::error!(
2561                    "Cannot handle submit order: no instrument found for {instrument_id}, {cmd}",
2562                );
2563                return;
2564            }
2565        }
2566
2567        let client_id = client.client_id();
2568        let claim_result = self
2569            .cache
2570            .borrow_mut()
2571            .claim_order_clients(&[(client_order_id, client_id)]);
2572
2573        if let Err(e) = claim_result {
2574            self.deny_order(
2575                &order,
2576                &OrderDeniedReason::ValidationFailed {
2577                    detail: format!(
2578                        "Failed to claim execution client {client_id} for {client_order_id}: {e}"
2579                    ),
2580                }
2581                .to_string(),
2582            );
2583            return;
2584        }
2585
2586        if self.config.manage_own_order_books && should_handle_own_book_order(&order) {
2587            let mut own_book = self.get_or_init_own_order_book(&order.instrument_id());
2588            own_book.add(order.to_own_book_order());
2589        }
2590
2591        log_info!("Submit {order}", color = LogColor::Blue);
2592
2593        if let Err(e) = client.submit_order(cmd) {
2594            self.deny_order(
2595                &order,
2596                &OrderDeniedReason::SubmitFailed {
2597                    detail: e.to_string(),
2598                }
2599                .to_string(),
2600            );
2601            return;
2602        }
2603
2604        self.cache
2605            .borrow_mut()
2606            .mark_orders_dispatched([client_order_id]);
2607    }
2608
2609    fn handle_submit_order_list(&self, client: &dyn ExecutionClient, cmd: SubmitOrderList) {
2610        let mut orders = Vec::with_capacity(cmd.order_list.client_order_ids.len());
2611        let mut added_client_order_ids = AHashSet::new();
2612
2613        for client_order_id in &cmd.order_list.client_order_ids {
2614            let cached_order = { self.cache.borrow().order_owned(client_order_id) };
2615
2616            if let Some(order) = cached_order {
2617                orders.push(order);
2618                continue;
2619            }
2620
2621            let Some(order_init) = cmd
2622                .order_inits
2623                .iter()
2624                .find(|init| init.client_order_id == *client_order_id)
2625            else {
2626                log::error!(
2627                    "Cannot handle submit order list: order not found in cache and no initialization event for {client_order_id}, {cmd}"
2628                );
2629                continue;
2630            };
2631
2632            let Some(order) = self.add_order_from_init(order_init, cmd.position_id, &cmd) else {
2633                continue;
2634            };
2635
2636            added_client_order_ids.insert(order.client_order_id());
2637            orders.push(order);
2638        }
2639
2640        if self.config.snapshot_orders {
2641            for order in &orders {
2642                if added_client_order_ids.contains(&order.client_order_id()) {
2643                    self.create_order_state_snapshot(order);
2644                }
2645            }
2646        }
2647
2648        if orders.len() != cmd.order_list.client_order_ids.len() {
2649            let reason = OrderDeniedReason::OrderListIncomplete {
2650                order_list_id: cmd.order_list.id,
2651            }
2652            .to_string();
2653
2654            for order in &orders {
2655                self.deny_order(order, &reason);
2656            }
2657            return;
2658        }
2659
2660        let order_list_venue = cmd.instrument_id.venue;
2661        let client_venue = client.venue();
2662        if !client.handles_order_venue(order_list_venue) {
2663            let client_id = client.client_id();
2664            let reason = OrderDeniedReason::ClientVenueMismatch {
2665                client_id,
2666                order_venue: order_list_venue,
2667                client_venue,
2668            }
2669            .to_string();
2670
2671            for order in &orders {
2672                self.deny_order(order, &reason);
2673            }
2674            return;
2675        }
2676
2677        let is_uniform_instrument = orders
2678            .iter()
2679            .all(|o| o.instrument_id() == cmd.instrument_id);
2680
2681        if let Some(position_id) = cmd.position_id
2682            && !is_uniform_instrument
2683        {
2684            let reason = OrderDeniedReason::InvalidPositionId {
2685                position_id,
2686                detail: "not valid for a mixed-instrument order list; a position belongs to a single instrument"
2687                    .to_string(),
2688            }
2689            .to_string();
2690
2691            for order in &orders {
2692                self.deny_order(order, &reason);
2693            }
2694            return;
2695        }
2696
2697        if let Some(reason) = self.check_position_id_against_oms(
2698            cmd.instrument_id,
2699            cmd.strategy_id,
2700            cmd.position_id,
2701            client,
2702        ) {
2703            let reason = reason.to_string();
2704            for order in &orders {
2705                self.deny_order(order, &reason);
2706            }
2707            return;
2708        }
2709
2710        if self.config.snapshot_orders {
2711            for order in &orders {
2712                if !added_client_order_ids.contains(&order.client_order_id()) {
2713                    self.create_order_state_snapshot(order);
2714                }
2715            }
2716        }
2717
2718        {
2719            let cache = self.cache.borrow();
2720            if cache.instrument(&cmd.instrument_id).is_none() {
2721                log::error!(
2722                    "Cannot handle submit order list: no instrument found for {}, {cmd}",
2723                    cmd.instrument_id,
2724                );
2725                return;
2726            }
2727        }
2728
2729        let client_id = client.client_id();
2730        let claims = orders
2731            .iter()
2732            .map(|order| (order.client_order_id(), client_id))
2733            .collect::<Vec<_>>();
2734        let claim_result = self.cache.borrow_mut().claim_order_clients(&claims);
2735        if let Err(e) = claim_result {
2736            let reason = OrderDeniedReason::ValidationFailed {
2737                detail: format!(
2738                    "Failed to claim execution client {client_id} for order list {}: {e}",
2739                    cmd.order_list.id,
2740                ),
2741            }
2742            .to_string();
2743
2744            for order in &orders {
2745                self.deny_order(order, &reason);
2746            }
2747            return;
2748        }
2749
2750        if self.config.manage_own_order_books {
2751            for order in &orders {
2752                if should_handle_own_book_order(order) {
2753                    let mut own_book = self.get_or_init_own_order_book(&order.instrument_id());
2754                    own_book.add(order.to_own_book_order());
2755                }
2756            }
2757        }
2758
2759        log_info!("Submit {}", cmd.order_list, color = LogColor::Blue);
2760
2761        if let Err(e) = client.submit_order_list(cmd) {
2762            log::error!(
2763                "Error submitting order list to client {}",
2764                client.client_id()
2765            );
2766
2767            let reason = OrderDeniedReason::SubmitFailed {
2768                detail: e.to_string(),
2769            }
2770            .to_string();
2771
2772            for order in &orders {
2773                self.deny_order(order, &reason);
2774            }
2775            return;
2776        }
2777
2778        self.cache
2779            .borrow_mut()
2780            .mark_orders_dispatched(orders.iter().map(Order::client_order_id));
2781    }
2782
2783    fn add_order_from_init(
2784        &self,
2785        order_init: &OrderInitialized,
2786        position_id: Option<PositionId>,
2787        context: &dyn Display,
2788    ) -> Option<OrderAny> {
2789        let client_order_id = order_init.client_order_id;
2790        let order = match OrderAny::from_events(vec![OrderEventAny::Initialized(
2791            order_init.clone(),
2792        )]) {
2793            Ok(order) => order,
2794            Err(e) => {
2795                log::error!(
2796                    "Cannot reconstruct order from initialization event for {client_order_id}: {e}, {context}"
2797                );
2798                return None;
2799            }
2800        };
2801
2802        if let Err(e) = self
2803            .cache
2804            .borrow_mut()
2805            .add_order(order.clone(), position_id, None, true)
2806        {
2807            log::error!(
2808                "Cannot add reconstructed order to cache for {client_order_id}: {e}, {context}"
2809            );
2810            return None;
2811        }
2812
2813        Some(order)
2814    }
2815
2816    fn handle_modify_order(&self, client: &dyn ExecutionClient, cmd: ModifyOrder) {
2817        let venue_str = cmd
2818            .venue_order_id
2819            .map_or_else(String::new, |venue_order_id| format!(" {venue_order_id}"));
2820
2821        log_info!(
2822            "Modify {}{venue_str}",
2823            cmd.client_order_id,
2824            color = LogColor::Blue
2825        );
2826
2827        let command_id = cmd.command_id;
2828        if client.modify_order(cmd).is_err() {
2829            log::error!(
2830                "Error modifying order: client {}, command {command_id}",
2831                client.client_id()
2832            );
2833        }
2834    }
2835
2836    fn handle_batch_modify_orders(&self, client: &dyn ExecutionClient, cmd: BatchModifyOrders) {
2837        let command_id = cmd.command_id;
2838        if client.batch_modify_orders(cmd).is_err() {
2839            log::error!(
2840                "Error batch modifying orders: client {}, command {command_id}",
2841                client.client_id()
2842            );
2843        }
2844    }
2845
2846    fn handle_cancel_order(&self, client: &dyn ExecutionClient, cmd: CancelOrder) {
2847        let venue_str = cmd
2848            .venue_order_id
2849            .map_or_else(String::new, |venue_order_id| format!(" {venue_order_id}"));
2850
2851        log_info!(
2852            "Cancel {}{venue_str}",
2853            cmd.client_order_id,
2854            color = LogColor::Blue
2855        );
2856
2857        let command_id = cmd.command_id;
2858        if client.cancel_order(cmd).is_err() {
2859            log::error!(
2860                "Error canceling order: client {}, command {command_id}",
2861                client.client_id()
2862            );
2863        }
2864    }
2865
2866    fn handle_cancel_all_orders(&self, client: &dyn ExecutionClient, command: &CancelAllOrders) {
2867        let client_id = client.client_id();
2868        let account_id = client.account_id();
2869        let algorithm_commands = self.plan_cancel_all_orders(command, client_id, account_id);
2870        let venue_command = Self::create_cancel_all_child(command, client_id);
2871        let emulator_command = Self::create_cancel_all_child(command, client_id);
2872        let side_str = command
2873            .order_side
2874            .map_or_else(|| " ".to_string(), |order_side| format!(" {order_side} "));
2875
2876        log_info!("Cancel all{side_str}orders", color = LogColor::Blue);
2877
2878        let command_id = command.command_id;
2879
2880        if client.cancel_all_orders(venue_command).is_err() {
2881            log::error!(
2882                "Error canceling all orders: client {}, command {command_id}",
2883                client.client_id()
2884            );
2885        }
2886
2887        msgbus::send_trading_command(
2888            MessagingSwitchboard::order_emulator_execute(),
2889            TradingCommand::CancelAllOrders(emulator_command),
2890        );
2891
2892        for (exec_algorithm_id, algorithm_command) in algorithm_commands {
2893            let endpoint = format!("{exec_algorithm_id}.execute");
2894            msgbus::send_any(
2895                endpoint.into(),
2896                &TradingCommand::CancelOrder(algorithm_command),
2897            );
2898        }
2899    }
2900
2901    fn plan_cancel_all_orders(
2902        &self,
2903        command: &CancelAllOrders,
2904        client_id: ClientId,
2905        account_id: AccountId,
2906    ) -> Vec<(ExecAlgorithmId, CancelOrder)> {
2907        let order_side = command.order_side;
2908        let candidates: Vec<(OrderAny, bool)> = {
2909            let cache = self.cache.borrow();
2910            cache
2911                .orders_active_local_refs(
2912                    None,
2913                    Some(&command.instrument_id),
2914                    None,
2915                    None,
2916                    order_side,
2917                )
2918                .into_iter()
2919                .filter_map(|order| {
2920                    if order
2921                        .account_id()
2922                        .is_some_and(|order_account_id| order_account_id != account_id)
2923                    {
2924                        return None;
2925                    }
2926
2927                    let cached_client_id = cache.client_id(&order.client_order_id()).copied();
2928                    let matches_client = match cached_client_id {
2929                        Some(order_client_id) => order_client_id == client_id,
2930                        None => command.client_id.is_none(),
2931                    };
2932
2933                    if !matches_client {
2934                        return None;
2935                    }
2936
2937                    let is_emulated = order.is_emulated() || order.emulation_trigger().is_some();
2938                    if !is_emulated && order.exec_algorithm_id().is_none() {
2939                        return None;
2940                    }
2941
2942                    Some((order.cloned(), cached_client_id.is_none()))
2943                })
2944                .collect()
2945        };
2946
2947        let claims: Vec<_> = candidates
2948            .iter()
2949            .filter_map(|(order, needs_claim)| {
2950                needs_claim.then_some((order.client_order_id(), client_id))
2951            })
2952            .collect();
2953        let claims_succeeded = claims.is_empty()
2954            || match self.cache.borrow_mut().claim_order_clients(&claims) {
2955                Ok(()) => true,
2956                Err(e) => {
2957                    log::error!(
2958                        "Cannot scope local cancel-all orders to execution client {client_id}: {e}"
2959                    );
2960                    false
2961                }
2962            };
2963        let correlation_id = command.correlation_id.or(Some(command.command_id));
2964        let mut algorithm_commands = Vec::new();
2965
2966        for (order, needs_claim) in candidates {
2967            if needs_claim && !claims_succeeded {
2968                continue;
2969            }
2970
2971            let is_emulated = order.is_emulated() || order.emulation_trigger().is_some();
2972            if is_emulated {
2973                continue;
2974            }
2975
2976            if let Some(exec_algorithm_id) = order.exec_algorithm_id() {
2977                let mut child = CancelOrder::new(
2978                    command.trader_id,
2979                    Some(client_id),
2980                    order.strategy_id(),
2981                    order.instrument_id(),
2982                    order.client_order_id(),
2983                    order.venue_order_id(),
2984                    UUID4::new(),
2985                    command.ts_init,
2986                    command.params.clone(),
2987                    correlation_id,
2988                );
2989                child.causation_id = Some(command.command_id);
2990                algorithm_commands.push((exec_algorithm_id, child));
2991            }
2992        }
2993
2994        algorithm_commands.sort_by_key(|(exec_algorithm_id, command)| {
2995            (*exec_algorithm_id, command.client_order_id)
2996        });
2997        algorithm_commands.dedup_by_key(|(_, command)| command.client_order_id);
2998
2999        algorithm_commands
3000    }
3001
3002    fn create_cancel_all_child(command: &CancelAllOrders, client_id: ClientId) -> CancelAllOrders {
3003        let mut child = CancelAllOrders::new(
3004            command.trader_id,
3005            Some(client_id),
3006            command.strategy_id,
3007            command.instrument_id,
3008            command.order_side,
3009            UUID4::new(),
3010            command.ts_init,
3011            command.params.clone(),
3012            command.correlation_id.or(Some(command.command_id)),
3013        );
3014        child.causation_id = Some(command.command_id);
3015        child
3016    }
3017
3018    fn handle_batch_cancel_orders(&self, client: &dyn ExecutionClient, cmd: BatchCancelOrders) {
3019        let client_order_ids: Vec<ClientOrderId> = cmd
3020            .cancels
3021            .iter()
3022            .map(|cancel| cancel.client_order_id)
3023            .collect();
3024
3025        log_info!(
3026            "Batch cancel orders {client_order_ids:?}",
3027            color = LogColor::Blue
3028        );
3029
3030        let command_id = cmd.command_id;
3031        if client.batch_cancel_orders(cmd).is_err() {
3032            log::error!(
3033                "Error batch canceling orders: client {}, command {command_id}",
3034                client.client_id()
3035            );
3036        }
3037    }
3038
3039    fn handle_query_account(&self, client: &dyn ExecutionClient, cmd: QueryAccount) {
3040        log_info!("Query {}", cmd.account_id, color = LogColor::Blue);
3041
3042        let command_id = cmd.command_id;
3043        if client.query_account(cmd).is_err() {
3044            log::warn!(
3045                "Error querying account: client {}, command {command_id}",
3046                client.client_id()
3047            );
3048        }
3049    }
3050
3051    fn handle_query_order(&self, client: &dyn ExecutionClient, cmd: QueryOrder) {
3052        log_info!("Query {}", cmd.client_order_id, color = LogColor::Blue);
3053
3054        let command_id = cmd.command_id;
3055        if client.query_order(cmd).is_err() {
3056            log::warn!(
3057                "Error querying order: client {}, command {command_id}",
3058                client.client_id()
3059            );
3060        }
3061    }
3062
3063    fn create_order_state_snapshot(&self, order: &OrderAny) {
3064        if self.config.debug {
3065            log::debug!("Creating order state snapshot for {order}");
3066        }
3067
3068        if self.cache.borrow().has_backing()
3069            && let Err(e) = self.cache.borrow().snapshot_order_state(order)
3070        {
3071            log::warn!("Failed to snapshot order state: {e}");
3072        }
3073    }
3074
3075    fn create_position_state_snapshot(&self, position: &Position, open_only: bool) {
3076        Self::publish_position_state_snapshot(
3077            &self.clock,
3078            &self.cache,
3079            self.config.debug,
3080            position,
3081            open_only,
3082        );
3083    }
3084
3085    fn publish_position_state_snapshot(
3086        clock: &Rc<RefCell<dyn Clock>>,
3087        cache: &Rc<RefCell<Cache>>,
3088        debug: bool,
3089        position: &Position,
3090        open_only: bool,
3091    ) {
3092        if debug {
3093            log::debug!("Creating position state snapshot for {position}");
3094        }
3095
3096        let ts_snapshot = clock.borrow().timestamp_ns();
3097        let unrealized_pnl = cache.borrow().calculate_unrealized_pnl(position);
3098
3099        let snapshot = PositionStateSnapshot {
3100            position: position.clone(),
3101            unrealized_pnl,
3102            ts_snapshot,
3103        };
3104
3105        let topic = switchboard::get_snapshot_position_topic(position.id);
3106        msgbus::publish_any(topic, &snapshot);
3107
3108        let has_backing = cache.borrow().has_backing();
3109        if has_backing
3110            && let Err(e) = cache.borrow_mut().snapshot_position_state(
3111                position,
3112                ts_snapshot,
3113                unrealized_pnl,
3114                Some(open_only),
3115            )
3116        {
3117            log::warn!("Failed to snapshot position state: {e}");
3118        }
3119    }
3120
3121    fn handle_event(&mut self, event: &OrderEventAny) {
3122        let covered = match event {
3123            OrderEventAny::Filled(fill) if fill.reconciliation => {
3124                self.fill_precedes_reconciliation_snapshot(fill)
3125            }
3126            _ => false,
3127        };
3128
3129        self.handle_event_with_position_application(event, !covered);
3130    }
3131
3132    fn fill_precedes_reconciliation_snapshot(&self, fill: &OrderFilled) -> bool {
3133        let oms_type = self.determine_oms_type(fill);
3134        let cache = self.cache.borrow();
3135
3136        if cache
3137            .order(&fill.client_order_id)
3138            .is_some_and(|order| is_fill_price_restatement(&order, fill))
3139        {
3140            return false;
3141        }
3142
3143        let is_covered = |position: &Position| {
3144            position.account_id == fill.account_id
3145                && position.instrument_id == fill.instrument_id
3146                && fill_precedes_reconciled_position(&cache, position, fill.trade_id, fill.ts_event)
3147        };
3148
3149        if oms_type != OmsType::Hedging {
3150            let positions = cache.positions_refs(
3151                None,
3152                Some(&fill.instrument_id),
3153                None,
3154                Some(&fill.account_id),
3155                None,
3156            );
3157            return positions.into_iter().any(|position| is_covered(&position));
3158        }
3159
3160        let Ok(indexed) = self.cached_fill_position_id(fill, oms_type) else {
3161            return false;
3162        };
3163
3164        let Some(order) = cache.order(&fill.client_order_id) else {
3165            return false;
3166        };
3167
3168        let Some(position_id) = indexed
3169            .or(fill.position_id)
3170            .or_else(|| self.cached_hedging_position_id(fill, &order))
3171        else {
3172            return false;
3173        };
3174
3175        cache
3176            .position_ref(&position_id)
3177            .is_some_and(|position| is_covered(&position))
3178    }
3179
3180    fn handle_event_with_position_application(
3181        &mut self,
3182        event: &OrderEventAny,
3183        apply_position: bool,
3184    ) {
3185        let applied = self.apply_order_event(event, apply_position);
3186
3187        // Negative acknowledgment for clients awaiting application of an enqueued fill or void.
3188        // The declined event itself is the acknowledgment; each drop site logs its reason.
3189        if apply_position
3190            && !applied
3191            && matches!(
3192                event,
3193                OrderEventAny::Filled(_) | OrderEventAny::FillVoided(_)
3194            )
3195        {
3196            let topic = switchboard::get_order_fill_declined_topic(event.instrument_id());
3197            msgbus::publish_order_event(topic, event);
3198        }
3199    }
3200
3201    /// Applies an order event, returning whether it was applied and published.
3202    fn apply_order_event(&mut self, event: &OrderEventAny, apply_position: bool) -> bool {
3203        if let OrderEventAny::Filled(fill) = event
3204            && fill.last_qty.is_zero()
3205        {
3206            log::warn!("Skipping zero-quantity fill event: {fill}");
3207            return false;
3208        }
3209
3210        self.event_count += 1;
3211
3212        if self.config.debug {
3213            log::debug!("{RECV}{EVT} {event}");
3214        }
3215
3216        if self.publish_absent_order_denial(event) {
3217            return true;
3218        }
3219
3220        let event_client_order_id = event.client_order_id();
3221        let mut cache = self.cache.borrow();
3222
3223        let client_order_id = if cache.order_exists(&event_client_order_id) {
3224            event_client_order_id
3225        } else {
3226            drop(cache);
3227            let is_leg_fill =
3228                matches!(event, OrderEventAny::Filled(fill) if self.is_leg_fill(fill));
3229            cache = self.cache.borrow();
3230
3231            if !is_leg_fill {
3232                log::warn!(
3233                    "Order with {} not found in the cache to apply {}",
3234                    event.client_order_id(),
3235                    event
3236                );
3237            }
3238
3239            // Try to find order by venue order ID if available
3240            let venue_order_id = if let Some(id) = event.venue_order_id() {
3241                id
3242            } else {
3243                log::error!(
3244                    "Cannot apply event to any order: {} not found in the cache with no VenueOrderId",
3245                    event.client_order_id()
3246                );
3247                return false;
3248            };
3249
3250            // Look up client order ID from venue order ID
3251            let client_order_id = if let Some(id) = cache.client_order_id(&venue_order_id) {
3252                *id
3253            } else {
3254                if let OrderEventAny::Filled(fill) = event
3255                    && is_leg_fill
3256                {
3257                    log::info!(
3258                        "Processing leg fill without corresponding order: {} for instrument {}",
3259                        fill.client_order_id,
3260                        fill.instrument_id
3261                    );
3262                    drop(cache);
3263                    return self.handle_leg_fill_without_order(fill.clone());
3264                }
3265
3266                log::error!(
3267                    "Cannot apply event to any order: {} and {venue_order_id} not found in the cache",
3268                    event.client_order_id(),
3269                );
3270                return false;
3271            };
3272
3273            // Get order using found client order ID
3274            if cache.order_exists(&client_order_id) {
3275                log::info!("Order with {client_order_id} was found in the cache");
3276                client_order_id
3277            } else {
3278                if let OrderEventAny::Filled(fill) = event
3279                    && is_leg_fill
3280                {
3281                    log::info!(
3282                        "Processing leg fill without corresponding order: {} for instrument {}",
3283                        fill.client_order_id,
3284                        fill.instrument_id
3285                    );
3286                    drop(cache);
3287                    return self.handle_leg_fill_without_order(fill.clone());
3288                }
3289
3290                log::error!(
3291                    "Cannot apply event to any order: {client_order_id} and {venue_order_id} not found in cache",
3292                );
3293                return false;
3294            }
3295        };
3296        let order_before_fill = if matches!(event, OrderEventAny::Filled(_)) {
3297            cache.order(&client_order_id).map(|o| o.clone())
3298        } else {
3299            None
3300        };
3301
3302        drop(cache);
3303
3304        let event = if event_client_order_id == client_order_id {
3305            event.clone()
3306        } else {
3307            event.clone().with_client_order_id(client_order_id)
3308        };
3309
3310        match &event {
3311            OrderEventAny::Filled(fill) => {
3312                let Some(order_before_fill) = order_before_fill else {
3313                    log::error!(
3314                        "Cannot apply fill: order {} not found in the cache",
3315                        fill.client_order_id()
3316                    );
3317                    return false;
3318                };
3319                let configured_oms_type = self.determine_oms_type(fill);
3320                let Some(position_id) =
3321                    self.determine_position_id(fill, configured_oms_type, Some(&order_before_fill))
3322                else {
3323                    return false;
3324                };
3325                let oms_type = self
3326                    .cache
3327                    .borrow()
3328                    .oms_type(&position_id)
3329                    .unwrap_or(configured_oms_type);
3330
3331                let mut fill = fill.clone();
3332                fill.position_id = Some(position_id);
3333
3334                let restatement = is_fill_price_restatement(&order_before_fill, &fill);
3335                let validation = if apply_position {
3336                    self.validate_fill_for_order(&order_before_fill, &fill)
3337                } else {
3338                    self.validate_fill_for_order_projection(&order_before_fill, &fill)
3339                };
3340
3341                if validation.is_err() {
3342                    return false;
3343                }
3344
3345                let affects_quantity = fill_affects_quantity(apply_position, restatement);
3346                if affects_quantity
3347                    && !self.validate_fill_for_external_position(
3348                        &order_before_fill,
3349                        &fill,
3350                        oms_type,
3351                        position_id,
3352                    )
3353                {
3354                    return false;
3355                }
3356
3357                let event = OrderEventAny::Filled(fill.clone());
3358
3359                let Some(order) = self.update_cached_order(client_order_id, &event, false) else {
3360                    return false;
3361                };
3362
3363                let position_events = if apply_position {
3364                    self.handle_order_fill(&order, fill, oms_type, restatement)
3365                } else {
3366                    Vec::new()
3367                };
3368
3369                self.publish_order_event(&event);
3370                self.publish_position_events(position_events);
3371            }
3372            OrderEventAny::FillVoided(voided) => {
3373                let mut voided = voided.clone();
3374                let Some(order_before_void) = self
3375                    .cache
3376                    .borrow()
3377                    .order(&client_order_id)
3378                    .map(|order| order.clone())
3379                else {
3380                    log::error!("Cannot apply fill void: order {client_order_id} not found");
3381                    return false;
3382                };
3383                let original_fill = order_before_void
3384                    .events()
3385                    .into_iter()
3386                    .find_map(|candidate| match candidate {
3387                        OrderEventAny::Filled(fill) if fill.trade_id == voided.trade_id => {
3388                            Some(fill.clone())
3389                        }
3390                        _ => None,
3391                    });
3392
3393                if voided.position_id.is_none() {
3394                    voided.position_id = original_fill.as_ref().and_then(|fill| fill.position_id);
3395                }
3396                let event = OrderEventAny::FillVoided(voided.clone());
3397
3398                let mut validated_order = order_before_void.clone();
3399                match validated_order.apply(event.clone()) {
3400                    Ok(()) => {}
3401                    Err(OrderError::DuplicateFillVoid(trade_id)) => {
3402                        log::warn!(
3403                            "Duplicate fill void rejected at order level: trade_id={trade_id}"
3404                        );
3405                        return false;
3406                    }
3407                    Err(e) => {
3408                        log::error!("Cannot apply fill void to order: {e}");
3409                        return false;
3410                    }
3411                }
3412
3413                let corrected_positions = if apply_position
3414                    && original_fill
3415                        .as_ref()
3416                        .is_some_and(|fill| fill.position_id.is_some())
3417                    && !self.skips_settled_position_change(
3418                        "Fill void",
3419                        voided.instrument_id,
3420                        voided.trade_id,
3421                    ) {
3422                    match self.prepare_order_fill_void_positions(&order_before_void, &voided) {
3423                        Ok(positions) => positions,
3424                        Err(e) => {
3425                            log::error!("Cannot apply fill void to positions: {e}");
3426                            return false;
3427                        }
3428                    }
3429                } else {
3430                    Vec::new()
3431                };
3432
3433                let Some(position_events) =
3434                    self.apply_order_fill_void_positions(corrected_positions, &voided)
3435                else {
3436                    return false;
3437                };
3438
3439                if self
3440                    .update_cached_order(client_order_id, &event, true)
3441                    .is_none()
3442                {
3443                    return false;
3444                }
3445
3446                if original_fill.is_some() {
3447                    let portfolio_endpoint = MessagingSwitchboard::portfolio_update_order();
3448                    msgbus::send_order_event(portfolio_endpoint, event.clone());
3449                }
3450                self.publish_order_event(&event);
3451                self.publish_position_events(position_events);
3452            }
3453            _ => {
3454                if self
3455                    .update_cached_order(client_order_id, &event, true)
3456                    .is_some()
3457                {
3458                    self.publish_order_event(&event);
3459                }
3460            }
3461        }
3462
3463        true
3464    }
3465
3466    fn apply_order_fill_void_positions(
3467        &self,
3468        corrected_positions: Vec<CorrectedPosition>,
3469        voided: &OrderFillVoided,
3470    ) -> Option<Vec<PositionEvent>> {
3471        let mut position_events = Vec::new();
3472
3473        for CorrectedPosition {
3474            position,
3475            corrected_qty,
3476            absorbed_prior_cycles,
3477            closed_cycles_pnl,
3478        } in corrected_positions
3479        {
3480            if let Err(e) = self.cache.borrow_mut().update_position(&position) {
3481                log::error!("Cannot apply fill void to position {}: {e}", position.id);
3482                return None;
3483            }
3484
3485            if absorbed_prior_cycles {
3486                log::info!(
3487                    "Settling archived NETTING cycles rebuilt by fill void {} for position {}: realized={closed_cycles_pnl:?}",
3488                    voided.trade_id,
3489                    position.id,
3490                );
3491
3492                self.cache
3493                    .borrow_mut()
3494                    .settle_position_snapshots(&position, closed_cycles_pnl);
3495            }
3496
3497            if self.config.snapshot_positions {
3498                self.create_position_state_snapshot(&position, false);
3499            }
3500
3501            position_events.push(Self::create_fill_void_position_event(
3502                &position,
3503                voided,
3504                corrected_qty,
3505            ));
3506        }
3507
3508        Some(position_events)
3509    }
3510
3511    fn handle_leg_fill_without_order(&mut self, mut fill: OrderFilled) -> bool {
3512        let Some(instrument) = self.load_fill_instrument(&fill.instrument_id) else {
3513            return false;
3514        };
3515
3516        if let Err(e) = self.cache.borrow().try_account(&fill.account_id) {
3517            log::error!("Cannot handle leg fill: {e}, {fill}");
3518            return false;
3519        }
3520
3521        let oms_type = self.determine_oms_type(&fill);
3522        let position_id = self.determine_leg_fill_position_id(&fill, oms_type);
3523        fill.position_id = Some(position_id);
3524
3525        if !self.validate_fill_for_position(position_id, &fill) {
3526            return false;
3527        }
3528
3529        let duplicate_position_fill = self.position_contains_trade_id(position_id, fill.trade_id);
3530
3531        let event = OrderEventAny::Filled(fill.clone());
3532
3533        if duplicate_position_fill {
3534            log::warn!(
3535                "Duplicate leg fill: {} trade_id={} already applied to position {}, skipping",
3536                fill.client_order_id,
3537                fill.trade_id,
3538                position_id
3539            );
3540            return false;
3541        }
3542
3543        let portfolio_endpoint = MessagingSwitchboard::portfolio_update_order();
3544        msgbus::send_order_event(portfolio_endpoint, event.clone());
3545        let position_events = self.handle_position_update(&instrument, fill, oms_type);
3546        self.publish_order_event(&event);
3547        self.publish_position_events(position_events);
3548
3549        true
3550    }
3551
3552    fn determine_leg_fill_position_id(
3553        &mut self,
3554        fill: &OrderFilled,
3555        oms_type: OmsType,
3556    ) -> PositionId {
3557        let cache = self.cache.borrow();
3558        let cached_position_id = cache.position_id(&fill.client_order_id()).copied();
3559        drop(cache);
3560
3561        if let Some(position_id) = cached_position_id {
3562            if let Some(fill_position_id) = fill.position_id
3563                && fill_position_id != position_id
3564            {
3565                log::warn!(
3566                    "Incorrect position ID assigned to leg fill: \
3567                     cached={position_id}, assigned={fill_position_id}; \
3568                     re-assigning from cache",
3569                );
3570            }
3571
3572            return position_id;
3573        }
3574
3575        match oms_type {
3576            OmsType::Hedging => self
3577                .orderless_hedging_leg_position_id(fill)
3578                .or(fill.position_id)
3579                .unwrap_or_else(|| self.pos_id_generator.generate(fill.strategy_id, false)),
3580            OmsType::Netting => self.determine_netting_position_id(fill, None),
3581            _ => self.determine_netting_position_id(fill, None),
3582        }
3583    }
3584
3585    fn orderless_hedging_leg_position_id(&self, fill: &OrderFilled) -> Option<PositionId> {
3586        if !self.is_leg_fill(fill) {
3587            return None;
3588        }
3589
3590        let cache = self.cache.borrow();
3591        if cache.order_exists(&fill.client_order_id()) {
3592            return None;
3593        }
3594
3595        let matching_positions: Vec<PositionId> = cache
3596            .positions_open(
3597                Some(&fill.instrument_id.venue),
3598                Some(&fill.instrument_id),
3599                Some(&fill.strategy_id),
3600                Some(&fill.account_id),
3601                None,
3602            )
3603            .iter()
3604            .filter(|position| position.opening_order_id == fill.client_order_id)
3605            .map(|position| position.id)
3606            .collect();
3607
3608        match matching_positions.as_slice() {
3609            [position_id] => Some(*position_id),
3610            [] => None,
3611            _ => {
3612                log::warn!(
3613                    "Cannot uniquely correlate HEDGING leg fill {} to an orderless position: \
3614                     found {} positions with opening_order_id={}",
3615                    fill.trade_id,
3616                    matching_positions.len(),
3617                    fill.client_order_id,
3618                );
3619                None
3620            }
3621        }
3622    }
3623
3624    fn is_leg_fill(&self, fill: &OrderFilled) -> bool {
3625        if !fill.client_order_id.as_str().contains("-LEG-")
3626            && !fill.venue_order_id.as_str().contains("-LEG-")
3627        {
3628            return false;
3629        }
3630
3631        self.load_fill_instrument(&fill.instrument_id)
3632            .is_some_and(|instrument| !instrument.is_spread())
3633    }
3634
3635    fn determine_oms_type(&self, fill: &OrderFilled) -> OmsType {
3636        let client_id = self
3637            .cache
3638            .borrow()
3639            .client_id(&fill.client_order_id)
3640            .copied();
3641
3642        let client = client_id.and_then(|id| self.get_client(&id)).or_else(|| {
3643            self.source_client_id_for_account(fill.account_id, &fill.instrument_id)
3644                .and_then(|id| self.get_client(&id))
3645        });
3646
3647        self.resolve_oms_type_for_client(fill.strategy_id, client)
3648    }
3649
3650    fn resolve_oms_type_for_client(
3651        &self,
3652        strategy_id: StrategyId,
3653        client: Option<&dyn ExecutionClient>,
3654    ) -> OmsType {
3655        if let Some(oms_type) = self.oms_overrides.get(&strategy_id)
3656            && *oms_type != OmsType::Unspecified
3657        {
3658            return *oms_type;
3659        }
3660
3661        // Missing or ambiguous ownership retains the origin-free NETTING fallback
3662        client.map_or(OmsType::Netting, ExecutionClient::oms_type)
3663    }
3664
3665    fn check_position_id_against_oms(
3666        &self,
3667        instrument_id: InstrumentId,
3668        strategy_id: StrategyId,
3669        position_id: Option<PositionId>,
3670        client: &dyn ExecutionClient,
3671    ) -> Option<OrderDeniedReason> {
3672        let position_id = position_id?;
3673
3674        if self.resolve_oms_type_for_client(strategy_id, Some(client)) != OmsType::Netting {
3675            return None;
3676        }
3677
3678        let expected = format!("{instrument_id}-{strategy_id}");
3679        if position_id.as_str() == expected {
3680            return None;
3681        }
3682
3683        Some(OrderDeniedReason::InvalidPositionId {
3684            position_id,
3685            detail: format!(
3686                "not valid for NETTING OMS; expected '{expected}' (use HEDGING for custom position IDs)"
3687            ),
3688        })
3689    }
3690
3691    fn determine_position_id(
3692        &mut self,
3693        fill: &OrderFilled,
3694        oms_type: OmsType,
3695        order: Option<&OrderAny>,
3696    ) -> Option<PositionId> {
3697        let cached_position_id = self.cached_fill_position_id(fill, oms_type).ok()?;
3698
3699        if let Some(position_id) = cached_position_id {
3700            if self.config.debug {
3701                log::debug!("Assigned {position_id} to {}", fill.client_order_id());
3702            }
3703
3704            if !self.validate_fill_for_position(position_id, fill) {
3705                return None;
3706            }
3707
3708            return Some(position_id);
3709        }
3710
3711        let position_id = match (oms_type, fill.position_id) {
3712            (OmsType::Hedging, Some(position_id)) => position_id,
3713            (OmsType::Hedging, None) => self.determine_hedging_position_id(fill, order),
3714            (OmsType::Netting, _) => self.determine_netting_position_id(fill, order),
3715            _ => self.determine_netting_position_id(fill, order),
3716        };
3717
3718        if !self.validate_fill_for_position(position_id, fill) {
3719            return None;
3720        }
3721
3722        self.index_exec_spawn_position(fill.client_order_id, order, position_id);
3723
3724        Some(position_id)
3725    }
3726
3727    fn cached_fill_position_id(
3728        &self,
3729        fill: &OrderFilled,
3730        oms_type: OmsType,
3731    ) -> Result<Option<PositionId>, ()> {
3732        let cache = self.cache.borrow();
3733
3734        let flip = match (oms_type == OmsType::Hedging)
3735            .then(|| cache.hedging_flip_position_ids(fill.client_order_id))
3736            .transpose()
3737        {
3738            Ok(flip) => flip.flatten(),
3739            Err(e) => {
3740                log::error!("Cannot route hedging fill {}: {e}", fill.trade_id);
3741                return Err(());
3742            }
3743        };
3744
3745        let cached_position_id = flip
3746            .map(|ids| ids[1])
3747            .or_else(|| cache.position_id(&fill.client_order_id()).copied());
3748        drop(cache);
3749
3750        if self.config.debug {
3751            log::debug!(
3752                "Determining position ID for {}, position_id={:?}",
3753                fill.client_order_id(),
3754                cached_position_id,
3755            );
3756        }
3757
3758        if let Some(cached_position_id) = cached_position_id
3759            && let Some(fill_position_id) = fill.position_id
3760            && cached_position_id != fill_position_id
3761        {
3762            if oms_type == OmsType::Hedging
3763                && !flip.is_some_and(|ids| ids.contains(&fill_position_id))
3764            {
3765                log::error!(
3766                    "Cannot apply hedging fill {} for {}: venue position ID {fill_position_id} conflicts with cached position ID {cached_position_id}",
3767                    fill.trade_id,
3768                    fill.client_order_id(),
3769                );
3770
3771                return Err(());
3772            }
3773
3774            if oms_type != OmsType::Hedging {
3775                log::warn!(
3776                    "Incorrect position ID assigned to fill: \
3777                     cached={cached_position_id}, assigned={fill_position_id}; \
3778                     re-assigning from cache",
3779                );
3780            }
3781        }
3782
3783        Ok(cached_position_id)
3784    }
3785
3786    fn index_exec_spawn_position(
3787        &self,
3788        client_order_id: ClientOrderId,
3789        order: Option<&OrderAny>,
3790        position_id: PositionId,
3791    ) {
3792        let order = if let Some(o) = order {
3793            o.clone()
3794        } else {
3795            let cache = self.cache.borrow();
3796            cache.order(&client_order_id).map_or_else(
3797                || panic!("Order for {client_order_id} not found to determine position ID"),
3798                |o| o.clone(),
3799            )
3800        };
3801
3802        if order.exec_algorithm_id().is_some()
3803            && let Some(exec_spawn_id) = order.exec_spawn_id()
3804        {
3805            let cache = self.cache.borrow();
3806            let primary = if let Some(p) = cache.order(&exec_spawn_id) {
3807                p.clone()
3808            } else {
3809                log::warn!(
3810                    "Primary exec spawn order {exec_spawn_id} not found, \
3811                     skipping position ID propagation"
3812                );
3813                return;
3814            };
3815            let primary_already_indexed = cache.position_id(&primary.client_order_id()).is_some();
3816            drop(cache);
3817
3818            if primary.position_id().is_none() && !primary_already_indexed {
3819                if let Some(mut primary_mut) = self.cache.borrow_mut().order_mut(&exec_spawn_id) {
3820                    primary_mut.set_position_id(Some(position_id));
3821                }
3822                let _ = self.cache.borrow_mut().add_position_id(
3823                    &position_id,
3824                    &primary.instrument_id().venue,
3825                    &primary.client_order_id(),
3826                    &primary.strategy_id(),
3827                );
3828                log::debug!("Assigned primary order {position_id}");
3829            }
3830        }
3831    }
3832
3833    /// Returns whether `fill` may be applied to the position assigned to `position_id`.
3834    ///
3835    /// Only `instrument_id` is compared. A position's instrument never changes, and a fill
3836    /// for another instrument would be priced with this position's precision, multiplier,
3837    /// currencies, and PnL rules.
3838    ///
3839    /// `account_id` and `strategy_id` are deliberately NOT compared, because each has a
3840    /// legitimate mismatch path. Netting position IDs are `{instrument_id}-{strategy_id}`,
3841    /// so two accounts trading one instrument under one strategy share a position ID.
3842    /// External order claims can be handed to a successor strategy while the predecessor's
3843    /// positions stay cached, so a later venue fill can carry the new strategy against them.
3844    fn validate_fill_for_position(&self, position_id: PositionId, fill: &OrderFilled) -> bool {
3845        let cache = self.cache.borrow();
3846        let Some(position) = cache.position_ref(&position_id) else {
3847            return true;
3848        };
3849
3850        if position.instrument_id != fill.instrument_id {
3851            log::error!(
3852                "Cannot apply fill {} to position {position_id}: instrument_id mismatch, expected={}, received={}",
3853                fill.trade_id,
3854                position.instrument_id,
3855                fill.instrument_id
3856            );
3857            return false;
3858        }
3859
3860        true
3861    }
3862
3863    fn validate_fill_for_external_position(
3864        &self,
3865        order: &OrderAny,
3866        fill: &OrderFilled,
3867        oms_type: OmsType,
3868        position_id: PositionId,
3869    ) -> bool {
3870        if oms_type != OmsType::Netting || !order.is_reduce_only() {
3871            return true;
3872        }
3873
3874        let cache = self.cache.borrow();
3875
3876        let Some(position) = cache.position_ref(&position_id) else {
3877            return true;
3878        };
3879
3880        // A settled position takes no further fills, so only the order applies this one
3881        if position.is_settled() {
3882            return true;
3883        }
3884
3885        if position.strategy_id.is_external()
3886            && position.strategy_id != fill.strategy_id
3887            && (position.account_id != fill.account_id
3888                || !position.is_opposite_side(fill.order_side)
3889                || fill.last_qty > position.quantity)
3890        {
3891            log::error!(
3892                "Cannot apply reduce-only fill {} to external NETTING position {position_id}: \
3893                 account, side, or quantity does not match the open position",
3894                fill.trade_id,
3895            );
3896            return false;
3897        }
3898
3899        true
3900    }
3901
3902    fn determine_hedging_position_id(
3903        &mut self,
3904        fill: &OrderFilled,
3905        order: Option<&OrderAny>,
3906    ) -> PositionId {
3907        let cache = self.cache.borrow();
3908
3909        let cached_order;
3910        let order: &OrderAny = if let Some(order) = order {
3911            order
3912        } else {
3913            cached_order = cache.order(&fill.client_order_id()).unwrap_or_else(|| {
3914                panic!(
3915                    "Order for {} not found to determine position ID",
3916                    fill.client_order_id()
3917                )
3918            });
3919            &cached_order
3920        };
3921
3922        if let Some(position_id) = self.cached_hedging_position_id(fill, order) {
3923            return position_id;
3924        }
3925
3926        // Generate new position ID
3927        let position_id = self.pos_id_generator.generate(fill.strategy_id, false);
3928
3929        if self.config.debug {
3930            log::debug!("Generated {} for {}", position_id, fill.client_order_id());
3931        }
3932        position_id
3933    }
3934
3935    fn cached_hedging_position_id(
3936        &self,
3937        fill: &OrderFilled,
3938        order: &OrderAny,
3939    ) -> Option<PositionId> {
3940        let cache = self.cache.borrow();
3941
3942        if let Some(position_id) = order.exec_spawn_id().and_then(|spawn_id| {
3943            cache
3944                .orders_for_exec_spawn(&spawn_id)
3945                .into_iter()
3946                .find_map(|order| order.position_id())
3947        }) {
3948            return Some(position_id);
3949        }
3950
3951        if !order.is_reduce_only() {
3952            return None;
3953        }
3954
3955        let mut candidates = cache
3956            .positions_open(
3957                None,
3958                Some(&fill.instrument_id),
3959                Some(&fill.strategy_id),
3960                Some(&fill.account_id),
3961                None,
3962            )
3963            .into_iter()
3964            .filter(|position| position.is_opposite_side(fill.order_side));
3965        let position = candidates.next()?;
3966        if candidates.next().is_some() || !order.would_reduce_only(position.side, position.quantity)
3967        {
3968            return None;
3969        }
3970
3971        Some(position.id)
3972    }
3973
3974    fn determine_netting_position_id(
3975        &self,
3976        fill: &OrderFilled,
3977        order: Option<&OrderAny>,
3978    ) -> PositionId {
3979        let position_id = PositionId::new(format!("{}-{}", fill.instrument_id, fill.strategy_id));
3980        let cache = self.cache.borrow();
3981        if order.is_none_or(|order| !order.is_reduce_only())
3982            || cache
3983                .position_ref(&position_id)
3984                .is_some_and(|position| position.is_open())
3985        {
3986            return position_id;
3987        }
3988
3989        let mut candidates = cache
3990            .positions_open(
3991                None,
3992                Some(&fill.instrument_id),
3993                Some(&StrategyId::external()),
3994                Some(&fill.account_id),
3995                None,
3996            )
3997            .into_iter()
3998            .filter(|position| {
3999                position.is_opposite_side(fill.order_side)
4000                    && cache.oms_type(&position.id) == Some(OmsType::Netting)
4001            });
4002
4003        let candidate = candidates.next();
4004
4005        if let Some(position) = candidate
4006            && candidates.next().is_none()
4007            && fill.last_qty <= position.quantity
4008        {
4009            return position.id;
4010        }
4011
4012        position_id
4013    }
4014
4015    fn validate_fill_for_order(&self, order: &OrderAny, fill: &OrderFilled) -> anyhow::Result<()> {
4016        if order.is_duplicate_fill(fill) {
4017            log::warn!(
4018                "Duplicate fill: {} trade_id={} already applied, skipping",
4019                order.client_order_id(),
4020                fill.trade_id
4021            );
4022            anyhow::bail!("Duplicate fill");
4023        }
4024
4025        if is_fill_price_restatement(order, fill) {
4026            return Ok(());
4027        }
4028
4029        if let Some(position_id) = fill.position_id
4030            && self.position_contains_trade_id(position_id, fill.trade_id)
4031        {
4032            log::warn!(
4033                "Duplicate fill: {} trade_id={} already applied to position {}, skipping",
4034                order.client_order_id(),
4035                fill.trade_id,
4036                position_id
4037            );
4038            anyhow::bail!("Duplicate position fill");
4039        }
4040
4041        self.check_overfill(order, fill)
4042    }
4043
4044    fn validate_fill_for_order_projection(
4045        &self,
4046        order: &OrderAny,
4047        fill: &OrderFilled,
4048    ) -> anyhow::Result<()> {
4049        if order.is_duplicate_fill(fill) {
4050            anyhow::bail!("Duplicate fill");
4051        }
4052
4053        if is_fill_price_restatement(order, fill) {
4054            return Ok(());
4055        }
4056
4057        self.check_overfill(order, fill)
4058    }
4059
4060    fn position_contains_trade_id(&self, position_id: PositionId, trade_id: TradeId) -> bool {
4061        self.cache
4062            .borrow()
4063            .position(&position_id)
4064            .is_some_and(|position| position.trade_ids.contains(&trade_id))
4065    }
4066
4067    fn update_cached_order(
4068        &self,
4069        client_order_id: ClientOrderId,
4070        event: &OrderEventAny,
4071        send_portfolio_update: bool,
4072    ) -> Option<OrderAny> {
4073        let result = { self.cache.borrow_mut().update_order(event) };
4074
4075        let order = match result {
4076            Ok(order) => order,
4077            Err(e) => {
4078                if matches!(
4079                    e.downcast_ref::<OrderError>(),
4080                    Some(OrderError::InvalidStateTransition)
4081                ) {
4082                    // A non-fill event that fails to apply to an already-closed order is an
4083                    // expected venue race (e.g. a place reject then a stream cancel for the same
4084                    // order), not an anomaly. A dropped fill stays at warn even on a closed order,
4085                    // since it represents real, possibly lost, execution.
4086                    let already_closed = self
4087                        .cache
4088                        .borrow()
4089                        .order(&client_order_id)
4090                        .is_some_and(|o| o.is_closed());
4091
4092                    if already_closed && !matches!(event, OrderEventAny::Filled(_)) {
4093                        log::debug!("InvalidStateTrigger: {e}, did not apply {event}");
4094                    } else {
4095                        log::warn!("InvalidStateTrigger: {e}, did not apply {event}");
4096                    }
4097                    return None;
4098                }
4099
4100                if let Some(OrderError::DuplicateFill(trade_id)) = e.downcast_ref::<OrderError>() {
4101                    log::warn!(
4102                        "Duplicate fill rejected at order level: trade_id={trade_id}, did not apply {event}"
4103                    );
4104                    return None;
4105                }
4106
4107                if let Some(OrderError::DuplicateFillVoid(trade_id)) =
4108                    e.downcast_ref::<OrderError>()
4109                {
4110                    log::warn!(
4111                        "Duplicate fill void rejected at order level: trade_id={trade_id}, did not apply {event}"
4112                    );
4113                    return None;
4114                }
4115
4116                log::error!("Error applying event: {e}, did not apply {event}");
4117
4118                // Failed updates leave the order unchanged, so only terminal events need cleanup
4119                if matches!(
4120                    event,
4121                    OrderEventAny::Denied(_)
4122                        | OrderEventAny::Rejected(_)
4123                        | OrderEventAny::Canceled(_)
4124                        | OrderEventAny::Expired(_)
4125                ) {
4126                    log::warn!(
4127                        "Terminal event {event} failed to apply to {client_order_id}, forcing cleanup from own book"
4128                    );
4129                    self.cache
4130                        .borrow_mut()
4131                        .force_remove_from_own_order_book(&client_order_id);
4132                }
4133
4134                return None;
4135            }
4136        };
4137
4138        // The client's first status transition closes the dispatch window
4139        if !Self::has_submittable_status(&order) {
4140            self.cache
4141                .borrow_mut()
4142                .clear_order_dispatch(&client_order_id);
4143        }
4144
4145        if self.config.manage_own_order_books && should_handle_own_book_order(&order) {
4146            let needs_own_book = {
4147                self.cache
4148                    .borrow()
4149                    .own_order_book(&order.instrument_id())
4150                    .is_none()
4151            };
4152
4153            if needs_own_book {
4154                self.cache.borrow_mut().update_own_order_book(&order);
4155            }
4156        }
4157
4158        if self.config.debug {
4159            log::debug!("{SEND}{EVT} {event}");
4160        }
4161
4162        if self.config.snapshot_orders {
4163            self.create_order_state_snapshot(&order);
4164        }
4165
4166        if send_portfolio_update {
4167            self.send_order_update_to_portfolio(event);
4168        }
4169
4170        Some(order)
4171    }
4172
4173    fn send_order_update_to_portfolio(&self, event: &OrderEventAny) {
4174        let is_wallet = event.account_id().is_some_and(|account_id| {
4175            self.cache
4176                .borrow()
4177                .account(&account_id)
4178                .is_some_and(|account| account.account_type() == AccountType::Wallet)
4179        });
4180        let send_to_portfolio = match event {
4181            OrderEventAny::Filled(fill) => self
4182                .cache
4183                .borrow()
4184                .account(&fill.account_id)
4185                .is_none_or(|account| !account.is_margin_account()),
4186            OrderEventAny::Accepted(_)
4187            | OrderEventAny::Canceled(_)
4188            | OrderEventAny::Expired(_)
4189            | OrderEventAny::Rejected(_)
4190            | OrderEventAny::Updated(_) => true,
4191            OrderEventAny::Submitted(_)
4192            | OrderEventAny::Triggered(_)
4193            | OrderEventAny::PendingUpdate(_)
4194            | OrderEventAny::PendingCancel(_)
4195            | OrderEventAny::ModifyDenied(_)
4196            | OrderEventAny::ModifyRejected(_)
4197            | OrderEventAny::CancelDenied(_)
4198            | OrderEventAny::CancelRejected(_)
4199            | OrderEventAny::FillVoided(_) => is_wallet,
4200            _ => false,
4201        };
4202
4203        if send_to_portfolio {
4204            let portfolio_endpoint = MessagingSwitchboard::portfolio_update_order();
4205            msgbus::send_order_event(portfolio_endpoint, event.clone());
4206        }
4207    }
4208
4209    fn publish_order_event(&self, event: &OrderEventAny) {
4210        let topic = switchboard::get_event_order_topic(event.strategy_id());
4211        msgbus::publish_order_event(topic, event);
4212
4213        #[rustfmt::skip]
4214        let topic = match event {
4215            OrderEventAny::Submitted(_) => switchboard::get_order_submitted_topic(event.instrument_id()),
4216            OrderEventAny::Rejected(_) => switchboard::get_order_rejected_topic(event.instrument_id()),
4217            OrderEventAny::PendingUpdate(_) => switchboard::get_order_pending_update_topic(event.instrument_id()),
4218            OrderEventAny::PendingCancel(_) => switchboard::get_order_pending_cancel_topic(event.instrument_id()),
4219            OrderEventAny::ModifyDenied(_) => switchboard::get_order_modify_denied_topic(event.instrument_id()),
4220            OrderEventAny::ModifyRejected(_) => switchboard::get_order_modify_rejected_topic(event.instrument_id()),
4221            OrderEventAny::CancelDenied(_) => switchboard::get_order_cancel_denied_topic(event.instrument_id()),
4222            OrderEventAny::CancelRejected(_) => switchboard::get_order_cancel_rejected_topic(event.instrument_id()),
4223            OrderEventAny::Canceled(_) => switchboard::get_order_canceled_topic(event.instrument_id()),
4224            OrderEventAny::FillVoided(_) => switchboard::get_order_fill_voided_topic(event.instrument_id()),
4225            // Keep Filled out of this generic fanout: handle_order_fill publishes the instrument
4226            // topic, while leg fills stay on the strategy topic.
4227            _ => return,
4228        };
4229
4230        msgbus::publish_order_event(topic, event);
4231    }
4232
4233    fn publish_position_events(&self, events: Vec<PositionEvent>) {
4234        for event in events {
4235            let strategy_id = match &event {
4236                PositionEvent::PositionOpened(event) => event.strategy_id,
4237                PositionEvent::PositionChanged(event) => event.strategy_id,
4238                PositionEvent::PositionClosed(event) => event.strategy_id,
4239                PositionEvent::PositionAdjusted(event) => event.strategy_id,
4240            };
4241            let topic = switchboard::get_event_position_topic(strategy_id);
4242            msgbus::publish_position_event(topic, &event);
4243        }
4244    }
4245
4246    fn check_overfill(&self, order: &OrderAny, fill: &OrderFilled) -> anyhow::Result<()> {
4247        let potential_overfill = order.calculate_overfill(fill.last_qty);
4248
4249        if potential_overfill.is_positive() {
4250            if self.config.allow_overfills {
4251                log::warn!(
4252                    "Order overfill detected: {} potential_overfill={}, current_filled={}, last_qty={}, quantity={}",
4253                    order.client_order_id(),
4254                    potential_overfill,
4255                    order.filled_qty(),
4256                    fill.last_qty,
4257                    order.quantity()
4258                );
4259            } else {
4260                let msg = format!(
4261                    "Order overfill rejected: {} potential_overfill={}, current_filled={}, last_qty={}, quantity={}. \
4262                Set `allow_overfills=true` in ExecutionEngineConfig to allow overfills.",
4263                    order.client_order_id(),
4264                    potential_overfill,
4265                    order.filled_qty(),
4266                    fill.last_qty,
4267                    order.quantity()
4268                );
4269                log::warn!("{msg}");
4270                anyhow::bail!("{msg}");
4271            }
4272        }
4273
4274        Ok(())
4275    }
4276
4277    fn handle_order_fill(
4278        &mut self,
4279        order: &OrderAny,
4280        fill: OrderFilled,
4281        oms_type: OmsType,
4282        restatement: bool,
4283    ) -> Vec<PositionEvent> {
4284        let Some(instrument) = self.load_fill_instrument(&fill.instrument_id) else {
4285            return Vec::new();
4286        };
4287
4288        let is_margin_account = {
4289            let cache = self.cache.borrow();
4290            let account = match cache.try_account(&fill.account_id) {
4291                Ok(account) => account,
4292                Err(e) => {
4293                    log::error!("Cannot handle order fill: {e}, {fill}");
4294                    return Vec::new();
4295                }
4296            };
4297
4298            account.is_margin_account()
4299        };
4300
4301        // Margin combo fills update order state only; price restatements do not change quantity
4302        if !restatement && (!is_margin_account || !instrument.is_spread()) {
4303            let portfolio_endpoint = MessagingSwitchboard::portfolio_update_order();
4304            msgbus::send_order_event(portfolio_endpoint, OrderEventAny::Filled(fill.clone()));
4305        }
4306
4307        let (position, position_events) = if instrument.is_spread() {
4308            (None, Vec::new())
4309        } else if restatement {
4310            let position_events = self.restate_open_position_price(&fill);
4311            let position_id = fill.position_id;
4312            (
4313                position_id.and_then(|position_id| {
4314                    self.cache
4315                        .borrow()
4316                        .position(&position_id)
4317                        .map(|position| position.clone_without_events())
4318                }),
4319                position_events,
4320            )
4321        } else {
4322            let position_events = self.handle_position_update(&instrument, fill.clone(), oms_type);
4323            let position_id = fill.position_id.unwrap();
4324            (
4325                self.cache
4326                    .borrow()
4327                    .position(&position_id)
4328                    .map(|position| position.clone_without_events()),
4329                position_events,
4330            )
4331        };
4332
4333        if !position_events.is_empty() {
4334            self.index_external_position_reduction(order, &fill, oms_type, position.as_ref());
4335        }
4336
4337        // Handle contingent orders for both spread and non-spread instruments
4338        // For spread instruments, contingent orders work without position linkage
4339        if matches!(order.contingency_type(), Some(ContingencyType::Oto)) {
4340            // For non-spread instruments, link to position if available
4341            if !instrument.is_spread()
4342                && let Some(ref pos) = position
4343                && pos.is_open()
4344            {
4345                let position_id = pos.id;
4346
4347                for client_order_id in order.linked_order_ids().unwrap_or_default() {
4348                    // Take a scoped write borrow on the contingent's cell. The borrow drops at
4349                    // the end of `and_then` so the subsequent `add_position_id` on the cache is
4350                    // free to take `&mut Cache`.
4351                    let link = self.cache.borrow_mut().order_mut(client_order_id).and_then(
4352                        |mut contingent_order| {
4353                            if contingent_order.position_id().is_none() {
4354                                contingent_order.set_position_id(Some(position_id));
4355                                Some((
4356                                    contingent_order.instrument_id().venue,
4357                                    contingent_order.client_order_id(),
4358                                    contingent_order.strategy_id(),
4359                                ))
4360                            } else {
4361                                None
4362                            }
4363                        },
4364                    );
4365
4366                    if let Some((venue, contingent_id, strategy_id)) = link
4367                        && let Err(e) = self.cache.borrow_mut().add_position_id(
4368                            &position_id,
4369                            &venue,
4370                            &contingent_id,
4371                            &strategy_id,
4372                        )
4373                    {
4374                        log::error!("Failed to add position ID: {e}");
4375                    }
4376                }
4377            }
4378            // For spread instruments, contingent orders can still be triggered
4379            // but without position linkage (since no position is created for spreads)
4380        }
4381
4382        let topic = switchboard::get_order_filled_topic(fill.instrument_id);
4383        let event = OrderEventAny::Filled(fill);
4384        msgbus::publish_order_event(topic, &event);
4385
4386        position_events
4387    }
4388
4389    fn load_fill_instrument(&self, instrument_id: &InstrumentId) -> Option<InstrumentAny> {
4390        if let Some(instrument) = self.cache.borrow().instrument(instrument_id) {
4391            return Some(instrument.clone());
4392        }
4393
4394        let loaded = self.cache.borrow_mut().load_instrument(instrument_id);
4395        match loaded {
4396            Ok(Some(instrument)) => Some(instrument),
4397            Ok(None) => {
4398                log::error!("Cannot handle fill: no instrument found for {instrument_id}");
4399                None
4400            }
4401            Err(e) => {
4402                log::error!("Cannot load instrument {instrument_id} for fill: {e}");
4403                None
4404            }
4405        }
4406    }
4407
4408    fn index_external_position_reduction(
4409        &self,
4410        order: &OrderAny,
4411        fill: &OrderFilled,
4412        oms_type: OmsType,
4413        position: Option<&Position>,
4414    ) {
4415        if oms_type == OmsType::Netting
4416            && order.is_reduce_only()
4417            && let Some(position) = position
4418            && position.strategy_id.is_external()
4419            && let Err(e) = self.cache.borrow_mut().add_position_id(
4420                &position.id,
4421                &fill.instrument_id.venue,
4422                &fill.client_order_id,
4423                &position.strategy_id,
4424            )
4425        {
4426            log::error!("Failed to index external position for reducing order: {e}");
4427        }
4428    }
4429
4430    fn prepare_order_fill_void_positions(
4431        &self,
4432        order: &OrderAny,
4433        event: &OrderFillVoided,
4434    ) -> anyhow::Result<Vec<CorrectedPosition>> {
4435        let source_event_id = order
4436            .events()
4437            .into_iter()
4438            .find_map(|order_event| match order_event {
4439                OrderEventAny::Filled(fill) if fill.trade_id == event.trade_id => {
4440                    Some(fill.event_id)
4441                }
4442                _ => None,
4443            })
4444            .ok_or_else(|| anyhow::anyhow!("fill {} is not in order history", event.trade_id))?;
4445
4446        let positions: Vec<Position> = {
4447            let cache = self.cache.borrow();
4448
4449            let strategy_id = event
4450                .position_id
4451                .and_then(|id| cache.position_ref(&id))
4452                .filter(|position| {
4453                    order.is_reduce_only()
4454                        && position.strategy_id.is_external()
4455                        && cache.oms_type(&position.id) == Some(OmsType::Netting)
4456                })
4457                .map_or(event.strategy_id, |position| position.strategy_id);
4458
4459            cache
4460                .positions(
4461                    None,
4462                    Some(&event.instrument_id),
4463                    Some(&strategy_id),
4464                    Some(&event.account_id),
4465                    None,
4466                )
4467                .into_iter()
4468                .map(|position| position.cloned())
4469                .collect()
4470        };
4471        let mut fragments = Vec::new();
4472
4473        for position in &positions {
4474            for replay_event in &position.replay_events {
4475                let PositionReplayEvent::Filled(fill) = replay_event else {
4476                    continue;
4477                };
4478
4479                if fill.client_order_id != event.client_order_id || fill.trade_id != event.trade_id
4480                {
4481                    continue;
4482                }
4483                let split_rank = if fill.event_id == source_event_id {
4484                    0
4485                } else if fill.causation_id == Some(source_event_id) {
4486                    1
4487                } else {
4488                    continue;
4489                };
4490                fragments.push((position.id, split_rank, fill.last_qty, fill.commission));
4491            }
4492        }
4493        anyhow::ensure!(
4494            !fragments.is_empty(),
4495            "no position fragments found for fill {}",
4496            event.trade_id
4497        );
4498        fragments.sort_by_key(|(_, split_rank, _, _)| *split_rank);
4499
4500        let precision = fragments
4501            .iter()
4502            .map(|(_, _, qty, _)| qty.precision)
4503            .chain(positions.iter().flat_map(|position| {
4504                position
4505                    .fill_voids
4506                    .iter()
4507                    .filter(|record| {
4508                        (record.event.client_order_id, record.event.trade_id)
4509                            == (event.client_order_id, event.trade_id)
4510                    })
4511                    .map(|record| record.voided_qty.precision)
4512            }))
4513            .chain([event.voided_qty.precision])
4514            .max()
4515            .unwrap_or(event.voided_qty.precision);
4516
4517        let mut allocations = IndexMap::<PositionId, (Quantity, Option<Money>)>::new();
4518        let mut remaining_qty = rescale_fill_void_qty(event.voided_qty, precision)?;
4519        for (position_id, _, quantity, _) in fragments.iter().rev() {
4520            if remaining_qty.is_zero() {
4521                break;
4522            }
4523
4524            let quantity = rescale_fill_void_qty(*quantity, precision)?;
4525            let removed = remaining_qty.min(quantity);
4526            let allocation = allocations
4527                .entry(*position_id)
4528                .or_insert((Quantity::zero(precision), None));
4529            allocation.0 = allocation
4530                .0
4531                .checked_add(removed)
4532                .ok_or_else(|| anyhow::anyhow!("position fill void allocation overflow"))?;
4533            remaining_qty = remaining_qty
4534                .checked_sub(removed)
4535                .ok_or_else(|| anyhow::anyhow!("position fill void quantity underflow"))?;
4536        }
4537        anyhow::ensure!(
4538            remaining_qty.is_zero(),
4539            "position fragments do not cover voided quantity for fill {}",
4540            event.trade_id
4541        );
4542
4543        if let Some(mut remaining_commission) = event.commission_voided {
4544            for (position_id, _, _, commission) in fragments.iter().rev() {
4545                if remaining_commission.is_zero() {
4546                    break;
4547                }
4548                let Some(commission) = commission else {
4549                    continue;
4550                };
4551                anyhow::ensure!(
4552                    commission.currency == remaining_commission.currency,
4553                    "position commission currency differs for fill {}",
4554                    event.trade_id
4555                );
4556                let magnitude = remaining_commission.abs().min(commission.abs());
4557
4558                let removed = if remaining_commission.is_negative() {
4559                    -magnitude
4560                } else {
4561                    magnitude
4562                };
4563
4564                let allocation = allocations
4565                    .entry(*position_id)
4566                    .or_insert((Quantity::zero(precision), None));
4567                allocation.1 = Some(allocation.1.map_or(Ok(removed), |commission| {
4568                    commission
4569                        .checked_add(removed)
4570                        .ok_or_else(|| anyhow::anyhow!("position fill void commission overflow"))
4571                })?);
4572
4573                remaining_commission = remaining_commission
4574                    .checked_sub(removed)
4575                    .ok_or_else(|| anyhow::anyhow!("position fill void commission underflow"))?;
4576            }
4577            anyhow::ensure!(
4578                remaining_commission.is_zero(),
4579                "position fragments do not cover voided commission for fill {}",
4580                event.trade_id
4581            );
4582        }
4583
4584        let mut corrected_positions = Vec::new();
4585
4586        for (position_id, (voided_qty, commission_voided)) in allocations {
4587            if voided_qty.is_zero() {
4588                anyhow::bail!(
4589                    "commission-only position correction requires authoritative reconciliation for fill {}",
4590                    event.trade_id
4591                );
4592            }
4593
4594            let prior = positions
4595                .iter()
4596                .find(|position| position.id == position_id)
4597                .ok_or_else(|| anyhow::anyhow!("position {position_id} is not cached"))?;
4598            let mut position = prior.clone();
4599
4600            let previous = position
4601                .fill_voids
4602                .iter()
4603                .rev()
4604                .find(|record| {
4605                    record.event.client_order_id == event.client_order_id
4606                        && record.event.trade_id == event.trade_id
4607                })
4608                .map(|record| (record.voided_qty, record.commission_voided));
4609            if previous == Some((voided_qty, commission_voided)) {
4610                continue;
4611            }
4612
4613            let prior_qty = previous.map_or(Quantity::zero(precision), |(qty, _)| qty);
4614            let prior_qty = rescale_fill_void_qty(prior_qty, precision)?;
4615            let corrected_qty = voided_qty
4616                .checked_sub(prior_qty)
4617                .ok_or_else(|| anyhow::anyhow!("stale position fill void quantity"))?;
4618
4619            // `events` holds the fills since the position was last flat, because `apply_fill`
4620            // clears it when reopening from flat. A NETTING flip splits one fill across the
4621            // closing and reopening cycles under the same trade, so compare quantities rather
4622            // than presence: the correction reaches an earlier cycle once it exceeds what the
4623            // current cycle originally held. Earlier corrections have already shrunk the
4624            // fragments in `events` while `voided_qty` stays cumulative, so add back what this
4625            // position already voided. Read this before `apply_fill_void`, whose rebuild
4626            // re-derives `events` and can move that boundary.
4627            let current_cycle_qty = position
4628                .events
4629                .iter()
4630                .filter(|fill| {
4631                    fill.client_order_id == event.client_order_id && fill.trade_id == event.trade_id
4632                })
4633                .try_fold(prior_qty, |total, fill| {
4634                    let qty = rescale_fill_void_qty(fill.last_qty, precision)?;
4635                    total
4636                        .checked_add(qty)
4637                        .ok_or_else(|| anyhow::anyhow!("position current cycle quantity overflow"))
4638                })?;
4639
4640            let closed_cycles_pnl =
4641                position.apply_fill_void(event.clone(), voided_qty, commission_voided)?;
4642            let absorbed_prior_cycles = position::requires_snapshot_settlement(
4643                prior,
4644                &position,
4645                voided_qty,
4646                current_cycle_qty,
4647                self.config.carry_replay_events_on_reopen,
4648            );
4649            corrected_positions.push(CorrectedPosition {
4650                position,
4651                corrected_qty,
4652                absorbed_prior_cycles,
4653                closed_cycles_pnl,
4654            });
4655        }
4656        Ok(corrected_positions)
4657    }
4658
4659    fn create_fill_void_position_event(
4660        position: &Position,
4661        fill_voided: &OrderFillVoided,
4662        corrected_qty: Quantity,
4663    ) -> PositionEvent {
4664        let event_id = UUID4::new();
4665        let ts_init = fill_voided.ts_init;
4666
4667        if position.is_closed() {
4668            PositionEvent::PositionClosed(PositionClosed {
4669                trader_id: position.trader_id,
4670                strategy_id: position.strategy_id,
4671                instrument_id: position.instrument_id,
4672                position_id: position.id,
4673                account_id: position.account_id,
4674                opening_order_id: position.opening_order_id,
4675                closing_order_id: position.closing_order_id,
4676                entry: position.entry,
4677                side: position.side,
4678                signed_qty: position.signed_qty,
4679                quantity: position.quantity,
4680                peak_quantity: position.peak_qty,
4681                last_qty: corrected_qty,
4682                last_px: fill_voided.last_px,
4683                currency: position.quote_currency,
4684                avg_px_open: position.avg_px_open,
4685                avg_px_close: position.avg_px_close,
4686                realized_return: position.realized_return,
4687                realized_pnl: position.realized_pnl,
4688                unrealized_pnl: Money::zero(position.quote_currency),
4689                duration: position.duration_ns,
4690                event_id,
4691                ts_opened: position.ts_opened,
4692                ts_closed: position.ts_closed,
4693                ts_event: fill_voided.ts_event,
4694                ts_init,
4695            })
4696        } else {
4697            PositionEvent::PositionChanged(PositionChanged {
4698                trader_id: position.trader_id,
4699                strategy_id: position.strategy_id,
4700                instrument_id: position.instrument_id,
4701                position_id: position.id,
4702                account_id: position.account_id,
4703                opening_order_id: position.opening_order_id,
4704                entry: position.entry,
4705                side: position.side,
4706                signed_qty: position.signed_qty,
4707                quantity: position.quantity,
4708                peak_quantity: position.peak_qty,
4709                last_qty: corrected_qty,
4710                last_px: fill_voided.last_px,
4711                currency: position.quote_currency,
4712                avg_px_open: position.avg_px_open,
4713                avg_px_close: position.avg_px_close,
4714                realized_return: position.realized_return,
4715                realized_pnl: position.realized_pnl,
4716                unrealized_pnl: Money::zero(position.quote_currency),
4717                event_id,
4718                ts_opened: position.ts_opened,
4719                ts_event: fill_voided.ts_event,
4720                ts_init,
4721            })
4722        }
4723    }
4724
4725    /// Handle position creation or update for a fill.
4726    ///
4727    /// This function mirrors the Python `_handle_position_update` method.
4728    fn handle_position_update(
4729        &mut self,
4730        instrument: &InstrumentAny,
4731        fill: OrderFilled,
4732        oms_type: OmsType,
4733    ) -> Vec<PositionEvent> {
4734        enum Action {
4735            Open,
4736            Reopen,
4737            Flip(Box<Position>),
4738            Update,
4739        }
4740
4741        let position_id = if let Some(position_id) = fill.position_id {
4742            position_id
4743        } else {
4744            log::error!("Cannot handle position update: no position ID found for fill {fill}");
4745            return Vec::new();
4746        };
4747
4748        if self.skips_settled_position_change("Fill", fill.instrument_id, fill.trade_id) {
4749            return Vec::new();
4750        }
4751
4752        let action = {
4753            let cache = self.cache.borrow();
4754
4755            match cache.position(&position_id) {
4756                None => Action::Open,
4757                Some(position) if position.is_closed() => Action::Reopen,
4758                Some(position) if self.will_flip_position(&position, &fill) => {
4759                    Action::Flip(Box::new(position.clone()))
4760                }
4761                Some(_) => Action::Update,
4762            }
4763        };
4764
4765        match action {
4766            Action::Open => {
4767                if self.reject_reduce_only_position_open(&fill, oms_type) {
4768                    return Vec::new();
4769                }
4770
4771                // Copy these before `fill` moves into `open_position`
4772                let instrument_id = fill.instrument_id;
4773                let trade_id = fill.trade_id;
4774
4775                self.open_position(instrument, None, true, fill, oms_type)
4776                    .unwrap_or_else(|e| {
4777                        log::error!(
4778                            "Failed to open position {position_id} for instrument \
4779                             {instrument_id} from fill {trade_id}: {e:?}"
4780                        );
4781                        Vec::new()
4782                    })
4783            }
4784            Action::Reopen => {
4785                if self.reject_reduce_only_position_open(&fill, oms_type) {
4786                    return Vec::new();
4787                }
4788
4789                let instrument_id = fill.instrument_id;
4790                let trade_id = fill.trade_id;
4791
4792                self.open_position(instrument, Some(position_id), true, fill, oms_type)
4793                    .unwrap_or_else(|e| {
4794                        log::error!(
4795                            "Failed to reopen position {position_id} for instrument \
4796                             {instrument_id} from fill {trade_id}: {e:?}"
4797                        );
4798                        Vec::new()
4799                    })
4800            }
4801            Action::Flip(mut position) => {
4802                self.flip_position(instrument, &mut position, &fill, oms_type)
4803            }
4804            Action::Update => self
4805                .update_position_from_fill(position_id, &fill)
4806                .into_iter()
4807                .collect(),
4808        }
4809    }
4810
4811    fn reject_reduce_only_position_open(&self, fill: &OrderFilled, oms_type: OmsType) -> bool {
4812        let cache = self.cache.borrow();
4813        let Some(order) = cache.order_owned(&fill.client_order_id) else {
4814            return false;
4815        };
4816
4817        if !order.is_reduce_only() {
4818            return false;
4819        }
4820
4821        let positions_open = cache.positions_open(
4822            None,
4823            Some(&fill.instrument_id),
4824            None,
4825            Some(&fill.account_id),
4826            None,
4827        );
4828        let position_id = fill
4829            .position_id
4830            .map_or_else(|| "None".to_string(), |position_id| position_id.to_string());
4831        let matching_position_details = Self::position_details(
4832            positions_open
4833                .iter()
4834                .filter(|position| position.is_opposite_side(fill.order_side))
4835                .map(|position| &**position),
4836        );
4837        let open_position_details =
4838            Self::position_details(positions_open.iter().map(|position| &**position));
4839
4840        log::error!(
4841            "Cannot open {oms_type} position {position_id} from reduce-only fill {} for {}; \
4842             matching_reduce_positions=[{}], open_positions=[{}]",
4843            fill.trade_id,
4844            fill.instrument_id,
4845            matching_position_details,
4846            open_position_details
4847        );
4848
4849        true
4850    }
4851
4852    #[allow(
4853        clippy::needless_pass_by_value,
4854        reason = "takes the opening fill by value to seed the new position"
4855    )]
4856    fn open_position(
4857        &self,
4858        instrument: &InstrumentAny,
4859        prior_position_id: Option<PositionId>,
4860        archive_prior: bool,
4861        fill: OrderFilled,
4862        oms_type: OmsType,
4863    ) -> anyhow::Result<Vec<PositionEvent>> {
4864        let position = Position::new_checked(instrument, fill.clone())?;
4865
4866        if let Some(position_id) = prior_position_id {
4867            let prior_snapshot = {
4868                let cache = self.cache.borrow();
4869                let position = cache
4870                    .position(&position_id)
4871                    .ok_or_else(|| anyhow::anyhow!("position {position_id} is not cached"))?;
4872
4873                if archive_prior && position.has_replay_trade_id(fill.trade_id) {
4874                    log::warn!(
4875                        "Ignoring duplicate fill {} for closed position {}; no position reopened (side={:?}, qty={}, px={})",
4876                        fill.trade_id,
4877                        position.id,
4878                        fill.order_side,
4879                        fill.last_qty,
4880                        fill.last_px
4881                    );
4882                    return Ok(Vec::new());
4883                }
4884
4885                archive_prior.then(|| position.clone_for_snapshot())
4886            };
4887
4888            if let Some(position) = prior_snapshot {
4889                self.reopen_position(&position, oms_type)?;
4890            }
4891        }
4892
4893        let is_orderless_leg = self.is_leg_fill(&fill)
4894            && !self.cache.borrow().order_exists(&position.opening_order_id);
4895        if let Some(position_id) = prior_position_id {
4896            debug_assert_eq!(position_id, position.id);
4897
4898            self.cache.borrow_mut().replace_position(
4899                &position,
4900                oms_type,
4901                !is_orderless_leg,
4902                self.config.carry_replay_events_on_reopen
4903                    || (oms_type == OmsType::Hedging && position_id.is_virtual()),
4904            )?;
4905        } else if is_orderless_leg {
4906            self.cache
4907                .borrow_mut()
4908                .add_position_without_order(&position, oms_type)?;
4909        } else {
4910            self.cache.borrow_mut().add_position(&position, oms_type)?;
4911        }
4912
4913        let (position, snapshot_position) = {
4914            let cache = self.cache.borrow();
4915            let position = cache
4916                .position(&fill.position_id.expect("Opening fill has no position ID"))
4917                .expect("Opened position is no longer cached");
4918            (
4919                position.clone_for_snapshot(),
4920                self.config.snapshot_positions.then(|| position.clone()),
4921            )
4922        };
4923
4924        if let Some(snapshot_position) = snapshot_position {
4925            self.create_position_state_snapshot(&snapshot_position, true);
4926        }
4927
4928        let ts_init = self.clock.borrow().timestamp_ns();
4929        let event = PositionOpened::create(&position, &fill, UUID4::new(), ts_init);
4930
4931        Ok(vec![PositionEvent::PositionOpened(event)])
4932    }
4933
4934    fn reopen_position(&self, position: &Position, oms_type: OmsType) -> anyhow::Result<()> {
4935        if oms_type == OmsType::Netting {
4936            if position.is_open() {
4937                anyhow::bail!(
4938                    "Cannot reopen position {} (oms_type=NETTING): reopening is only valid for closed positions in NETTING mode",
4939                    position.id
4940                );
4941            }
4942        } else {
4943            // HEDGING mode
4944            log::warn!(
4945                "Received fill for closed position {} in HEDGING mode; archiving closed cycle and creating new position",
4946                position.id
4947            );
4948        }
4949
4950        // Snapshot the closed cycle before its ID is reused: `add_position` replaces the
4951        // cached position, and realized PnL totals read closed cycles from the snapshots
4952        self.snapshot_position(position)?;
4953
4954        Ok(())
4955    }
4956
4957    /// Archives the closed `position` and anchors the frame when an anchorer is installed.
4958    ///
4959    /// An installed anchorer needs the encoded frame, so this takes the eager path. Without one
4960    /// the cache defers the encode unless a backing database has to persist the frame.
4961    fn snapshot_position(&self, position: &Position) -> anyhow::Result<()> {
4962        let mut cache = self.cache.borrow_mut();
4963
4964        let Some(anchorer) = &self.snapshot_anchorer else {
4965            return cache.snapshot_position(position);
4966        };
4967
4968        let snapshot_ref = cache.snapshot_position_encoded(position)?;
4969        drop(cache);
4970
4971        if let Err(e) = anchorer(snapshot_ref) {
4972            log::warn!("Failed to record cache snapshot anchor: {e}");
4973        }
4974
4975        Ok(())
4976    }
4977
4978    fn update_position(
4979        &self,
4980        position: &mut Position,
4981        fill: &OrderFilled,
4982    ) -> Option<PositionEvent> {
4983        if let Err(e) = position.try_apply(fill) {
4984            log::error!(
4985                "Failed to apply fill {} to position {}: {e}",
4986                fill.trade_id,
4987                position.id
4988            );
4989            return None;
4990        }
4991
4992        // Check if position is closed after applying the fill
4993        let is_closed = position.is_closed();
4994
4995        // Update position in cache - this should handle the closed state tracking
4996        if let Err(e) = self.cache.borrow_mut().update_position(position) {
4997            log::error!("Failed to update position: {e:?}");
4998            return None;
4999        }
5000
5001        // Create position state snapshot if enabled
5002        if self.config.snapshot_positions {
5003            self.create_position_state_snapshot(position, false);
5004        }
5005
5006        let ts_init = self.clock.borrow().timestamp_ns();
5007
5008        if is_closed {
5009            let event = PositionClosed::create(position, fill, UUID4::new(), ts_init);
5010            Some(PositionEvent::PositionClosed(event))
5011        } else {
5012            let event = PositionChanged::create(position, fill, UUID4::new(), ts_init);
5013            Some(PositionEvent::PositionChanged(event))
5014        }
5015    }
5016
5017    fn restate_open_position_price(&self, fill: &OrderFilled) -> Vec<PositionEvent> {
5018        let Some(position_id) = fill.position_id else {
5019            return Vec::new();
5020        };
5021
5022        let applicable = self
5023            .cache
5024            .borrow()
5025            .position(&position_id)
5026            .is_some_and(|position| position.accepts_price_restatement(fill));
5027
5028        if !applicable {
5029            if let Some(position) = self.cache.borrow().position(&position_id) {
5030                log::warn!(
5031                    "Price restatement for {} trade_id={} was not applied to position {}: \
5032                     the trade is not an opening fill of the current cycle with a matching quantity",
5033                    fill.client_order_id,
5034                    fill.trade_id,
5035                    position.id,
5036                );
5037            }
5038
5039            return Vec::new();
5040        }
5041
5042        self.update_position_from_fill(position_id, fill)
5043            .into_iter()
5044            .collect()
5045    }
5046
5047    fn update_position_from_fill(
5048        &self,
5049        position_id: PositionId,
5050        fill: &OrderFilled,
5051    ) -> Option<PositionEvent> {
5052        let position = match self
5053            .cache
5054            .borrow_mut()
5055            .update_position_from_fill(position_id, fill)
5056        {
5057            Ok(position) => position,
5058            Err(e) => {
5059                log::error!("Failed to update position: {e:?}");
5060                return None;
5061            }
5062        };
5063
5064        if self.config.snapshot_positions {
5065            let position = self
5066                .cache
5067                .borrow()
5068                .position_owned(&position_id)
5069                .expect("Updated position is no longer cached");
5070            self.create_position_state_snapshot(&position, false);
5071        }
5072
5073        let ts_init = self.clock.borrow().timestamp_ns();
5074
5075        if position.is_closed() {
5076            let event = PositionClosed::create(&position, fill, UUID4::new(), ts_init);
5077            Some(PositionEvent::PositionClosed(event))
5078        } else {
5079            let event = PositionChanged::create(&position, fill, UUID4::new(), ts_init);
5080            Some(PositionEvent::PositionChanged(event))
5081        }
5082    }
5083
5084    fn settle_instrument_close(&self, close: &InstrumentClose) {
5085        let instrument_id = close.instrument_id;
5086
5087        let settled =
5088            match settlement::settle_instrument_close(&mut self.cache.borrow_mut(), *close) {
5089                Ok(settled) => settled,
5090                Err(e) => {
5091                    log::error!("Cannot settle {instrument_id}: {e}");
5092                    return;
5093                }
5094            };
5095
5096        let Some(close) = settlement::settlement_close(&self.cache.borrow(), &instrument_id) else {
5097            return;
5098        };
5099
5100        let mut position_events = Vec::with_capacity(settled.len());
5101
5102        for (position, last_qty) in settled {
5103            if self.config.snapshot_positions {
5104                let snapshot = self.cache.borrow().position_owned(&position.id);
5105                if let Some(snapshot) = snapshot {
5106                    self.create_position_state_snapshot(&snapshot, false);
5107                }
5108            }
5109
5110            log::info!(
5111                "Settled position {} at {} from contract expiration, realized_pnl={:?}",
5112                position.id,
5113                close.close_price,
5114                position.realized_pnl,
5115            );
5116
5117            let ts_init = self.clock.borrow().timestamp_ns();
5118            let event = PositionClosed::create_from_instrument_close(
5119                &position,
5120                &close,
5121                last_qty,
5122                UUID4::new(),
5123                ts_init,
5124            );
5125            position_events.push(PositionEvent::PositionClosed(event));
5126        }
5127
5128        self.publish_position_events(position_events);
5129    }
5130
5131    // Only venues this engine settles count, so a close cached without that subscription,
5132    // such as in a backtest, leaves fills applying to positions.
5133    fn skips_settled_position_change(
5134        &self,
5135        kind: &str,
5136        instrument_id: InstrumentId,
5137        trade_id: TradeId,
5138    ) -> bool {
5139        if !self.instrument_close_venues.contains(&instrument_id.venue) {
5140            return false;
5141        }
5142
5143        let is_settled =
5144            settlement::settlement_close(&self.cache.borrow(), &instrument_id).is_some();
5145
5146        if is_settled {
5147            log::warn!(
5148                "{kind} {trade_id} for {instrument_id} arrived after contract settlement; positions unchanged"
5149            );
5150        }
5151
5152        is_settled
5153    }
5154
5155    fn will_flip_position(&self, position: &Position, fill: &OrderFilled) -> bool {
5156        position.is_opposite_side(fill.order_side) && (fill.last_qty > position.quantity)
5157    }
5158
5159    fn position_signed_decimal_qty(position: &Position) -> Decimal {
5160        match position.side {
5161            PositionSide::Long => position.quantity.as_decimal(),
5162            PositionSide::Short => -position.quantity.as_decimal(),
5163            _ => Decimal::ZERO,
5164        }
5165    }
5166
5167    fn position_details<'a>(positions: impl IntoIterator<Item = &'a Position>) -> String {
5168        positions
5169            .into_iter()
5170            .map(|position| {
5171                format!(
5172                    "{} strategy_id={} signed_qty={}",
5173                    position.id,
5174                    position.strategy_id,
5175                    Self::position_signed_decimal_qty(position)
5176                )
5177            })
5178            .collect::<Vec<_>>()
5179            .join(", ")
5180    }
5181
5182    fn flip_position(
5183        &mut self,
5184        instrument: &InstrumentAny,
5185        position: &mut Position,
5186        fill: &OrderFilled,
5187        oms_type: OmsType,
5188    ) -> Vec<PositionEvent> {
5189        let mut position_events = Vec::new();
5190
5191        if fill.commission.is_none() {
5192            log::warn!(
5193                "Commission is not available for position flip, splitting with no commission"
5194            );
5195        }
5196
5197        let position_id_flip = if oms_type == OmsType::Hedging
5198            && let Some(position_id) = fill.position_id
5199            && position_id.is_virtual()
5200        {
5201            // Generate new position ID for flipped virtual position (Hedging OMS only)
5202            Some(self.pos_id_generator.generate(fill.strategy_id, true))
5203        } else {
5204            // Default: use the same position ID as the fill (Python behavior)
5205            fill.position_id
5206        };
5207
5208        let (fill_split1, fill_split2) =
5209            match fill.split_for_position_flip(position.quantity, position_id_flip, UUID4::new()) {
5210                Ok(fills) => fills,
5211                Err(e) => {
5212                    log::error!("Failed to split position flip: {e}");
5213                    return position_events;
5214                }
5215            };
5216
5217        if let Err(e) = Position::new_checked(instrument, fill_split2.clone()) {
5218            log::error!("Failed to validate flipped position: {e}");
5219            return position_events;
5220        }
5221
5222        // A database error can leave the closing fill applied in memory
5223        if let Some(position_event) = self.update_position(position, &fill_split1) {
5224            position_events.push(position_event);
5225        } else if !position
5226            .events
5227            .last()
5228            .is_some_and(|event| event.event_id == fill_split1.event_id)
5229        {
5230            return position_events;
5231        }
5232
5233        // Snapshot closed position before reusing ID (NETTING mode)
5234        if oms_type == OmsType::Netting
5235            && let Err(e) = self.snapshot_position(position)
5236        {
5237            log::warn!("Failed to snapshot position during flip: {e:?}");
5238        }
5239
5240        if oms_type == OmsType::Hedging
5241            && let Some(position_id) = fill.position_id
5242            && position_id.is_virtual()
5243        {
5244            log::warn!("Closing position {fill_split1}");
5245            log::warn!("Flipping position {fill_split2}");
5246        }
5247
5248        // Open flipped position
5249        let prior_position_id =
5250            (fill_split2.position_id == Some(position.id)).then_some(position.id);
5251
5252        match self.open_position(instrument, prior_position_id, false, fill_split2, oms_type) {
5253            Ok(opened_events) => position_events.extend(opened_events),
5254            Err(e) => log::error!("Failed to open flipped position: {e:?}"),
5255        }
5256
5257        position_events
5258    }
5259
5260    /// Sets the internal position ID generator counts based on existing cached positions.
5261    pub fn set_position_id_counts(&mut self) {
5262        let cache = self.cache.borrow();
5263        let positions = cache.positions(None, None, None, None, None);
5264
5265        // Count positions per instrument_id using a HashMap
5266        let mut counts: HashMap<StrategyId, usize> = HashMap::new();
5267
5268        for position in positions {
5269            *counts.entry(position.strategy_id).or_insert(0) += 1;
5270        }
5271
5272        self.pos_id_generator.reset();
5273
5274        for (strategy_id, count) in counts {
5275            self.pos_id_generator.set_count(count, strategy_id);
5276            log::info!("Set PositionId count for {strategy_id} to {count}");
5277        }
5278    }
5279
5280    fn deny_order(&self, order: &OrderAny, reason: &str) {
5281        let denied = OrderDenied::new(
5282            order.trader_id(),
5283            order.strategy_id(),
5284            order.instrument_id(),
5285            order.client_order_id(),
5286            reason.into(),
5287            UUID4::new(),
5288            self.clock.borrow().timestamp_ns(),
5289            self.clock.borrow().timestamp_ns(),
5290        );
5291
5292        let event = OrderEventAny::Denied(denied);
5293        let order = match self.cache.borrow_mut().update_order(&event) {
5294            Ok(order) => order,
5295            Err(e) => {
5296                log::error!("Failed to apply denied event to order: {e}");
5297                return;
5298            }
5299        };
5300
5301        let topic = switchboard::get_event_order_topic(order.strategy_id());
5302        msgbus::publish_order_event(topic, &event);
5303
5304        if self.config.snapshot_orders {
5305            self.create_order_state_snapshot(&order);
5306        }
5307    }
5308
5309    fn publish_absent_order_denial(&self, event: &OrderEventAny) -> bool {
5310        if matches!(
5311            event,
5312            OrderEventAny::ModifyDenied(_) | OrderEventAny::CancelDenied(_)
5313        ) && !self.cache.borrow().order_exists(&event.client_order_id())
5314        {
5315            self.publish_order_event(event);
5316            return true;
5317        }
5318
5319        false
5320    }
5321
5322    fn deny_modify_command(&self, command: &ModifyOrder, reason: &str) {
5323        let order = self
5324            .cache
5325            .borrow()
5326            .order(&command.client_order_id)
5327            .map(|order| order.clone());
5328        let ts_now = self.clock.borrow().timestamp_ns();
5329
5330        let mut event = OrderModifyDenied::new(
5331            order.as_ref().map_or(command.trader_id, Order::trader_id),
5332            order
5333                .as_ref()
5334                .map_or(command.strategy_id, Order::strategy_id),
5335            order
5336                .as_ref()
5337                .map_or(command.instrument_id, Order::instrument_id),
5338            command.client_order_id,
5339            reason.into(),
5340            UUID4::new(),
5341            ts_now,
5342            ts_now,
5343            order
5344                .as_ref()
5345                .and_then(Order::venue_order_id)
5346                .or(command.venue_order_id),
5347            order.as_ref().and_then(Order::account_id),
5348        );
5349        event.causation_id = Some(command.command_id);
5350        self.publish_command_denied(&OrderEventAny::ModifyDenied(event));
5351    }
5352
5353    fn deny_cancel_command(&self, command: &CancelOrder, reason: &str) {
5354        let order = self
5355            .cache
5356            .borrow()
5357            .order(&command.client_order_id)
5358            .map(|order| order.clone());
5359        let ts_now = self.clock.borrow().timestamp_ns();
5360
5361        let mut event = OrderCancelDenied::new(
5362            order.as_ref().map_or(command.trader_id, Order::trader_id),
5363            order
5364                .as_ref()
5365                .map_or(command.strategy_id, Order::strategy_id),
5366            order
5367                .as_ref()
5368                .map_or(command.instrument_id, Order::instrument_id),
5369            command.client_order_id,
5370            reason.into(),
5371            UUID4::new(),
5372            ts_now,
5373            ts_now,
5374            order
5375                .as_ref()
5376                .and_then(Order::venue_order_id)
5377                .or(command.venue_order_id),
5378            order.as_ref().and_then(Order::account_id),
5379        );
5380        event.causation_id = Some(command.command_id);
5381        self.publish_command_denied(&OrderEventAny::CancelDenied(event));
5382    }
5383
5384    fn publish_command_denied(&self, event: &OrderEventAny) {
5385        let order = if self.cache.borrow().order_exists(&event.client_order_id()) {
5386            match self.cache.borrow_mut().update_order(event) {
5387                Ok(order) => Some(order),
5388                Err(e) => {
5389                    log::error!("Failed to apply command denial: {e}");
5390                    return;
5391                }
5392            }
5393        } else {
5394            None
5395        };
5396
5397        self.send_order_update_to_portfolio(event);
5398        self.publish_order_event(event);
5399
5400        if self.config.snapshot_orders
5401            && let Some(order) = order
5402        {
5403            self.create_order_state_snapshot(&order);
5404        }
5405    }
5406
5407    fn get_or_init_own_order_book(&self, instrument_id: &InstrumentId) -> RefMut<'_, OwnOrderBook> {
5408        let mut cache = self.cache.borrow_mut();
5409        if cache.own_order_book_mut(instrument_id).is_none() {
5410            let own_book = OwnOrderBook::new(*instrument_id);
5411            cache
5412                .add_own_order_book(own_book)
5413                .expect("adding an own order book cannot fail");
5414        }
5415
5416        RefMut::map(cache, |c| {
5417            c.own_order_book_mut(instrument_id)
5418                .expect("own order book was ensured above")
5419        })
5420    }
5421}
5422
5423fn rescale_fill_void_qty(qty: Quantity, precision: u8) -> anyhow::Result<Quantity> {
5424    qty.checked_rescale(precision)
5425        .ok_or_else(|| anyhow::anyhow!("fill void quantity rescaling overflow or precision loss"))
5426}
5427
5428enum SubmissionValidationResult {
5429    Valid,
5430    StaleOrder {
5431        client_order_id: ClientOrderId,
5432        status: OrderStatus,
5433    },
5434    Dispatched {
5435        client_order_id: ClientOrderId,
5436    },
5437    Deny(OrderDeniedReason),
5438}
5439
5440#[cfg(test)]
5441mod tests {
5442    use nautilus_common::{
5443        clock::VirtualClock,
5444        msgbus::{MessageBus, set_message_bus},
5445    };
5446    use nautilus_model::{
5447        accounts::CashAccount,
5448        enums::{LiquiditySide, OrderSide, OrderType, PositionSide},
5449        events::{
5450            OrderFillVoided,
5451            order::spec::{OrderCanceledSpec, OrderFillVoidedSpec, OrderFilledSpec},
5452        },
5453        identifiers::{AccountId, ClientOrderId, TradeId, VenueOrderId},
5454        instruments::{InstrumentAny, stubs::audusd_sim},
5455        orders::{builder::OrderTestBuilder, stubs::TestOrderEventStubs},
5456        position::PositionFillVoid,
5457        types::Price,
5458    };
5459    use rstest::*;
5460
5461    use super::*;
5462
5463    #[cfg(feature = "high-precision")]
5464    #[rstest]
5465    fn open_position_rejects_unrepresentable_cost_without_mutating_cache() {
5466        let cache = Rc::new(RefCell::new(Cache::default()));
5467
5468        let engine = ExecutionEngine::new(
5469            Rc::new(RefCell::new(VirtualClock::new())),
5470            cache.clone(),
5471            None,
5472        );
5473        let instrument = InstrumentAny::CurrencyPair(audusd_sim());
5474        let position_id = PositionId::from("P-COST-UNDERFLOW");
5475        let fill = OrderFilledSpec::builder()
5476            .instrument_id(instrument.id())
5477            .position_id(position_id)
5478            .last_qty(Quantity::from("0.0000000000000001"))
5479            .last_px(Price::from("0.0000000000000001"))
5480            .build();
5481
5482        let result = engine.open_position(&instrument, None, false, fill, OmsType::Netting);
5483
5484        assert_eq!(
5485            result.unwrap_err().to_string(),
5486            "position proportional arithmetic underflow"
5487        );
5488        assert!(cache.borrow().position(&position_id).is_none());
5489        assert_eq!(
5490            cache
5491                .borrow()
5492                .positions_total_count(None, None, None, None, None),
5493            0
5494        );
5495    }
5496
5497    #[cfg(feature = "high-precision")]
5498    #[rstest]
5499    #[case::closing("0.0000000000000001", "1.0000000000000001", "0.0000000000000001")]
5500    #[case::opening("1", "1.0000000000000001", "0.0000000000000001")]
5501    #[case::split("1", "9999999999999.9999999999999999", "0.1234567890123456")]
5502    fn flip_position_rejection_preserves_open_position(
5503        #[case] qty: &str,
5504        #[case] last_qty: &str,
5505        #[case] last_px: &str,
5506    ) {
5507        let cache = Rc::new(RefCell::new(Cache::default()));
5508
5509        let mut engine = ExecutionEngine::new(
5510            Rc::new(RefCell::new(VirtualClock::new())),
5511            cache.clone(),
5512            None,
5513        );
5514        let instrument = InstrumentAny::CurrencyPair(audusd_sim());
5515        let opening = OrderFilledSpec::builder()
5516            .instrument_id(instrument.id())
5517            .position_id(PositionId::from("P-FLIP-REJECT"))
5518            .last_qty(Quantity::from(qty))
5519            .last_px(Price::from("1.00000"))
5520            .build();
5521        let mut position = Position::new(&instrument, opening.clone());
5522        let before = serde_json::to_value(&position).unwrap();
5523        cache
5524            .borrow_mut()
5525            .add_position(&position, OmsType::Netting)
5526            .unwrap();
5527        let mut reversing = opening;
5528        reversing.trade_id = TradeId::from("T-FLIP-REJECT");
5529        reversing.event_id = UUID4::new();
5530        reversing.order_side = OrderSide::Sell;
5531        reversing.last_qty = Quantity::from(last_qty);
5532        reversing.last_px = Price::from(last_px);
5533
5534        let events = engine.flip_position(&instrument, &mut position, &reversing, OmsType::Netting);
5535
5536        assert!(events.is_empty());
5537        assert_eq!(serde_json::to_value(&position).unwrap(), before);
5538        assert_eq!(
5539            serde_json::to_value(&*cache.borrow().position(&position.id).unwrap()).unwrap(),
5540            before
5541        );
5542        assert!(
5543            cache
5544                .borrow()
5545                .position_snapshots(Some(&position.id), None)
5546                .is_empty()
5547        );
5548        assert!(cache.borrow().is_position_open(&position.id));
5549        assert!(!cache.borrow().is_position_closed(&position.id));
5550    }
5551
5552    #[rstest]
5553    fn netting_positions_open_for_report_scopes_positions_by_account() {
5554        let instrument = InstrumentAny::CurrencyPair(audusd_sim());
5555        let account1_id = AccountId::from("SIM-001");
5556        let account2_id = AccountId::from("SIM-002");
5557        let position1 = position_for_account(
5558            &instrument,
5559            account1_id,
5560            StrategyId::from("S-001"),
5561            PositionId::from("P-ACC-1"),
5562            OrderSide::Buy,
5563            Quantity::from(1_000),
5564        );
5565        let position2 = position_for_account(
5566            &instrument,
5567            account2_id,
5568            StrategyId::from("S-002"),
5569            PositionId::from("P-ACC-2"),
5570            OrderSide::Buy,
5571            Quantity::from(2_000),
5572        );
5573        let mut cache = Cache::default();
5574        cache.add_position(&position1, OmsType::Netting).unwrap();
5575        cache.add_position(&position2, OmsType::Netting).unwrap();
5576
5577        let report = PositionStatusReport::new(
5578            account1_id,
5579            instrument.id(),
5580            PositionSide::Long,
5581            Quantity::from(1_000),
5582            UnixNanos::from(1_000_000),
5583            UnixNanos::from(1_000_000),
5584            None,
5585            None,
5586            None,
5587        );
5588
5589        let positions_open = ExecutionEngine::netting_positions_open_for_report(&cache, &report);
5590        let signed_qty: Decimal = positions_open
5591            .iter()
5592            .map(|position| ExecutionEngine::position_signed_decimal_qty(position))
5593            .sum();
5594
5595        assert_eq!(positions_open.len(), 1);
5596        assert_eq!(positions_open[0].id, position1.id);
5597        assert_eq!(signed_qty, Decimal::from(1_000));
5598    }
5599
5600    #[rstest]
5601    fn netting_split_position_ownership_message_reports_only_split_ownership() {
5602        let instrument = InstrumentAny::CurrencyPair(audusd_sim());
5603        let account_id = AccountId::from("SIM-001");
5604        let external_position = position_for_account(
5605            &instrument,
5606            account_id,
5607            StrategyId::from("EXTERNAL"),
5608            PositionId::from("P-EXTERNAL"),
5609            OrderSide::Buy,
5610            Quantity::from(1_000),
5611        );
5612        let strategy_position = position_for_account(
5613            &instrument,
5614            account_id,
5615            StrategyId::from("S-001"),
5616            PositionId::from("P-STRATEGY"),
5617            OrderSide::Buy,
5618            Quantity::from(500),
5619        );
5620        let same_strategy_position = position_for_account(
5621            &instrument,
5622            account_id,
5623            StrategyId::from("EXTERNAL"),
5624            PositionId::from("P-EXTERNAL-2"),
5625            OrderSide::Buy,
5626            Quantity::from(250),
5627        );
5628        let report = PositionStatusReport::new(
5629            account_id,
5630            instrument.id(),
5631            PositionSide::Long,
5632            Quantity::from(1_500),
5633            UnixNanos::from(1_000_000),
5634            UnixNanos::from(1_000_000),
5635            None,
5636            None,
5637            None,
5638        );
5639
5640        let message = ExecutionEngine::netting_split_position_ownership_message(
5641            &report,
5642            &[&external_position, &strategy_position],
5643        )
5644        .expect("split ownership should produce a warning message");
5645
5646        assert!(message.contains("account_id=SIM-001"));
5647        assert!(message.contains(&format!("instrument_id={}", instrument.id())));
5648        assert!(message.contains("EXTERNAL"));
5649        assert!(message.contains("S-001"));
5650        assert!(message.contains("P-EXTERNAL"));
5651        assert!(message.contains("P-STRATEGY"));
5652        assert!(message.contains("signed_qty=1000"));
5653        assert!(message.contains("signed_qty=500"));
5654        assert!(
5655            ExecutionEngine::netting_split_position_ownership_message(
5656                &report,
5657                &[&external_position, &same_strategy_position],
5658            )
5659            .is_none()
5660        );
5661    }
5662
5663    #[rstest]
5664    fn materialize_external_order_rejects_venue_id_owned_by_another_order() {
5665        let cache = Rc::new(RefCell::new(Cache::default()));
5666        let venue_order_id = VenueOrderId::from("V-SHARED");
5667        let owner_id = ClientOrderId::from("O-OWNER");
5668        cache
5669            .borrow_mut()
5670            .add_venue_order_id(&owner_id, &venue_order_id, false)
5671            .unwrap();
5672        let engine = ExecutionEngine::new(
5673            Rc::new(RefCell::new(VirtualClock::new())),
5674            Rc::clone(&cache),
5675            None,
5676        );
5677        let instrument = InstrumentAny::CurrencyPair(audusd_sim());
5678        let claimant_id = ClientOrderId::from("O-CLAIMANT");
5679        let order = OrderTestBuilder::new(OrderType::Limit)
5680            .instrument_id(instrument.id())
5681            .client_order_id(claimant_id)
5682            .side(OrderSide::Buy)
5683            .quantity(Quantity::from(100_000))
5684            .price(Price::from("1.00000"))
5685            .build();
5686        let OrderEventAny::Initialized(initialized) = order.last_event().clone() else {
5687            panic!("Expected initialized order");
5688        };
5689
5690        let result = engine.materialize_external_order(initialized, venue_order_id, None, None);
5691
5692        assert!(result.is_none());
5693        assert!(!cache.borrow().order_exists(&claimant_id));
5694        assert_eq!(
5695            cache.borrow().client_order_id(&venue_order_id),
5696            Some(&owner_id)
5697        );
5698        assert_eq!(cache.borrow().venue_order_id(&claimant_id), None);
5699    }
5700
5701    #[rstest]
5702    fn carry_replay_reopen_transfers_history_allocations() {
5703        let instrument = InstrumentAny::CurrencyPair(audusd_sim());
5704        let position_id = PositionId::from("P-REOPEN-TRANSFER");
5705        let opening = position_fill(
5706            &instrument,
5707            position_id,
5708            "O-OPEN",
5709            "T-OPEN",
5710            OrderSide::Buy,
5711            10,
5712            1,
5713        );
5714        let closing = position_fill(
5715            &instrument,
5716            position_id,
5717            "O-CLOSE",
5718            "T-CLOSE",
5719            OrderSide::Sell,
5720            10,
5721            2,
5722        );
5723        let reopening = position_fill(
5724            &instrument,
5725            position_id,
5726            "O-REOPEN",
5727            "T-REOPEN",
5728            OrderSide::Buy,
5729            10,
5730            3,
5731        );
5732        let mut position = Position::new(&instrument, opening.clone());
5733        position.apply(&closing);
5734
5735        let fill_voided = OrderFillVoidedSpec::builder()
5736            .trader_id(opening.trader_id)
5737            .strategy_id(opening.strategy_id)
5738            .instrument_id(opening.instrument_id)
5739            .client_order_id(opening.client_order_id)
5740            .venue_order_id(opening.venue_order_id)
5741            .account_id(opening.account_id)
5742            .correction_id("C-TRANSFER".into())
5743            .trade_id(opening.trade_id)
5744            .voided_qty(Quantity::from(1))
5745            .order_side(opening.order_side)
5746            .order_type(opening.order_type)
5747            .last_px(opening.last_px)
5748            .currency(opening.currency)
5749            .liquidity_side(opening.liquidity_side)
5750            .maybe_position_id(opening.position_id)
5751            .event_id(UUID4::new())
5752            .ts_event(UnixNanos::from(4))
5753            .ts_init(UnixNanos::from(4))
5754            .build();
5755        position.fill_voids.push(PositionFillVoid {
5756            event: fill_voided,
5757            voided_qty: Quantity::from(1),
5758            commission_voided: None,
5759        });
5760
5761        let cache = Rc::new(RefCell::new(Cache::default()));
5762        cache
5763            .borrow_mut()
5764            .add_position_without_order(&position, OmsType::Netting)
5765            .unwrap();
5766        {
5767            let mut cached = cache.borrow_mut();
5768            let mut position = cached.position_mut(&position_id).unwrap();
5769            position.replay_events.reserve(8);
5770            position.fill_voids.reserve(4);
5771        }
5772        let (replay_ptr, void_ptr, replay_len, void_len, replay_before, voids_before) = {
5773            let cache = cache.borrow();
5774            let position = cache.position(&position_id).unwrap();
5775            (
5776                position.replay_events.as_ptr(),
5777                position.fill_voids.as_ptr(),
5778                position.replay_events.len(),
5779                position.fill_voids.len(),
5780                serde_json::to_value(&position.replay_events).unwrap(),
5781                serde_json::to_value(&position.fill_voids).unwrap(),
5782            )
5783        };
5784        let config = ExecutionEngineConfig::builder()
5785            .carry_replay_events_on_reopen(true)
5786            .build()
5787            .unwrap();
5788        let mut engine = ExecutionEngine::new(
5789            Rc::new(RefCell::new(VirtualClock::new())),
5790            Rc::clone(&cache),
5791            Some(config),
5792        );
5793
5794        let events = engine.handle_position_update(&instrument, reopening, OmsType::Netting);
5795
5796        assert_eq!(events.len(), 1);
5797        let cache = cache.borrow();
5798        let position = cache.position(&position_id).unwrap();
5799        assert_eq!(position.replay_events.as_ptr(), replay_ptr);
5800        assert_eq!(position.fill_voids.as_ptr(), void_ptr);
5801        assert_eq!(position.replay_events.len(), replay_len + 1);
5802        assert_eq!(position.fill_voids.len(), void_len);
5803        assert_eq!(
5804            serde_json::to_value(&position.replay_events[..replay_len]).unwrap(),
5805            replay_before,
5806        );
5807        assert_eq!(
5808            serde_json::to_value(&position.fill_voids).unwrap(),
5809            voids_before
5810        );
5811        assert!(matches!(
5812            &position.replay_events[0],
5813            PositionReplayEvent::Filled(fill) if fill.event_id == opening.event_id
5814        ));
5815    }
5816
5817    #[rstest]
5818    fn position_opened_uses_state_captured_before_snapshot_subscriber() {
5819        let instrument = InstrumentAny::CurrencyPair(audusd_sim());
5820        let position_id = PositionId::from("P-SNAPSHOT-SUBSCRIBER");
5821        let fill = position_fill(
5822            &instrument,
5823            position_id,
5824            "O-SNAPSHOT-SUBSCRIBER",
5825            "T-SNAPSHOT-SUBSCRIBER",
5826            OrderSide::Buy,
5827            10,
5828            1,
5829        );
5830        let cache = Rc::new(RefCell::new(Cache::default()));
5831        let config = ExecutionEngineConfig::builder()
5832            .snapshot_positions(true)
5833            .build()
5834            .unwrap();
5835        let engine = ExecutionEngine::new(
5836            Rc::new(RefCell::new(VirtualClock::new())),
5837            Rc::clone(&cache),
5838            Some(config),
5839        );
5840        set_message_bus(Rc::new(RefCell::new(MessageBus::default())));
5841        let subscriber_cache = Rc::clone(&cache);
5842        let topic = switchboard::get_snapshot_position_topic(position_id);
5843        msgbus::subscribe_any(
5844            topic.as_str().into(),
5845            TypedHandler::from_typed::<PositionStateSnapshot, _>(move |_| {
5846                subscriber_cache
5847                    .borrow_mut()
5848                    .position_mut(&position_id)
5849                    .unwrap()
5850                    .quantity = Quantity::from(99);
5851            }),
5852            None,
5853        );
5854
5855        let events = engine
5856            .open_position(&instrument, None, true, fill.clone(), OmsType::Netting)
5857            .unwrap();
5858
5859        assert_eq!(
5860            cache.borrow().position(&position_id).unwrap().quantity,
5861            Quantity::from(99)
5862        );
5863        let [PositionEvent::PositionOpened(opened)] = events.as_slice() else {
5864            panic!("Expected one position-opened event");
5865        };
5866        assert_eq!(opened.position_id, position_id);
5867        assert_eq!(opened.opening_order_id, fill.client_order_id);
5868        assert_eq!(opened.quantity, fill.last_qty);
5869        assert_eq!(opened.last_px, fill.last_px);
5870    }
5871
5872    fn position_fill(
5873        instrument: &InstrumentAny,
5874        position_id: PositionId,
5875        order_id: &str,
5876        trade_id: &str,
5877        order_side: OrderSide,
5878        quantity: u32,
5879        ts_event: u64,
5880    ) -> OrderFilled {
5881        OrderFilledSpec::builder()
5882            .instrument_id(instrument.id())
5883            .client_order_id(ClientOrderId::from(order_id))
5884            .venue_order_id(VenueOrderId::from(order_id))
5885            .trade_id(TradeId::from(trade_id))
5886            .order_side(order_side)
5887            .last_qty(Quantity::from(quantity))
5888            .last_px(Price::from("1.00000"))
5889            .currency(instrument.quote_currency())
5890            .liquidity_side(LiquiditySide::Maker)
5891            .position_id(position_id)
5892            .ts_event(UnixNanos::from(ts_event))
5893            .build()
5894    }
5895
5896    fn position_for_account(
5897        instrument: &InstrumentAny,
5898        account_id: AccountId,
5899        strategy_id: StrategyId,
5900        position_id: PositionId,
5901        order_side: OrderSide,
5902        quantity: Quantity,
5903    ) -> Position {
5904        let client_order_id = ClientOrderId::from(format!("O-{position_id}"));
5905        let fill = OrderFilledSpec::builder()
5906            .strategy_id(strategy_id)
5907            .instrument_id(instrument.id())
5908            .client_order_id(client_order_id)
5909            .venue_order_id(VenueOrderId::from(format!("V-{position_id}")))
5910            .account_id(account_id)
5911            .trade_id(TradeId::new(format!("T-{position_id}")))
5912            .order_side(order_side)
5913            .last_qty(quantity)
5914            .last_px(Price::from("1.0"))
5915            .currency(instrument.quote_currency())
5916            .liquidity_side(LiquiditySide::Maker)
5917            .position_id(position_id)
5918            .commission(Money::from("2 USD"))
5919            .build();
5920
5921        Position::new(instrument, fill)
5922    }
5923
5924    #[rstest]
5925    fn declined_fill_and_void_publish_negative_acknowledgment() {
5926        let (mut engine, instrument, nacks) = nack_engine();
5927        let overfill = nack_order_fill(&instrument, "T-OVERFILL", Quantity::from(200));
5928        let valid = nack_order_fill(&instrument, "T-VALID", Quantity::from(50));
5929        let zero_void = nack_order_fill_void(&valid, Quantity::from(0));
5930
5931        engine.process(&OrderEventAny::Filled(overfill.clone()));
5932        engine.process(&OrderEventAny::Filled(valid.clone()));
5933        // A declined reconciliation projection is not an enqueued client event, so no NACK
5934        engine.project_reconciliation_fill(&valid);
5935        engine.process(&OrderEventAny::FillVoided(zero_void.clone()));
5936
5937        assert_eq!(
5938            *nacks.borrow(),
5939            vec![
5940                OrderEventAny::Filled(overfill),
5941                OrderEventAny::FillVoided(zero_void),
5942            ]
5943        );
5944    }
5945
5946    #[derive(Debug, Clone, Copy)]
5947    enum DeclineCase {
5948        ZeroQuantityFill,
5949        DuplicateFill,
5950        DuplicateVoid,
5951        UnknownOrderFill,
5952        UnknownOrderCancel,
5953    }
5954
5955    #[rstest]
5956    #[case::zero_quantity_fill(DeclineCase::ZeroQuantityFill)]
5957    #[case::duplicate_fill(DeclineCase::DuplicateFill)]
5958    #[case::duplicate_void(DeclineCase::DuplicateVoid)]
5959    #[case::unknown_order_fill(DeclineCase::UnknownOrderFill)]
5960    #[case::unknown_order_cancel(DeclineCase::UnknownOrderCancel)]
5961    fn declined_order_event_negative_acknowledgment(#[case] case: DeclineCase) {
5962        let (mut engine, instrument, nacks) = nack_engine();
5963        let fill = nack_order_fill(&instrument, "T-CASE", Quantity::from(50));
5964
5965        let (events, expected) = match case {
5966            DeclineCase::ZeroQuantityFill => {
5967                let zero = OrderEventAny::Filled(nack_order_fill(
5968                    &instrument,
5969                    "T-ZERO",
5970                    Quantity::from(0),
5971                ));
5972                (vec![zero.clone()], vec![zero])
5973            }
5974            DeclineCase::DuplicateFill => {
5975                let filled = OrderEventAny::Filled(fill);
5976                (vec![filled.clone(), filled.clone()], vec![filled])
5977            }
5978            DeclineCase::DuplicateVoid => {
5979                let voided = OrderEventAny::FillVoided(nack_order_fill_void(&fill, fill.last_qty));
5980                (
5981                    vec![OrderEventAny::Filled(fill), voided.clone(), voided.clone()],
5982                    vec![voided],
5983                )
5984            }
5985            DeclineCase::UnknownOrderFill => {
5986                let mut unknown = fill;
5987                unknown.client_order_id = ClientOrderId::from("O-UNKNOWN");
5988                unknown.venue_order_id = VenueOrderId::from("V-UNKNOWN");
5989                let filled = OrderEventAny::Filled(unknown);
5990                (vec![filled.clone()], vec![filled])
5991            }
5992            // Only fills and voids are awaited by clients, so other declined events never NACK
5993            DeclineCase::UnknownOrderCancel => {
5994                let canceled = OrderCanceledSpec::builder()
5995                    .instrument_id(instrument.id())
5996                    .client_order_id(ClientOrderId::from("O-UNKNOWN"))
5997                    .venue_order_id(VenueOrderId::from("V-UNKNOWN"))
5998                    .account_id(fill.account_id)
5999                    .build();
6000                (vec![OrderEventAny::Canceled(canceled)], Vec::new())
6001            }
6002        };
6003
6004        for event in &events {
6005            engine.process(event);
6006        }
6007
6008        assert_eq!(*nacks.borrow(), expected);
6009    }
6010
6011    // Engine holding one accepted BUY 100 limit order O-NACK (venue V-NACK), with a recorder of
6012    // every event republished on the fill-declined topics
6013    fn nack_engine() -> (
6014        ExecutionEngine,
6015        InstrumentAny,
6016        Rc<RefCell<Vec<OrderEventAny>>>,
6017    ) {
6018        let instrument = InstrumentAny::CurrencyPair(audusd_sim());
6019        let cache = Rc::new(RefCell::new(Cache::default()));
6020        cache
6021            .borrow_mut()
6022            .add_instrument(instrument.clone())
6023            .unwrap();
6024        cache
6025            .borrow_mut()
6026            .add_account(CashAccount::default().into())
6027            .unwrap();
6028
6029        let engine = ExecutionEngine::new(
6030            Rc::new(RefCell::new(VirtualClock::new())),
6031            Rc::clone(&cache),
6032            None,
6033        );
6034        set_message_bus(Rc::new(RefCell::new(MessageBus::default())));
6035
6036        let order = OrderTestBuilder::new(OrderType::Limit)
6037            .instrument_id(instrument.id())
6038            .client_order_id(ClientOrderId::from("O-NACK"))
6039            .side(OrderSide::Buy)
6040            .quantity(Quantity::from(100))
6041            .price(Price::from("1.00000"))
6042            .build();
6043        cache
6044            .borrow_mut()
6045            .add_order(order.clone(), None, None, false)
6046            .unwrap();
6047        let account_id = AccountId::from("SIM-001");
6048        let submitted = TestOrderEventStubs::submitted(&order, account_id);
6049        cache.borrow_mut().update_order(&submitted).unwrap();
6050        let accepted =
6051            TestOrderEventStubs::accepted(&order, account_id, VenueOrderId::from("V-NACK"));
6052        cache.borrow_mut().update_order(&accepted).unwrap();
6053
6054        let nacks: Rc<RefCell<Vec<OrderEventAny>>> = Rc::new(RefCell::new(Vec::new()));
6055        let capture = Rc::clone(&nacks);
6056        msgbus::subscribe_order_events(
6057            "events.order_fill_declined.*".into(),
6058            TypedHandler::from(move |event: &OrderEventAny| {
6059                capture.borrow_mut().push(event.clone());
6060            }),
6061            None,
6062        );
6063
6064        (engine, instrument, nacks)
6065    }
6066
6067    fn nack_order_fill(
6068        instrument: &InstrumentAny,
6069        trade_id: &str,
6070        last_qty: Quantity,
6071    ) -> OrderFilled {
6072        OrderFilledSpec::builder()
6073            .instrument_id(instrument.id())
6074            .client_order_id(ClientOrderId::from("O-NACK"))
6075            .venue_order_id(VenueOrderId::from("V-NACK"))
6076            .account_id(AccountId::from("SIM-001"))
6077            .trade_id(TradeId::from(trade_id))
6078            .order_side(OrderSide::Buy)
6079            .order_type(OrderType::Limit)
6080            .last_qty(last_qty)
6081            .last_px(Price::from("1.00000"))
6082            .currency(instrument.quote_currency())
6083            .liquidity_side(LiquiditySide::Taker)
6084            .build()
6085    }
6086
6087    fn nack_order_fill_void(fill: &OrderFilled, voided_qty: Quantity) -> OrderFillVoided {
6088        OrderFillVoidedSpec::builder()
6089            .trader_id(fill.trader_id)
6090            .strategy_id(fill.strategy_id)
6091            .instrument_id(fill.instrument_id)
6092            .client_order_id(fill.client_order_id)
6093            .venue_order_id(fill.venue_order_id)
6094            .account_id(fill.account_id)
6095            .trade_id(fill.trade_id)
6096            .voided_qty(voided_qty)
6097            .order_side(fill.order_side)
6098            .order_type(fill.order_type)
6099            .last_px(fill.last_px)
6100            .currency(fill.currency)
6101            .liquidity_side(fill.liquidity_side)
6102            .build()
6103    }
6104}