1use std::{cell::RefCell, collections::BinaryHeap, fmt::Debug, rc::Rc};
19
20use ahash::{AHashMap, AHashSet};
21use async_trait::async_trait;
22use nautilus_common::{
23 cache::Cache,
24 clients::{ExecutionClient, generate_mass_status},
25 clock::Clock,
26 factories::OrderEventFactory,
27 live::try_get_exec_event_sender,
28 messages::{
29 ExecutionEvent,
30 execution::{
31 BatchCancelOrders, BatchModifyOrders, CancelAllOrders, CancelOrder,
32 GenerateFillReports, GenerateOrderStatusReport, GenerateOrderStatusReports,
33 GeneratePositionStatusReports, ModifyOrder, QueryAccount, QueryOrder, SubmitOrder,
34 SubmitOrderList, TradingCommand,
35 },
36 },
37 msgbus::{
38 self, MStr, MessagingSwitchboard, Pattern, TypedHandler,
39 typed_handler::ShareableMessageHandler,
40 },
41 timer::{TimeEvent, TimeEventCallback},
42};
43use nautilus_core::{DurationNanos, Params, UUID4, UnixNanos, WeakCell};
44use nautilus_execution::{
45 client::core::ExecutionClientCore,
46 matching_engine::{
47 OrderMatchingEngine,
48 inflight::InflightOrders,
49 orders::{MatchingOrders, OtoCommand},
50 },
51 models::{fee::FeeModelHandle, fill::FillModelHandle, latency::LatencyModel},
52};
53use nautilus_model::{
54 accounts::AccountAny,
55 data::{
56 Bar, InstrumentClose, InstrumentStatus, OrderBookDeltas, OrderBookDepth, QuoteTick,
57 TradeTick,
58 },
59 enums::OmsType,
60 events::{OrderCancelDenied, OrderEventAny, OrderModifyDenied, OrderRejected, PositionEvent},
61 identifiers::{AccountId, ClientId, ClientOrderId, InstrumentId, Venue},
62 instruments::{Instrument, InstrumentAny},
63 orders::{Order, OrderAny},
64 reports::{ExecutionMassStatus, FillReport, OrderStatusReport, PositionStatusReport},
65 types::{AccountBalance, MarginBalance, Money},
66};
67use ustr::Ustr;
68
69use crate::config::SandboxExecutionClientConfig;
70
71const EXPIRED_ENGINE_SWEEP_INTERVAL: DurationNanos = DurationNanos::from_mins(1);
73
74pub struct SandboxExecutionClient {
83 core: RefCell<ExecutionClientCore>,
84 factory: OrderEventFactory,
85 config: SandboxExecutionClientConfig,
86 inner: Rc<RefCell<SandboxInner>>,
87 handlers: RefCell<Option<RegisteredHandlers>>,
88 clock: Rc<RefCell<dyn Clock>>,
89 cache: Rc<RefCell<Cache>>,
90}
91
92struct RegisteredHandlers {
93 deltas_pattern: MStr<Pattern>,
94 deltas_handler: TypedHandler<OrderBookDeltas>,
95 depth_pattern: MStr<Pattern>,
96 depth_handler: TypedHandler<OrderBookDepth>,
97 quote_pattern: MStr<Pattern>,
98 quote_handler: TypedHandler<QuoteTick>,
99 trade_pattern: MStr<Pattern>,
100 trade_handler: TypedHandler<TradeTick>,
101 bar_pattern: MStr<Pattern>,
102 bar_handler: TypedHandler<Bar>,
103 status_pattern: MStr<Pattern>,
104 status_handler: ShareableMessageHandler,
105 close_pattern: MStr<Pattern>,
106 close_handler: ShareableMessageHandler,
107 position_pattern: MStr<Pattern>,
108 position_handler: TypedHandler<PositionEvent>,
109}
110
111impl Debug for SandboxExecutionClient {
112 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113 f.debug_struct(stringify!(SandboxExecutionClient))
114 .field("venue", &self.config.venue)
115 .field("account_id", &self.core.borrow().account_id)
116 .field("connected", &self.core.borrow().is_connected())
117 .field(
118 "matching_engines",
119 &self.inner.borrow().matching_engines.len(),
120 )
121 .finish()
122 }
123}
124
125impl SandboxExecutionClient {
126 pub fn new(
137 core: ExecutionClientCore,
138 config: SandboxExecutionClientConfig,
139 clock: Rc<RefCell<dyn Clock>>,
140 cache: Rc<RefCell<Cache>>,
141 ) -> anyhow::Result<Self> {
142 config.validate()?;
143
144 let fee_model = config.fee_model.clone().map(FeeModelHandle::from).ok_or_else(|| {
145 anyhow::anyhow!(
146 "SandboxExecutionClientConfig requires an explicit fee_model, including an explicit zero-fee model"
147 )
148 })?;
149
150 Self::new_with_fee_model(core, config, clock, cache, fee_model)
151 }
152
153 pub fn new_with_fee_model(
162 core: ExecutionClientCore,
163 config: SandboxExecutionClientConfig,
164 clock: Rc<RefCell<dyn Clock>>,
165 cache: Rc<RefCell<Cache>>,
166 fee_model: FeeModelHandle,
167 ) -> anyhow::Result<Self> {
168 config.validate()?;
169
170 let mut balances = AHashMap::new();
171 for money in &config.starting_balances {
172 balances.insert(money.currency.code.to_string(), *money);
173 }
174
175 let fill_model = config
176 .fill_model
177 .clone()
178 .map_or_default(FillModelHandle::from);
179
180 let inner = Rc::new_cyclic(|weak: &std::rc::Weak<RefCell<SandboxInner>>| {
181 RefCell::new(SandboxInner {
182 clock: clock.clone(),
183 cache: cache.clone(),
184 config: config.clone(),
185 fill_model,
186 fee_model,
187 matching_engines: AHashMap::new(),
188 next_engine_raw_id: 0,
189 balances,
190 event_handler: None,
191 inbound_queue: BinaryHeap::new(),
192 inflight_orders: InflightOrders::default(),
193 matching_orders: MatchingOrders::default(),
194 inbound_seq: 0,
195 client_id: core.client_id,
196 account_id: core.account_id,
197 self_weak: WeakCell::from(weak.clone()),
198 })
199 });
200
201 let factory = OrderEventFactory::new(
202 core.trader_id,
203 core.account_id,
204 core.account_type,
205 core.base_currency,
206 );
207
208 Ok(Self {
209 core: RefCell::new(core),
210 factory,
211 config,
212 inner,
213 handlers: RefCell::new(None),
214 clock,
215 cache,
216 })
217 }
218
219 #[must_use]
221 pub const fn config(&self) -> &SandboxExecutionClientConfig {
222 &self.config
223 }
224
225 #[must_use]
227 pub fn matching_engine_count(&self) -> usize {
228 self.inner.borrow().matching_engines.len()
229 }
230
231 fn dispatch_order_event(&self, event: OrderEventAny) {
232 self.inner.borrow().dispatch_order_event(event);
233 }
234
235 fn register_message_handlers(&self) {
236 if self.handlers.borrow().is_some() {
237 log::warn!("Sandbox message handlers already registered");
238 return;
239 }
240
241 let inner_weak = WeakCell::from(Rc::downgrade(&self.inner));
242 let venue = self.config.venue;
243
244 let deltas_handler = {
245 let inner = inner_weak.clone();
246 TypedHandler::from(move |deltas: &OrderBookDeltas| {
247 if deltas.instrument_id.venue == venue
248 && let Some(inner_rc) = inner.upgrade()
249 {
250 SandboxInner::on_order_book_deltas(&inner_rc, deltas);
251 }
252 })
253 };
254
255 let depth_handler = {
256 let inner = inner_weak.clone();
257 TypedHandler::from(move |depth: &OrderBookDepth| {
258 SandboxInner::on_order_book_depth(&inner, venue, depth);
259 })
260 };
261
262 let quote_handler = {
263 let inner = inner_weak.clone();
264 TypedHandler::from(move |quote: &QuoteTick| {
265 if quote.instrument_id.venue == venue
266 && let Some(inner_rc) = inner.upgrade()
267 {
268 SandboxInner::on_quote_tick(&inner_rc, quote);
269 }
270 })
271 };
272
273 let trade_handler = {
274 let inner = inner_weak.clone();
275 TypedHandler::from(move |trade: &TradeTick| {
276 if trade.instrument_id.venue == venue
277 && let Some(inner_rc) = inner.upgrade()
278 {
279 SandboxInner::on_trade_tick(&inner_rc, trade);
280 }
281 })
282 };
283
284 let bar_handler = {
286 let inner = inner_weak.clone();
287 TypedHandler::from(move |bar: &Bar| {
288 if bar.bar_type.instrument_id().venue == venue
289 && let Some(inner_rc) = inner.upgrade()
290 {
291 SandboxInner::on_bar(&inner_rc, bar);
292 }
293 })
294 };
295
296 let status_handler = {
297 let inner = inner_weak.clone();
298 ShareableMessageHandler::from_typed(move |status: &InstrumentStatus| {
299 if status.instrument_id.venue == venue
300 && let Some(inner_rc) = inner.upgrade()
301 {
302 SandboxInner::on_instrument_status(&inner_rc, status);
303 }
304 })
305 };
306
307 let close_handler = {
308 let inner = inner_weak.clone();
309 ShareableMessageHandler::from_typed(move |close: &InstrumentClose| {
310 if close.instrument_id.venue == venue
311 && let Some(inner_rc) = inner.upgrade()
312 {
313 SandboxInner::on_instrument_close(&inner_rc, close);
314 }
315 })
316 };
317
318 let position_handler = {
319 TypedHandler::from(move |event: &PositionEvent| {
320 if let Some(inner_rc) = inner_weak.upgrade() {
321 SandboxInner::on_position_event(&inner_rc, event);
322 }
323 })
324 };
325
326 let deltas_pattern: MStr<Pattern> = format!("data.book.deltas.{venue}.*").into();
327 let depth_pattern: MStr<Pattern> = format!("data.book.depth.{venue}.*").into();
328 let quote_pattern: MStr<Pattern> = format!("data.quotes.{venue}.*").into();
329 let trade_pattern: MStr<Pattern> = format!("data.trades.{venue}.*").into();
330 let bar_pattern: MStr<Pattern> = "data.bars.*".into();
331 let status_pattern: MStr<Pattern> = format!("data.status.{venue}.*").into();
332 let close_pattern: MStr<Pattern> = format!("data.close.{venue}.*").into();
333 let position_pattern: MStr<Pattern> = "events.position.*".into();
334
335 msgbus::subscribe_book_deltas(deltas_pattern, deltas_handler.clone(), Some(10));
336 msgbus::subscribe_book_depth(depth_pattern, depth_handler.clone(), Some(10));
337 msgbus::subscribe_quotes(quote_pattern, quote_handler.clone(), Some(10));
338 msgbus::subscribe_trades(trade_pattern, trade_handler.clone(), Some(10));
339 msgbus::subscribe_bars(bar_pattern, bar_handler.clone(), Some(10));
340 msgbus::subscribe_any(status_pattern, status_handler.clone(), Some(10));
341 msgbus::subscribe_instrument_close(close_pattern, close_handler.clone(), Some(10));
342 msgbus::subscribe_position_events(position_pattern, position_handler.clone(), Some(10));
343
344 *self.handlers.borrow_mut() = Some(RegisteredHandlers {
345 deltas_pattern,
346 deltas_handler,
347 depth_pattern,
348 depth_handler,
349 quote_pattern,
350 quote_handler,
351 trade_pattern,
352 trade_handler,
353 bar_pattern,
354 bar_handler,
355 status_pattern,
356 status_handler,
357 close_pattern,
358 close_handler,
359 position_pattern,
360 position_handler,
361 });
362
363 log::debug!(
364 "Sandbox registered message handlers for venue={}",
365 self.config.venue
366 );
367 }
368
369 fn deregister_message_handlers(&self) {
370 if let Some(handlers) = self.handlers.borrow_mut().take() {
371 msgbus::unsubscribe_book_deltas(handlers.deltas_pattern, &handlers.deltas_handler);
372 msgbus::unsubscribe_book_depth(handlers.depth_pattern, &handlers.depth_handler);
373 msgbus::unsubscribe_quotes(handlers.quote_pattern, &handlers.quote_handler);
374 msgbus::unsubscribe_trades(handlers.trade_pattern, &handlers.trade_handler);
375 msgbus::unsubscribe_bars(handlers.bar_pattern, &handlers.bar_handler);
376 msgbus::unsubscribe_any(handlers.status_pattern, &handlers.status_handler);
377 msgbus::unsubscribe_instrument_close(handlers.close_pattern, &handlers.close_handler);
378 msgbus::unsubscribe_position_events(
379 handlers.position_pattern,
380 &handlers.position_handler,
381 );
382
383 log::debug!(
384 "Sandbox deregistered message handlers for venue={}",
385 self.config.venue
386 );
387 }
388 }
389
390 fn expiry_sweep_timer_name(&self) -> String {
391 format!("{}-sandbox-expiry-sweep", self.core.borrow().client_id)
392 }
393
394 fn register_expiry_sweep_timer(&self) {
395 let inner_weak = WeakCell::from(Rc::downgrade(&self.inner));
396 let callback: Rc<dyn Fn(TimeEvent)> = Rc::new(move |_event: TimeEvent| {
397 let Some(inner_rc) = inner_weak.upgrade() else {
398 return;
399 };
400
401 if let Ok(mut inner) = inner_rc.try_borrow_mut() {
404 inner.sweep_expired_engines();
405 } else {
406 log::debug!("Skipping sandbox expiry sweep due to active borrow");
407 }
408 });
409
410 let name = self.expiry_sweep_timer_name();
411
412 if let Err(e) = self.clock.borrow_mut().set_timer_ns(
413 &name,
414 EXPIRED_ENGINE_SWEEP_INTERVAL,
415 None,
416 None,
417 Some(TimeEventCallback::from(callback)),
418 None,
419 None,
420 ) {
421 log::error!("Failed to register sandbox expiry sweep timer: {e}");
422 }
423 }
424
425 fn cancel_expiry_sweep_timer(&self) {
426 self.clock
427 .borrow_mut()
428 .cancel_timer(&self.expiry_sweep_timer_name());
429 }
430
431 fn cancel_inbound_alert(&self) {
432 let client_id = self.core.borrow().client_id;
433 self.clock
434 .borrow_mut()
435 .cancel_timer(&inbound_alert_name(client_id));
436 }
437
438 fn get_current_account_balances(&self) -> Vec<AccountBalance> {
439 let account_id = self.core.borrow().account_id;
440 let cache = self.cache.borrow();
441
442 if let Some(account) = cache.account(&account_id) {
443 return account.balances().into_values().collect();
444 }
445
446 self.get_account_balances()
447 }
448
449 fn sync_cached_account_config(&self) -> anyhow::Result<()> {
450 let Some(mut account) = self.get_account() else {
451 return Ok(());
452 };
453
454 account.set_calculate_account_state(!self.config.frozen_account);
455
456 if let AccountAny::Margin(margin_account) = &mut account {
457 if let Some(model) = &self.config.margin_model {
458 margin_account.set_margin_model(model.clone().into());
459 }
460
461 margin_account.set_default_leverage(self.config.default_leverage);
462 for (instrument_id, leverage) in &self.config.leverages {
463 margin_account.set_leverage(*instrument_id, *leverage);
464 }
465 }
466
467 self.cache.borrow_mut().update_account(&account)
468 }
469
470 pub fn process_quote_tick(&self, quote: &QuoteTick) -> anyhow::Result<()> {
476 SandboxInner::drain_inbound(&self.inner);
477
478 let instrument_id = quote.instrument_id;
479 let instrument = self.cache.borrow().try_instrument(&instrument_id)?.clone();
480
481 if !check_quote_or_drop("quote tick", quote, &instrument) {
482 return Ok(());
483 }
484
485 let mut inner = self.inner.borrow_mut();
486 inner.ensure_matching_engine(&instrument);
487 if let Some(engine) = inner.matching_engines.get_mut(&instrument_id) {
488 engine.process_quote_tick(quote);
489 }
490
491 inner.drain_oto_commands();
492 Ok(())
493 }
494
495 pub fn process_trade_tick(&self, trade: &TradeTick) -> anyhow::Result<()> {
501 SandboxInner::drain_inbound(&self.inner);
502
503 if !self.config.trade_execution {
504 return Ok(());
505 }
506
507 let instrument_id = trade.instrument_id;
508 let instrument = self.cache.borrow().try_instrument(&instrument_id)?.clone();
509
510 if !check_trade_or_drop("trade tick", trade, &instrument) {
511 return Ok(());
512 }
513
514 let mut inner = self.inner.borrow_mut();
515 inner.ensure_matching_engine(&instrument);
516 if let Some(engine) = inner.matching_engines.get_mut(&instrument_id) {
517 engine.process_trade_tick(trade);
518 }
519
520 inner.drain_oto_commands();
521 Ok(())
522 }
523
524 pub fn process_bar(&self, bar: &Bar) -> anyhow::Result<()> {
530 SandboxInner::drain_inbound(&self.inner);
531
532 if !self.config.bar_execution {
533 return Ok(());
534 }
535
536 let instrument_id = bar.bar_type.instrument_id();
537 let instrument = self.cache.borrow().try_instrument(&instrument_id)?.clone();
538
539 if !check_bar_or_drop("bar", bar, &instrument) {
540 return Ok(());
541 }
542
543 let mut inner = self.inner.borrow_mut();
544 inner.ensure_matching_engine(&instrument);
545 if let Some(engine) = inner.matching_engines.get_mut(&instrument_id) {
546 engine.process_bar(bar);
547 }
548
549 inner.drain_oto_commands();
550 Ok(())
551 }
552
553 pub fn process_order_book_deltas(&self, deltas: &OrderBookDeltas) -> anyhow::Result<()> {
559 SandboxInner::drain_inbound(&self.inner);
560
561 let instrument_id = deltas.instrument_id;
562 let instrument = self.cache.borrow().try_instrument(&instrument_id)?.clone();
563
564 let mut inner = self.inner.borrow_mut();
565 inner.ensure_matching_engine(&instrument);
566 if let Some(engine) = inner.matching_engines.get_mut(&instrument_id) {
567 engine.process_order_book_deltas(deltas)?;
568 }
569
570 inner.drain_oto_commands();
571 Ok(())
572 }
573
574 pub fn reset(&self) {
576 let mut inner = self.inner.borrow_mut();
577 for engine in inner.matching_engines.values_mut() {
578 engine.reset();
579 }
580
581 inner.balances.clear();
582 for money in &self.config.starting_balances {
583 inner
584 .balances
585 .insert(money.currency.code.to_string(), *money);
586 }
587
588 inner.clear_inbound_queue();
589 self.cancel_inbound_alert();
590
591 log::info!(
592 "Sandbox execution client reset: venue={}",
593 self.config.venue
594 );
595 }
596
597 fn get_account_balances(&self) -> Vec<AccountBalance> {
598 self.inner
599 .borrow()
600 .balances
601 .values()
602 .map(|money| AccountBalance::new(*money, Money::zero(money.currency), *money))
603 .collect()
604 }
605
606 fn get_order(&self, client_order_id: &ClientOrderId) -> anyhow::Result<OrderAny> {
607 Ok(self.cache.borrow().try_order_owned(client_order_id)?)
608 }
609}
610
611#[async_trait(?Send)]
612impl ExecutionClient for SandboxExecutionClient {
613 fn is_connected(&self) -> bool {
614 self.core.borrow().is_connected()
615 }
616
617 fn client_id(&self) -> ClientId {
618 self.core.borrow().client_id
619 }
620
621 fn account_id(&self) -> AccountId {
622 self.core.borrow().account_id
623 }
624
625 fn venue(&self) -> Venue {
626 self.core.borrow().venue
627 }
628
629 fn oms_type(&self) -> OmsType {
630 self.config.oms_type
631 }
632
633 fn provides_bulk_position_coverage(&self, _instrument_id: InstrumentId) -> bool {
635 false
636 }
637
638 fn settles_contract_expirations(&self) -> bool {
639 true
640 }
641
642 fn on_instrument(&mut self, instrument: InstrumentAny) {
643 let instrument_id = instrument.id();
644 let mut inner = self.inner.borrow_mut();
645 if let Some(engine) = inner.matching_engines.get_mut(&instrument_id)
646 && let Err(e) = engine.update_instrument(instrument)
647 {
648 log::error!("Failed to update instrument {instrument_id} in sandbox engine: {e}");
649 }
650
651 inner.drain_oto_commands();
652 }
653
654 fn get_account(&self) -> Option<AccountAny> {
655 let account_id = self.core.borrow().account_id;
656 self.cache.borrow().account_owned(&account_id)
657 }
658
659 fn reset(&mut self) -> anyhow::Result<()> {
660 Self::reset(self);
661 Ok(())
662 }
663
664 fn generate_account_state(
665 &self,
666 balances: Vec<AccountBalance>,
667 margins: Vec<MarginBalance>,
668 reported: bool,
669 ts_event: UnixNanos,
670 info: Option<Params>,
671 ) -> anyhow::Result<()> {
672 let ts_init = self.clock.borrow().timestamp_ns();
673 let state = self
674 .factory
675 .generate_account_state(balances, margins, reported, ts_event, ts_init, info);
676 let endpoint = MessagingSwitchboard::portfolio_update_account();
677 msgbus::send_account_state(endpoint, &state);
678 self.sync_cached_account_config()?;
679 Ok(())
680 }
681
682 fn start(&mut self) -> anyhow::Result<()> {
683 if self.core.borrow().is_started() {
684 return Ok(());
685 }
686
687 if let Some(sender) = try_get_exec_event_sender() {
688 let handler: Rc<dyn Fn(OrderEventAny)> = Rc::new(move |event: OrderEventAny| {
689 if let Err(e) = sender.send(ExecutionEvent::Order(event)) {
690 log::warn!("Failed to send order event: {e}");
691 }
692 });
693 let mut inner = self.inner.borrow_mut();
694 inner.event_handler = Some(handler.clone());
695 for engine in inner.matching_engines.values_mut() {
696 engine.set_event_handler(handler.clone());
697 }
698 }
699
700 self.inner.borrow_mut().load_open_orders();
701
702 self.register_message_handlers();
703 self.register_expiry_sweep_timer();
704
705 self.core.borrow().set_started();
706 let core = self.core.borrow();
707 log::info!(
708 "Sandbox execution client started: venue={}, account_id={}, oms_type={:?}, account_type={:?}",
709 self.config.venue,
710 core.account_id,
711 self.config.oms_type,
712 self.config.account_type,
713 );
714 Ok(())
715 }
716
717 fn stop(&mut self) -> anyhow::Result<()> {
718 if self.core.borrow().is_stopped() {
719 return Ok(());
720 }
721
722 self.deregister_message_handlers();
723 self.cancel_expiry_sweep_timer();
724 self.cancel_inbound_alert();
725
726 {
731 let mut inner = self.inner.borrow_mut();
732 let discarded = inner.take_inbound_queue();
733 inner.refuse_discarded(discarded);
734 }
735
736 self.core.borrow().set_stopped();
737 self.core.borrow().set_disconnected();
738 log::info!(
739 "Sandbox execution client stopped: venue={}",
740 self.config.venue
741 );
742 Ok(())
743 }
744
745 async fn connect(&mut self) -> anyhow::Result<()> {
746 if self.core.borrow().is_connected() {
747 return Ok(());
748 }
749
750 let balances = self.get_account_balances();
751 let ts_event = self.clock.borrow().timestamp_ns();
752 self.generate_account_state(balances, vec![], false, ts_event, None)?;
753
754 self.core.borrow().set_connected();
755 log::info!(
756 "Sandbox execution client connected: venue={}",
757 self.config.venue
758 );
759 Ok(())
760 }
761
762 async fn disconnect(&mut self) -> anyhow::Result<()> {
763 if self.core.borrow().is_disconnected() {
764 return Ok(());
765 }
766
767 self.core.borrow().set_disconnected();
768 log::info!(
769 "Sandbox execution client disconnected: venue={}",
770 self.config.venue
771 );
772 Ok(())
773 }
774
775 fn submit_order(&self, cmd: SubmitOrder) -> anyhow::Result<()> {
776 let order = self.get_order(&cmd.client_order_id)?;
777
778 if order.is_closed() {
779 log::warn!("Cannot submit closed order {}", order.client_order_id());
780 return Ok(());
781 }
782
783 let ts_init = self.clock.borrow().timestamp_ns();
784 let event = self.factory.generate_order_submitted(&order, ts_init);
785 self.dispatch_order_event(event);
786
787 let mut inner = self.inner.borrow_mut();
788 if inner.config.latency_model.is_none() {
789 inner.apply_submit_order(&cmd)?;
790 } else {
791 inner.defer_or_apply(TradingCommand::SubmitOrder(cmd));
792 }
793 Ok(())
794 }
795
796 fn submit_order_list(&self, cmd: SubmitOrderList) -> anyhow::Result<()> {
797 let ts_init = self.clock.borrow().timestamp_ns();
798
799 let orders: Vec<OrderAny> = self
800 .cache
801 .borrow()
802 .orders_for_ids(&cmd.order_list.client_order_ids, &cmd);
803
804 for order in &orders {
805 if order.is_closed() {
806 log::warn!("Cannot submit closed order {}", order.client_order_id());
807 continue;
808 }
809
810 let event = self.factory.generate_order_submitted(order, ts_init);
811 self.dispatch_order_event(event);
812 }
813
814 let mut inner = self.inner.borrow_mut();
815 if inner.config.latency_model.is_none() {
816 let _ = inner.apply_submit_order_list(&cmd);
817 } else {
818 inner.defer_or_apply(TradingCommand::SubmitOrderList(cmd));
819 }
820 Ok(())
821 }
822
823 fn modify_order(&self, cmd: ModifyOrder) -> anyhow::Result<()> {
824 let mut inner = self.inner.borrow_mut();
825 if inner.config.latency_model.is_none() {
826 inner.apply_modify_order(&cmd);
827 } else {
828 inner.defer_or_apply(TradingCommand::ModifyOrder(cmd));
829 }
830 Ok(())
831 }
832
833 fn batch_modify_orders(&self, cmd: BatchModifyOrders) -> anyhow::Result<()> {
834 let mut inner = self.inner.borrow_mut();
835 if inner.config.latency_model.is_none() {
836 inner.apply_batch_modify_orders(&cmd);
837 } else {
838 inner.defer_or_apply(TradingCommand::ModifyOrders(cmd));
839 }
840 Ok(())
841 }
842
843 fn cancel_order(&self, cmd: CancelOrder) -> anyhow::Result<()> {
844 let mut inner = self.inner.borrow_mut();
845 if inner.config.latency_model.is_none() {
846 inner.apply_cancel_order(&cmd);
847 } else {
848 inner.defer_or_apply(TradingCommand::CancelOrder(cmd));
849 }
850 Ok(())
851 }
852
853 fn cancel_all_orders(&self, cmd: CancelAllOrders) -> anyhow::Result<()> {
854 let mut inner = self.inner.borrow_mut();
855 if inner.config.latency_model.is_none() {
856 inner.apply_cancel_all_orders(&cmd);
857 } else {
858 inner.defer_or_apply(TradingCommand::CancelAllOrders(cmd));
859 }
860 Ok(())
861 }
862
863 fn batch_cancel_orders(&self, cmd: BatchCancelOrders) -> anyhow::Result<()> {
864 let mut inner = self.inner.borrow_mut();
865 if inner.config.latency_model.is_none() {
866 inner.apply_batch_cancel_orders(&cmd);
867 } else {
868 inner.defer_or_apply(TradingCommand::CancelOrders(cmd));
869 }
870 Ok(())
871 }
872
873 fn query_account(&self, _cmd: QueryAccount) -> anyhow::Result<()> {
874 let balances = self.get_current_account_balances();
875 let ts_event = self.clock.borrow().timestamp_ns();
876 self.generate_account_state(balances, vec![], false, ts_event, None)?;
877 Ok(())
878 }
879
880 fn query_order(&self, _cmd: QueryOrder) -> anyhow::Result<()> {
881 Ok(())
883 }
884
885 async fn generate_order_status_report(
886 &self,
887 cmd: &GenerateOrderStatusReport,
888 ) -> anyhow::Result<Option<OrderStatusReport>> {
889 let cache = self.cache.borrow();
890
891 let client_order_id = cmd.client_order_id.or_else(|| {
892 cmd.venue_order_id
893 .and_then(|id| cache.client_order_id(&id).copied())
894 });
895
896 let Some(order) = client_order_id.and_then(|id| cache.order(&id)) else {
897 return Ok(None);
898 };
899
900 if order.account_id() != Some(self.core.borrow().account_id)
901 || order.instrument_id().venue != self.config.venue
902 || cmd
903 .instrument_id
904 .is_some_and(|id| id != order.instrument_id())
905 || cmd
906 .venue_order_id
907 .is_some_and(|id| Some(id) != order.venue_order_id())
908 {
909 return Ok(None);
910 }
911
912 let ts_init = self.clock.borrow().timestamp_ns();
913 Ok(order_status_report(&order, ts_init))
914 }
915
916 async fn generate_order_status_reports(
917 &self,
918 cmd: &GenerateOrderStatusReports,
919 ) -> anyhow::Result<Vec<OrderStatusReport>> {
920 let account_id = self.core.borrow().account_id;
921 let ts_init = self.clock.borrow().timestamp_ns();
922 let cache = self.cache.borrow();
923
924 let reports = cache
925 .orders_refs(
926 Some(&self.config.venue),
927 cmd.instrument_id.as_ref(),
928 None,
929 Some(&account_id),
930 None,
931 )
932 .into_iter()
933 .filter(|order| !cmd.open_only || order.is_open() || order.is_inflight())
934 .filter(|order| {
935 !order.is_closed()
936 || (cmd.start.is_none_or(|start| order.ts_last() >= start)
937 && cmd.end.is_none_or(|end| order.ts_last() <= end))
938 })
939 .filter_map(|order| order_status_report(&order, ts_init))
940 .collect();
941
942 Ok(reports)
943 }
944
945 async fn generate_fill_reports(
946 &self,
947 _cmd: GenerateFillReports,
948 ) -> anyhow::Result<Vec<FillReport>> {
949 Ok(Vec::new())
951 }
952
953 async fn generate_position_status_reports(
954 &self,
955 _cmd: &GeneratePositionStatusReports,
956 ) -> anyhow::Result<Vec<PositionStatusReport>> {
957 Ok(Vec::new())
959 }
960
961 async fn generate_mass_status(
962 &self,
963 lookback_mins: Option<u64>,
964 ) -> anyhow::Result<Option<ExecutionMassStatus>> {
965 let ts_init = self.clock.borrow().timestamp_ns();
966 generate_mass_status(self, lookback_mins, ts_init).await
967 }
968}
969
970fn order_status_report(order: &OrderAny, ts_init: UnixNanos) -> Option<OrderStatusReport> {
971 let mut report = order.to_order_status_report(None)?;
972 report.ts_init = ts_init;
973 report.venue_position_id = None;
974
975 for event in order.events() {
976 if let OrderEventAny::Canceled(event) = event {
977 report.cancel_reason = event.reason.map(|reason| reason.to_string());
978 }
979 }
980
981 Some(report)
982}
983
984struct SandboxInner {
986 clock: Rc<RefCell<dyn Clock>>,
987 cache: Rc<RefCell<Cache>>,
988 config: SandboxExecutionClientConfig,
989 fill_model: FillModelHandle,
990 fee_model: FeeModelHandle,
991 matching_engines: AHashMap<InstrumentId, OrderMatchingEngine>,
992 next_engine_raw_id: u32,
993 balances: AHashMap<String, Money>,
994 event_handler: Option<Rc<dyn Fn(OrderEventAny)>>,
997 inbound_queue: BinaryHeap<DelayedCommand>,
999 inflight_orders: InflightOrders,
1000 matching_orders: MatchingOrders,
1001 inbound_seq: u64,
1004 client_id: ClientId,
1005 account_id: AccountId,
1006 self_weak: WeakCell<Self>,
1007}
1008
1009#[derive(Debug)]
1012struct DelayedCommand {
1013 due_ns: UnixNanos,
1014 seq: u64,
1015 command: TradingCommand,
1016}
1017
1018impl Ord for DelayedCommand {
1019 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1020 other
1021 .due_ns
1022 .cmp(&self.due_ns)
1023 .then_with(|| other.seq.cmp(&self.seq))
1024 }
1025}
1026
1027impl PartialOrd for DelayedCommand {
1028 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1029 Some(self.cmp(other))
1030 }
1031}
1032
1033impl PartialEq for DelayedCommand {
1034 fn eq(&self, other: &Self) -> bool {
1035 self.cmp(other) == std::cmp::Ordering::Equal
1036 }
1037}
1038
1039impl Eq for DelayedCommand {}
1040
1041impl SandboxInner {
1042 fn load_open_orders(&mut self) {
1043 let venue = self.config.venue;
1044 let account_id = self.account_id;
1045 let mut open_orders: Vec<(OrderAny, AccountId)> = {
1046 let cache = self.cache.borrow();
1047 cache
1048 .orders_open(Some(&venue), None, None, Some(&account_id), None)
1049 .into_iter()
1050 .filter(|order| !order.is_emulated())
1051 .filter_map(|order| {
1052 order
1053 .account_id()
1054 .map(|account_id| (order.clone(), account_id))
1055 })
1056 .collect()
1057 };
1058
1059 open_orders.sort_by(|(a, _), (b, _)| {
1060 a.ts_init()
1061 .cmp(&b.ts_init())
1062 .then_with(|| a.client_order_id().cmp(&b.client_order_id()))
1063 });
1064
1065 for (order, account_id) in open_orders {
1066 let instrument_id = order.instrument_id();
1067 let instrument = self.cache.borrow().instrument(&instrument_id).cloned();
1068 match instrument {
1069 Some(instrument) => {
1070 self.ensure_matching_engine(&instrument);
1071
1072 if let Some(engine) = self.matching_engines.get_mut(&instrument_id) {
1073 engine.restore_open_order(&order, account_id);
1074 }
1075 }
1076 None => {
1077 log::warn!(
1078 "No instrument for {instrument_id} to restore open order {}",
1079 order.client_order_id()
1080 );
1081 }
1082 }
1083 }
1084 }
1085
1086 fn ensure_matching_engine(&mut self, instrument: &InstrumentAny) {
1087 let instrument_id = instrument.id();
1088
1089 if !self.matching_engines.contains_key(&instrument_id) {
1090 let engine_config = self.config.to_matching_engine_config();
1091 let fill_model = self.fill_model.clone();
1092 let fee_model = self.fee_model.clone();
1093 let raw_id = self.next_engine_raw_id;
1094 self.next_engine_raw_id = self.next_engine_raw_id.wrapping_add(1);
1095
1096 let mut engine = OrderMatchingEngine::new(
1097 instrument.clone(),
1098 raw_id,
1099 fill_model,
1100 fee_model,
1101 self.config.book_type,
1102 self.config.oms_type,
1103 self.config.account_type,
1104 self.clock.clone(),
1105 self.cache.clone(),
1106 engine_config,
1107 );
1108
1109 if let Some(handler) = &self.event_handler {
1110 engine.set_event_handler(handler.clone());
1111 }
1112
1113 engine.set_inflight_orders(self.inflight_orders.clone());
1114 engine.set_matching_orders(self.matching_orders.clone());
1115 self.matching_engines.insert(instrument_id, engine);
1116 }
1117 }
1118
1119 fn process_quote_tick(&mut self, quote: &QuoteTick) {
1120 let instrument_id = quote.instrument_id;
1121
1122 let instrument = self.cache.borrow().instrument(&instrument_id).cloned();
1123 if let Some(instrument) = instrument {
1124 if !check_quote_or_drop("quote tick", quote, &instrument) {
1125 return;
1126 }
1127
1128 self.ensure_matching_engine(&instrument);
1129
1130 if let Some(engine) = self.matching_engines.get_mut(&instrument_id) {
1131 engine.process_quote_tick(quote);
1132 }
1133 }
1134
1135 self.drain_oto_commands();
1136 }
1137
1138 fn process_trade_tick(&mut self, trade: &TradeTick) {
1139 if !self.config.trade_execution {
1140 return;
1141 }
1142
1143 let instrument_id = trade.instrument_id;
1144
1145 let instrument = self.cache.borrow().instrument(&instrument_id).cloned();
1146 if let Some(instrument) = instrument {
1147 if !check_trade_or_drop("trade tick", trade, &instrument) {
1148 return;
1149 }
1150
1151 self.ensure_matching_engine(&instrument);
1152
1153 if let Some(engine) = self.matching_engines.get_mut(&instrument_id) {
1154 engine.process_trade_tick(trade);
1155 }
1156 }
1157
1158 self.drain_oto_commands();
1159 }
1160
1161 fn process_bar(&mut self, bar: &Bar) {
1162 if !self.config.bar_execution {
1163 return;
1164 }
1165
1166 let instrument_id = bar.bar_type.instrument_id();
1167
1168 let instrument = self.cache.borrow().instrument(&instrument_id).cloned();
1169 if let Some(instrument) = instrument {
1170 if !check_bar_or_drop("bar", bar, &instrument) {
1171 return;
1172 }
1173
1174 self.ensure_matching_engine(&instrument);
1175
1176 if let Some(engine) = self.matching_engines.get_mut(&instrument_id) {
1177 engine.process_bar(bar);
1178 }
1179 }
1180
1181 self.drain_oto_commands();
1182 }
1183
1184 fn process_order_book_deltas(&mut self, deltas: &OrderBookDeltas) {
1185 let instrument_id = deltas.instrument_id;
1186
1187 let instrument = self.cache.borrow().instrument(&instrument_id).cloned();
1188 if let Some(instrument) = instrument {
1189 self.ensure_matching_engine(&instrument);
1190
1191 if let Some(engine) = self.matching_engines.get_mut(&instrument_id)
1192 && let Err(e) = engine.process_order_book_deltas(deltas)
1193 {
1194 log::error!("Error processing order book deltas: {e}");
1195 }
1196 }
1197
1198 self.drain_oto_commands();
1199 }
1200
1201 fn process_order_book_depth(&mut self, depth: &OrderBookDepth) {
1202 let instrument_id = depth.instrument_id;
1203
1204 let instrument = self.cache.borrow().instrument(&instrument_id).cloned();
1205 if let Some(instrument) = instrument {
1206 self.ensure_matching_engine(&instrument);
1207
1208 if let Some(engine) = self.matching_engines.get_mut(&instrument_id)
1209 && let Err(e) = engine.process_order_book_depth(depth)
1210 {
1211 log::error!("Error processing order book depth: {e}");
1212 }
1213 }
1214
1215 self.drain_oto_commands();
1216 }
1217
1218 fn process_instrument_status(&mut self, status: &InstrumentStatus) {
1219 let instrument_id = status.instrument_id;
1220
1221 if let Some(engine) = self.matching_engines.get_mut(&instrument_id) {
1222 engine.process_status(status.action);
1223 return;
1224 }
1225
1226 let instrument = self.cache.borrow().instrument(&instrument_id).cloned();
1227 if let Some(instrument) = instrument {
1228 self.ensure_matching_engine(&instrument);
1229
1230 if let Some(engine) = self.matching_engines.get_mut(&instrument_id) {
1231 engine.process_status(status.action);
1232 }
1233 } else {
1234 log::warn!(
1235 "Ignoring instrument status for {instrument_id}: instrument missing from cache",
1236 );
1237 }
1238 }
1239
1240 fn process_instrument_close(&mut self, close: &InstrumentClose) {
1241 let instrument_id = close.instrument_id;
1242
1243 if let Some(engine) = self.matching_engines.get_mut(&instrument_id) {
1248 engine.process_instrument_close(*close);
1249 self.sync_expired_cleanup(instrument_id);
1250 } else {
1251 log::warn!(
1252 "Ignoring instrument close for {instrument_id}: no existing matching engine",
1253 );
1254 }
1255
1256 self.drain_oto_commands();
1257 }
1258
1259 fn is_expired_now(&self, instrument_id: InstrumentId) -> bool {
1260 let Some(engine) = self.matching_engines.get(&instrument_id) else {
1261 return false;
1262 };
1263
1264 let now_ns = self.clock.borrow().timestamp_ns();
1265 engine
1266 .instrument
1267 .expiration_ns()
1268 .is_some_and(|ns| now_ns >= ns)
1269 }
1270
1271 fn has_open_orders(&self, instrument_id: InstrumentId) -> bool {
1272 self.cache.borrow().has_orders_open(
1273 Some(&self.config.venue),
1274 Some(&instrument_id),
1275 None,
1276 None,
1277 None,
1278 )
1279 }
1280
1281 fn sync_expired_cleanup(&mut self, instrument_id: InstrumentId) {
1282 if !self.is_expired_now(instrument_id) {
1283 return;
1284 }
1285
1286 if self
1287 .matching_engines
1288 .get_mut(&instrument_id)
1289 .is_some_and(OrderMatchingEngine::has_pending_fills)
1290 {
1291 return;
1292 }
1293
1294 let has_open_positions = self.cache.borrow().has_positions_open(
1295 Some(&self.config.venue),
1296 Some(&instrument_id),
1297 None,
1298 None,
1299 None,
1300 );
1301
1302 if has_open_positions {
1303 return;
1304 }
1305
1306 self.matching_engines.remove(&instrument_id);
1307 self.cache
1308 .borrow_mut()
1309 .purge_instrument_skip_order_guard(instrument_id);
1310 }
1311
1312 fn sync_expired_cleanup_many(&mut self, instrument_ids: &[InstrumentId]) {
1313 for &instrument_id in instrument_ids {
1314 self.sync_expired_cleanup(instrument_id);
1315 }
1316 }
1317
1318 fn sweep_expired_engines(&mut self) {
1321 let expired_ids: Vec<InstrumentId> = self
1322 .matching_engines
1323 .keys()
1324 .copied()
1325 .filter(|instrument_id| {
1326 self.is_expired_now(*instrument_id) && !self.has_open_orders(*instrument_id)
1327 })
1328 .collect();
1329
1330 let ts_now = self.clock.borrow().timestamp_ns();
1331
1332 for instrument_id in expired_ids {
1333 if let Some(engine) = self.matching_engines.get_mut(&instrument_id) {
1334 engine.process_instrument_expiration(ts_now);
1335 }
1336
1337 self.sync_expired_cleanup(instrument_id);
1338 }
1339
1340 self.drain_oto_commands();
1341 }
1342
1343 fn apply_trading_command(&mut self, cmd: &TradingCommand) -> anyhow::Result<()> {
1345 self.inflight_orders.remove(cmd);
1346
1347 if matches!(
1350 cmd,
1351 TradingCommand::ModifyOrder(_)
1352 | TradingCommand::ModifyOrders(_)
1353 | TradingCommand::CancelOrder(_)
1354 | TradingCommand::CancelOrders(_)
1355 ) && !self.ensure_engine_for(cmd.instrument_id())
1356 {
1357 self.refuse_command(cmd, "No matching engine for instrument");
1358 return Ok(());
1359 }
1360
1361 match cmd {
1362 TradingCommand::SubmitOrder(cmd) => self.apply_submit_order(cmd)?,
1363 TradingCommand::SubmitOrderList(cmd) => {
1364 for order in self.apply_submit_order_list(cmd) {
1366 self.reject_submit_leg(cmd, &order, "No instrument for order");
1367 }
1368 }
1369 TradingCommand::ModifyOrder(cmd) => self.apply_modify_order(cmd),
1370 TradingCommand::ModifyOrders(cmd) => self.apply_batch_modify_orders(cmd),
1371 TradingCommand::CancelOrder(cmd) => self.apply_cancel_order(cmd),
1372 TradingCommand::CancelOrders(cmd) => self.apply_batch_cancel_orders(cmd),
1373 TradingCommand::CancelAllOrders(cmd) => self.apply_cancel_all_orders(cmd),
1374 TradingCommand::QueryOrder(_) | TradingCommand::QueryAccount(_) => {}
1375 }
1376 Ok(())
1377 }
1378
1379 fn refuse_command(&self, command: &TradingCommand, reason: &str) {
1380 self.refuse_command_deduped(command, reason, &mut AHashSet::new());
1381 }
1382
1383 fn refuse_command_deduped(
1384 &self,
1385 command: &TradingCommand,
1386 reason: &str,
1387 pending_denied: &mut AHashSet<(ClientOrderId, UUID4)>,
1388 ) {
1389 let ts_now = self.clock.borrow().timestamp_ns();
1390 let account_id = self.account_id;
1391 let reason = Ustr::from(reason);
1392
1393 let reject_submit = |trader_id, strategy_id, instrument_id, client_order_id| {
1394 self.dispatch_order_event(OrderEventAny::Rejected(OrderRejected::new(
1395 trader_id,
1396 strategy_id,
1397 instrument_id,
1398 client_order_id,
1399 account_id,
1400 reason,
1401 UUID4::new(),
1402 ts_now,
1403 ts_now,
1404 false,
1405 false,
1406 )));
1407 };
1408
1409 match command {
1410 TradingCommand::SubmitOrder(cmd) => reject_submit(
1411 cmd.trader_id,
1412 cmd.strategy_id,
1413 cmd.instrument_id,
1414 cmd.client_order_id,
1415 ),
1416 TradingCommand::SubmitOrderList(cmd) => {
1417 let in_flight: Vec<(ClientOrderId, InstrumentId)> = self
1419 .cache
1420 .borrow()
1421 .orders_for_ids(&cmd.order_list.client_order_ids, cmd)
1422 .iter()
1423 .filter(|order| !order.is_closed())
1424 .map(|order| (order.client_order_id(), order.instrument_id()))
1425 .collect();
1426
1427 for (client_order_id, instrument_id) in in_flight {
1428 reject_submit(
1429 cmd.trader_id,
1430 cmd.strategy_id,
1431 instrument_id,
1432 client_order_id,
1433 );
1434 }
1435 }
1436 TradingCommand::ModifyOrder(cmd) => {
1437 if pending_denied.insert((cmd.client_order_id, cmd.command_id)) {
1438 self.deny_modify(cmd, reason, ts_now);
1439 }
1440 }
1441 TradingCommand::ModifyOrders(cmd) => {
1442 for modify in &cmd.modifies {
1443 if pending_denied.insert((modify.client_order_id, modify.command_id)) {
1444 self.deny_modify(modify, reason, ts_now);
1445 }
1446 }
1447 }
1448 TradingCommand::CancelOrder(cmd) => {
1449 if pending_denied.insert((cmd.client_order_id, cmd.command_id)) {
1450 self.deny_cancel(cmd, reason, ts_now);
1451 }
1452 }
1453 TradingCommand::CancelOrders(cmd) => {
1454 for cancel in &cmd.cancels {
1455 if pending_denied.insert((cancel.client_order_id, cancel.command_id)) {
1456 self.deny_cancel(cancel, reason, ts_now);
1457 }
1458 }
1459 }
1460 TradingCommand::CancelAllOrders(_) => {}
1462 TradingCommand::QueryOrder(_) | TradingCommand::QueryAccount(_) => {}
1463 }
1464 }
1465
1466 fn deny_modify(&self, cmd: &ModifyOrder, reason: Ustr, ts_now: UnixNanos) {
1467 let mut event = OrderModifyDenied::new(
1468 cmd.trader_id,
1469 cmd.strategy_id,
1470 cmd.instrument_id,
1471 cmd.client_order_id,
1472 reason,
1473 UUID4::new(),
1474 ts_now,
1475 ts_now,
1476 cmd.venue_order_id,
1477 Some(self.account_id),
1478 );
1479 event.causation_id = Some(cmd.command_id);
1480 self.dispatch_order_event(OrderEventAny::ModifyDenied(event));
1481 }
1482
1483 fn deny_cancel(&self, cmd: &CancelOrder, reason: Ustr, ts_now: UnixNanos) {
1484 let mut event = OrderCancelDenied::new(
1485 cmd.trader_id,
1486 cmd.strategy_id,
1487 cmd.instrument_id,
1488 cmd.client_order_id,
1489 reason,
1490 UUID4::new(),
1491 ts_now,
1492 ts_now,
1493 cmd.venue_order_id,
1494 Some(self.account_id),
1495 );
1496 event.causation_id = Some(cmd.command_id);
1497 self.dispatch_order_event(OrderEventAny::CancelDenied(event));
1498 }
1499
1500 fn dispatch_order_event(&self, event: OrderEventAny) {
1501 if let Some(handler) = &self.event_handler {
1502 handler(event);
1503 } else {
1504 msgbus::send_order_event(MessagingSwitchboard::exec_engine_process(), event);
1505 }
1506 }
1507
1508 fn ensure_engine_for(&mut self, instrument_id: InstrumentId) -> bool {
1511 if !self.matching_engines.contains_key(&instrument_id) {
1512 let instrument = self.cache.borrow().instrument(&instrument_id).cloned();
1513 let Some(instrument) = instrument else {
1514 log::warn!(
1515 "Cannot process command for {instrument_id}: instrument missing from cache",
1516 );
1517 return false;
1518 };
1519 self.ensure_matching_engine(&instrument);
1520 }
1521
1522 self.matching_engines.contains_key(&instrument_id)
1523 }
1524
1525 fn apply_submit_order(&mut self, cmd: &SubmitOrder) -> anyhow::Result<()> {
1526 let mut order = self.cache.borrow().try_order_owned(&cmd.client_order_id)?;
1527
1528 let instrument_id = order.instrument_id();
1529 let instrument = self.cache.borrow().try_instrument(&instrument_id)?.clone();
1530
1531 self.ensure_matching_engine(&instrument);
1532
1533 self.seed_cached_market_data(instrument_id);
1534
1535 if let Some(engine) = self.matching_engines.get_mut(&instrument_id) {
1536 engine.process_order(&mut order, self.account_id);
1537 self.sync_expired_cleanup(instrument_id);
1538 }
1539
1540 self.drain_oto_commands();
1541 Ok(())
1542 }
1543
1544 fn apply_submit_order_list(&mut self, cmd: &SubmitOrderList) -> Vec<OrderAny> {
1548 let orders: Vec<OrderAny> = self
1549 .cache
1550 .borrow()
1551 .orders_for_ids(&cmd.order_list.client_order_ids, cmd);
1552
1553 let mut cleanup_instrument_ids = Vec::new();
1554 let mut unresolved: Vec<OrderAny> = Vec::new();
1555
1556 for order in &orders {
1557 if order.is_closed() {
1558 continue;
1559 }
1560
1561 let instrument_id = order.instrument_id();
1562 if !cleanup_instrument_ids.contains(&instrument_id) {
1563 cleanup_instrument_ids.push(instrument_id);
1564 }
1565 let instrument = self.cache.borrow().instrument(&instrument_id).cloned();
1566
1567 let Some(instrument) = instrument else {
1568 unresolved.push(order.clone());
1571 continue;
1572 };
1573
1574 self.ensure_matching_engine(&instrument);
1575
1576 self.seed_cached_market_data(instrument_id);
1577
1578 if let Some(engine) = self.matching_engines.get_mut(&instrument_id) {
1579 let mut order_clone = order.clone();
1580 engine.process_order(&mut order_clone, self.account_id);
1581 }
1582 }
1583
1584 if !cleanup_instrument_ids.is_empty() {
1585 self.sync_expired_cleanup_many(&cleanup_instrument_ids);
1586 }
1587
1588 self.drain_oto_commands();
1589 unresolved
1590 }
1591
1592 fn drain_oto_commands(&mut self) {
1593 while let Some(command) = self.matching_orders.pop_command() {
1594 let instrument_id = command.instrument_id();
1595 if self.ensure_engine_for(instrument_id) {
1596 if matches!(command, OtoCommand::Release { .. }) {
1597 self.seed_cached_market_data(instrument_id);
1598 }
1599
1600 if let Some(engine) = self.matching_engines.get_mut(&instrument_id) {
1601 engine.process_oto_command(&command);
1602 }
1603 }
1604
1605 if let OtoCommand::Release {
1606 parent_quantity: Some(quantity),
1607 parent_order_id,
1608 parent_instrument_id,
1609 ..
1610 } = command
1611 && let Some(engine) = self.matching_engines.get_mut(&parent_instrument_id)
1612 {
1613 engine.process_oto_resize(parent_order_id, quantity);
1614 }
1615 }
1616 }
1617
1618 fn reject_submit_leg(&self, cmd: &SubmitOrderList, order: &OrderAny, reason: &str) {
1620 let ts_now = self.clock.borrow().timestamp_ns();
1621 self.dispatch_order_event(OrderEventAny::Rejected(OrderRejected::new(
1622 cmd.trader_id,
1623 cmd.strategy_id,
1624 order.instrument_id(),
1625 order.client_order_id(),
1626 self.account_id,
1627 Ustr::from(reason),
1628 UUID4::new(),
1629 ts_now,
1630 ts_now,
1631 false,
1632 false,
1633 )));
1634 }
1635
1636 fn seed_cached_market_data(&mut self, instrument_id: InstrumentId) {
1637 let Some(engine) = self.matching_engines.get_mut(&instrument_id) else {
1638 return;
1639 };
1640
1641 if self.config.liquidity_consumption
1643 && (engine.get_book().update_count != 0 || engine.get_core().last.is_some())
1644 {
1645 return;
1646 }
1647
1648 let (quote, trade) = {
1649 let cache = self.cache.borrow();
1650 (
1651 cache.quote(&instrument_id).copied(),
1652 cache.trade(&instrument_id).copied(),
1653 )
1654 };
1655
1656 if let Some(quote) = quote
1657 && check_quote_or_drop("cached quote tick", "e, &engine.instrument)
1658 {
1659 engine.process_quote_tick("e);
1660 }
1661
1662 if self.config.trade_execution
1663 && let Some(trade) = trade
1664 && check_trade_or_drop("cached trade tick", &trade, &engine.instrument)
1665 {
1666 engine.process_trade_tick(&trade);
1667 }
1668 }
1669
1670 fn apply_modify_order(&mut self, cmd: &ModifyOrder) {
1671 let account_id = self.account_id;
1672 if let Some(engine) = self.matching_engines.get_mut(&cmd.instrument_id) {
1673 engine.process_modify(cmd, account_id);
1674 } else {
1675 let ts_now = self.clock.borrow().timestamp_ns();
1676 self.deny_modify(cmd, "No matching engine for instrument".into(), ts_now);
1677 }
1678
1679 self.drain_oto_commands();
1680 }
1681
1682 fn apply_batch_modify_orders(&mut self, cmd: &BatchModifyOrders) {
1683 let account_id = self.account_id;
1684 if let Some(engine) = self.matching_engines.get_mut(&cmd.instrument_id) {
1685 engine.process_batch_modify(cmd, account_id);
1686 } else {
1687 let ts_now = self.clock.borrow().timestamp_ns();
1688 for command in &cmd.modifies {
1689 self.deny_modify(command, "No matching engine for instrument".into(), ts_now);
1690 }
1691 }
1692
1693 self.drain_oto_commands();
1694 }
1695
1696 fn apply_cancel_order(&mut self, cmd: &CancelOrder) {
1697 let account_id = self.account_id;
1698 if let Some(engine) = self.matching_engines.get_mut(&cmd.instrument_id) {
1699 engine.process_cancel(cmd, account_id);
1700 } else {
1701 let ts_now = self.clock.borrow().timestamp_ns();
1702 self.deny_cancel(cmd, "No matching engine for instrument".into(), ts_now);
1703 }
1704
1705 self.drain_oto_commands();
1706 }
1707
1708 fn apply_cancel_all_orders(&mut self, cmd: &CancelAllOrders) {
1709 let instrument_id = cmd.instrument_id;
1710 if let Some(engine) = self.matching_engines.get_mut(&instrument_id) {
1711 engine.process_cancel_all(cmd, self.account_id);
1712 } else {
1713 log::debug!("No open orders to cancel for {instrument_id}: no matching engine");
1714 }
1715
1716 self.drain_oto_commands();
1717 }
1718
1719 fn apply_batch_cancel_orders(&mut self, cmd: &BatchCancelOrders) {
1720 let account_id = self.account_id;
1721 if let Some(engine) = self.matching_engines.get_mut(&cmd.instrument_id) {
1722 engine.process_batch_cancel(cmd, account_id);
1723 } else {
1724 let ts_now = self.clock.borrow().timestamp_ns();
1725 for command in &cmd.cancels {
1726 self.deny_cancel(command, "No matching engine for instrument".into(), ts_now);
1727 }
1728 }
1729
1730 self.drain_oto_commands();
1731 }
1732
1733 fn enqueue(&mut self, command: TradingCommand, now_ns: UnixNanos, due_ns: UnixNanos) {
1736 let seq = self.inbound_seq;
1737 self.inbound_seq += 1;
1738
1739 self.inflight_orders.insert(&command);
1740 self.inbound_queue.push(DelayedCommand {
1741 due_ns,
1742 seq,
1743 command,
1744 });
1745
1746 self.arm_inbound_alert(now_ns);
1747 }
1748
1749 fn defer_or_apply(&mut self, command: TradingCommand) {
1754 let now_ns = self.clock.borrow().timestamp_ns();
1755
1756 let leg_latency = match self.command_leg_latency(&command, now_ns) {
1757 Ok(latency) => latency,
1758 Err(e) => {
1759 let reason = format!("Latency model failed: {e:#}");
1760 log::error!("{reason}");
1761 self.refuse_command(&command, &reason);
1762 return;
1763 }
1764 };
1765
1766 let Some(due_ns) = now_ns.checked_add(leg_latency) else {
1767 let reason = "Latency arrival timestamp exceeds u64 nanoseconds";
1768 log::error!("{reason}");
1769 self.refuse_command(&command, reason);
1770 return;
1771 };
1772
1773 let head_is_due = self
1774 .inbound_queue
1775 .peek()
1776 .is_some_and(|delayed| delayed.due_ns <= now_ns);
1777 if head_is_due || leg_latency > DurationNanos::ZERO {
1778 self.enqueue(command, now_ns, due_ns);
1779 return;
1780 }
1781
1782 if let Err(e) = self.apply_trading_command(&command) {
1783 log::error!("Error applying command: {e}");
1784 self.refuse_command(&command, "Command could not be applied at the venue");
1785 }
1786 }
1787
1788 fn command_leg_latency(
1790 &self,
1791 command: &TradingCommand,
1792 ts_now: UnixNanos,
1793 ) -> anyhow::Result<DurationNanos> {
1794 let Some(latency_model) = self.config.latency_model.as_ref() else {
1795 return Ok(DurationNanos::ZERO);
1796 };
1797
1798 match command {
1799 TradingCommand::SubmitOrder(_) | TradingCommand::SubmitOrderList(_) => {
1800 latency_model.get_insert_latency(command, ts_now)
1801 }
1802 TradingCommand::ModifyOrder(_) | TradingCommand::ModifyOrders(_) => {
1803 latency_model.get_update_latency(command, ts_now)
1804 }
1805 TradingCommand::CancelOrder(_)
1806 | TradingCommand::CancelOrders(_)
1807 | TradingCommand::CancelAllOrders(_) => {
1808 latency_model.get_delete_latency(command, ts_now)
1809 }
1810 TradingCommand::QueryOrder(_) | TradingCommand::QueryAccount(_) => {
1811 Ok(DurationNanos::ZERO)
1812 }
1813 }
1814 }
1815
1816 fn pop_due(&mut self, now_ns: UnixNanos) -> Option<DelayedCommand> {
1817 self.inbound_queue
1818 .peek()
1819 .is_some_and(|delayed| delayed.due_ns <= now_ns)
1820 .then(|| self.inbound_queue.pop().expect("peek returned Some"))
1821 }
1822
1823 fn on_quote_tick(inner: &Rc<RefCell<Self>>, quote: &QuoteTick) {
1824 Self::drain_inbound(inner);
1825 inner.borrow_mut().process_quote_tick(quote);
1826 }
1827
1828 fn on_trade_tick(inner: &Rc<RefCell<Self>>, trade: &TradeTick) {
1829 Self::drain_inbound(inner);
1830 inner.borrow_mut().process_trade_tick(trade);
1831 }
1832
1833 fn on_bar(inner: &Rc<RefCell<Self>>, bar: &Bar) {
1834 Self::drain_inbound(inner);
1835 inner.borrow_mut().process_bar(bar);
1836 }
1837
1838 fn on_order_book_deltas(inner: &Rc<RefCell<Self>>, deltas: &OrderBookDeltas) {
1839 Self::drain_inbound(inner);
1840 inner.borrow_mut().process_order_book_deltas(deltas);
1841 }
1842
1843 fn on_order_book_depth(inner: &WeakCell<Self>, venue: Venue, depth: &OrderBookDepth) {
1844 if depth.instrument_id.venue != venue {
1845 return;
1846 }
1847
1848 let Some(inner_rc) = inner.upgrade() else {
1849 return;
1850 };
1851
1852 Self::drain_inbound(&inner_rc);
1853 inner_rc.borrow_mut().process_order_book_depth(depth);
1854 }
1855
1856 fn on_instrument_status(inner: &Rc<RefCell<Self>>, status: &InstrumentStatus) {
1857 Self::drain_inbound(inner);
1858 inner.borrow_mut().process_instrument_status(status);
1859 }
1860
1861 fn on_instrument_close(inner: &Rc<RefCell<Self>>, close: &InstrumentClose) {
1862 Self::drain_inbound(inner);
1863 inner.borrow_mut().process_instrument_close(close);
1864 }
1865
1866 fn on_position_event(inner: &Rc<RefCell<Self>>, event: &PositionEvent) {
1867 let instrument_id = event.instrument_id();
1868
1869 let Ok(mut inner) = inner.try_borrow_mut() else {
1870 log::debug!(
1871 "Skipping immediate expiration retry for {instrument_id} due to active sandbox borrow",
1872 );
1873 return;
1874 };
1875
1876 if instrument_id.venue != inner.config.venue || event.account_id() != inner.account_id {
1877 return;
1878 }
1879
1880 let ts_now = inner.clock.borrow().timestamp_ns();
1882 if let Some(engine) = inner.matching_engines.get_mut(&instrument_id) {
1883 engine.process_instrument_expiration(ts_now);
1884 }
1885
1886 inner.sync_expired_cleanup(instrument_id);
1887 inner.drain_oto_commands();
1888 }
1889
1890 fn drain_inbound(inner: &Rc<RefCell<Self>>) {
1897 let Ok(mut this) = inner.try_borrow_mut() else {
1900 log::debug!("Skipping sandbox inbound drain due to active borrow");
1901 return;
1902 };
1903
1904 if this.config.latency_model.is_none() {
1905 return;
1906 }
1907
1908 let now_ns = this.clock.borrow().timestamp_ns();
1909
1910 while let Some(delayed) = this.pop_due(now_ns) {
1911 if let Err(e) = this.apply_trading_command(&delayed.command) {
1912 log::error!("Error applying deferred command: {e}");
1913 this.refuse_command(
1914 &delayed.command,
1915 "Command could not be applied at the venue",
1916 );
1917 }
1918 }
1919
1920 this.arm_inbound_alert(now_ns);
1921 }
1922
1923 fn take_inbound_queue(&mut self) -> Vec<DelayedCommand> {
1926 self.inflight_orders.clear();
1927
1928 if self.inbound_queue.is_empty() {
1929 return Vec::new();
1930 }
1931
1932 log::warn!(
1933 "Discarding {} command(s) still in flight at stop",
1934 self.inbound_queue.len(),
1935 );
1936
1937 let mut discarded = std::mem::take(&mut self.inbound_queue).into_vec();
1939 discarded.sort_unstable_by_key(|delayed| std::cmp::Reverse(delayed.seq));
1940 discarded
1941 }
1942
1943 fn refuse_discarded(&self, discarded: Vec<DelayedCommand>) {
1944 let mut pending_denied = AHashSet::new();
1945
1946 for delayed in discarded {
1947 self.refuse_command_deduped(
1948 &delayed.command,
1949 "Client stopped before the command was sent",
1950 &mut pending_denied,
1951 );
1952 }
1953 }
1954
1955 fn clear_inbound_queue(&mut self) {
1958 self.inbound_queue.clear();
1959 self.inflight_orders.clear();
1960 }
1961
1962 fn arm_inbound_alert(&self, now_ns: UnixNanos) {
1969 let Some(earliest_due) = self.inbound_queue.peek().map(|delayed| delayed.due_ns) else {
1970 return;
1971 };
1972
1973 if earliest_due <= now_ns {
1974 return;
1975 }
1976
1977 let name = inbound_alert_name(self.client_id);
1978 let armed_ns = self.clock.borrow().next_time_ns(&name);
1979
1980 match armed_ns {
1981 Some(armed_ns) if armed_ns <= earliest_due => return,
1983 Some(_) => self.clock.borrow_mut().cancel_timer(&name),
1985 None => {}
1986 }
1987
1988 let inner_weak = self.self_weak.clone();
1989 let alert_name = name.clone();
1990
1991 let callback: Rc<dyn Fn(TimeEvent)> = Rc::new(move |_event: TimeEvent| {
1992 let Some(inner_rc) = inner_weak.upgrade() else {
1993 return;
1994 };
1995
1996 if let Ok(this) = inner_rc.try_borrow() {
1998 this.clock.borrow_mut().cancel_timer(&alert_name);
1999 }
2000
2001 Self::drain_inbound(&inner_rc);
2003 });
2004
2005 if let Err(e) = self.clock.borrow_mut().set_time_alert_ns(
2006 &name,
2007 earliest_due,
2008 Some(TimeEventCallback::from(callback)),
2009 Some(true),
2010 ) {
2011 log::error!("Failed to arm sandbox inbound alert '{name}': {e}");
2012 }
2013 }
2014}
2015
2016fn inbound_alert_name(client_id: ClientId) -> String {
2017 format!("{client_id}-sandbox-inbound-alert")
2018}
2019
2020fn check_quote_or_drop(context: &str, quote: &QuoteTick, instrument: &InstrumentAny) -> bool {
2021 if quote_matches_instrument_precision(quote, instrument) {
2022 return true;
2023 }
2024
2025 log::warn!(
2026 "Dropping {context} for {} due to precision mismatch \
2027 (bid_px={}, ask_px={}, bid_sz={}, ask_sz={}, expected_price={}, expected_size={})",
2028 instrument.id(),
2029 quote.bid_price.precision,
2030 quote.ask_price.precision,
2031 quote.bid_size.precision,
2032 quote.ask_size.precision,
2033 instrument.price_precision(),
2034 instrument.size_precision(),
2035 );
2036 false
2037}
2038
2039fn check_trade_or_drop(context: &str, trade: &TradeTick, instrument: &InstrumentAny) -> bool {
2040 if trade_matches_instrument_precision(trade, instrument) {
2041 return true;
2042 }
2043
2044 log::warn!(
2045 "Dropping {context} for {} due to precision mismatch \
2046 (px={}, sz={}, expected_price={}, expected_size={})",
2047 instrument.id(),
2048 trade.price.precision,
2049 trade.size.precision,
2050 instrument.price_precision(),
2051 instrument.size_precision(),
2052 );
2053 false
2054}
2055
2056fn check_bar_or_drop(context: &str, bar: &Bar, instrument: &InstrumentAny) -> bool {
2057 if bar_matches_instrument_precision(bar, instrument) {
2058 return true;
2059 }
2060
2061 log::warn!(
2062 "Dropping {context} for {} due to precision mismatch \
2063 (open={}, high={}, low={}, close={}, volume={}, expected_price={}, expected_size={})",
2064 instrument.id(),
2065 bar.open.precision,
2066 bar.high.precision,
2067 bar.low.precision,
2068 bar.close.precision,
2069 bar.volume.precision,
2070 instrument.price_precision(),
2071 instrument.size_precision(),
2072 );
2073 false
2074}
2075
2076fn quote_matches_instrument_precision(quote: &QuoteTick, instrument: &InstrumentAny) -> bool {
2077 let price_precision = instrument.price_precision();
2078 let size_precision = instrument.size_precision();
2079
2080 quote.bid_price.precision == price_precision
2081 && quote.ask_price.precision == price_precision
2082 && quote.bid_size.precision == size_precision
2083 && quote.ask_size.precision == size_precision
2084}
2085
2086fn trade_matches_instrument_precision(trade: &TradeTick, instrument: &InstrumentAny) -> bool {
2087 let price_precision = instrument.price_precision();
2088 let size_precision = instrument.size_precision();
2089
2090 trade.price.precision == price_precision && trade.size.precision == size_precision
2091}
2092
2093fn bar_matches_instrument_precision(bar: &Bar, instrument: &InstrumentAny) -> bool {
2094 let price_precision = instrument.price_precision();
2095 let size_precision = instrument.size_precision();
2096
2097 bar.open.precision == price_precision
2098 && bar.high.precision == price_precision
2099 && bar.low.precision == price_precision
2100 && bar.close.precision == price_precision
2101 && bar.volume.precision == size_precision
2102}