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