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