1use std::{
17 cell::RefCell,
18 fmt::{Debug, Display},
19 rc::Rc,
20};
21
22use ahash::AHashMap;
23use nautilus_common::{cache::Cache, clock::Clock, messages::execution::SubmitOrder};
24use nautilus_core::UUID4;
25use nautilus_model::{
26 enums::{ContingencyType, OrderStatus},
27 events::{
28 OrderCanceled, OrderEvent, OrderEventAny, OrderExpired, OrderFilled, OrderRejected,
29 OrderUpdated,
30 },
31 identifiers::{ClientId, ClientOrderId, PositionId},
32 instruments::Instrument,
33 orders::{Order, OrderAny},
34 types::Quantity,
35};
36
37use super::OrderManagerAction;
38
39pub struct OrderManager {
46 clock: Rc<RefCell<dyn Clock>>,
47 cache: Rc<RefCell<Cache>>,
48 active_local: bool,
49 submit_order_commands: AHashMap<ClientOrderId, SubmitOrder>,
50 oto_target_quantities: AHashMap<ClientOrderId, Quantity>,
51}
52
53impl Debug for OrderManager {
54 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55 f.debug_struct(stringify!(OrderManager))
56 .field("pending_commands", &self.submit_order_commands.len())
57 .finish()
58 }
59}
60
61impl OrderManager {
62 pub fn new(
64 clock: Rc<RefCell<dyn Clock>>,
65 cache: Rc<RefCell<Cache>>,
66 active_local: bool,
67 ) -> Self {
68 Self {
69 clock,
70 cache,
71 active_local,
72 submit_order_commands: AHashMap::new(),
73 oto_target_quantities: AHashMap::new(),
74 }
75 }
76
77 #[must_use]
78 pub fn get_submit_order_commands(&self) -> AHashMap<ClientOrderId, SubmitOrder> {
80 self.submit_order_commands.clone()
81 }
82
83 pub fn cache_submit_order_command(&mut self, command: SubmitOrder) {
85 self.submit_order_commands
86 .insert(command.client_order_id, command);
87 }
88
89 pub fn pop_submit_order_command(
91 &mut self,
92 client_order_id: ClientOrderId,
93 ) -> Option<SubmitOrder> {
94 self.submit_order_commands.remove(&client_order_id)
95 }
96
97 pub fn reset(&mut self) {
99 self.submit_order_commands.clear();
100 self.oto_target_quantities.clear();
101 }
102
103 pub fn cancel_order(&mut self, order: &OrderAny) -> Vec<OrderManagerAction> {
105 let client_order_id = order.client_order_id();
106 let cache = self.cache.borrow();
107
108 if cache.is_order_pending_cancel_local(&client_order_id) {
109 return Vec::new();
110 }
111
112 if order.is_closed() || cache.is_order_closed(&client_order_id) {
113 log::warn!("Cannot cancel order: already closed");
114 return Vec::new();
115 }
116
117 drop(cache);
118 self.submit_order_commands.remove(&client_order_id);
119
120 vec![OrderManagerAction::CancelLocal(order.clone())]
121 }
122
123 pub fn modify_order_quantity(
125 &mut self,
126 order: &OrderAny,
127 new_quantity: Quantity,
128 ) -> Vec<OrderManagerAction> {
129 vec![OrderManagerAction::ModifyLocalQuantity {
130 order: order.clone(),
131 quantity: new_quantity,
132 }]
133 }
134
135 pub fn create_new_submit_order(
141 &mut self,
142 order: &OrderAny,
143 position_id: Option<PositionId>,
144 client_id: Option<ClientId>,
145 correlation_id: Option<UUID4>,
146 ) -> anyhow::Result<Vec<OrderManagerAction>> {
147 let mut actions = Vec::new();
148 let order_exists = self.cache.borrow().order_exists(&order.client_order_id());
149
150 self.cache
151 .borrow_mut()
152 .add_order(order.clone(), position_id, client_id, true)?;
153 if !order_exists {
154 let event = OrderEventAny::Initialized(order.init_event().clone());
155 actions.push(OrderManagerAction::PublishInitialized(event));
156 }
157
158 let submit = SubmitOrder::new(
159 order.trader_id(),
160 client_id,
161 order.strategy_id(),
162 order.instrument_id(),
163 order.client_order_id(),
164 order.init_event().clone(),
165 order.exec_algorithm_id(),
166 position_id,
167 None, UUID4::new(),
169 self.clock.borrow().timestamp_ns(),
170 correlation_id,
171 );
172
173 self.cache_submit_order_command(submit.clone());
174
175 if order.emulation_trigger().is_some() {
176 actions.push(OrderManagerAction::SubmitToEmulator(submit));
177 } else {
178 match order.exec_algorithm_id() {
179 Some(exec_algorithm_id) => {
180 actions.push(OrderManagerAction::SubmitToAlgorithm {
181 command: submit,
182 exec_algorithm_id,
183 });
184 }
185 None => actions.push(OrderManagerAction::SubmitToRisk(submit)),
186 }
187 }
188
189 Ok(actions)
190 }
191
192 #[must_use]
193 pub fn should_manage_order(&self, order: &OrderAny) -> bool {
195 self.active_local == order.is_active_local()
196 }
197
198 pub fn handle_event(&mut self, event: &OrderEventAny) -> Vec<OrderManagerAction> {
203 match event {
204 OrderEventAny::Denied(event) => {
205 self.submit_order_commands.remove(&event.client_order_id);
206 self.oto_target_quantities.remove(&event.client_order_id);
207 let order = self.cache.borrow().order_owned(&event.client_order_id);
208
209 match order {
210 Some(order)
211 if order.previous_status() == Some(OrderStatus::Released)
212 && order.contingency_type().is_some() =>
213 {
214 self.handle_contingencies(&order)
215 }
216 _ => Vec::new(),
217 }
218 }
219 OrderEventAny::Rejected(event) => self.handle_order_rejected(*event),
220 OrderEventAny::Canceled(event) => self.handle_order_canceled(*event),
221 OrderEventAny::Expired(event) => self.handle_order_expired(*event),
222 OrderEventAny::Updated(event) => self.handle_order_updated(*event),
223 OrderEventAny::ModifyDenied(_) | OrderEventAny::ModifyRejected(_) => {
224 let client_order_id = event.client_order_id();
225 if !self
226 .cache
227 .borrow()
228 .order(&client_order_id)
229 .is_some_and(|order| order.has_pending_update_command())
230 {
231 self.oto_target_quantities.remove(&client_order_id);
232 }
233
234 Vec::new()
235 }
236 OrderEventAny::Filled(event) => self.handle_order_filled(event),
237 _ => Vec::new(),
238 }
239 }
240
241 pub fn handle_order_rejected(&mut self, rejected: OrderRejected) -> Vec<OrderManagerAction> {
243 self.handle_terminal_event(&rejected)
244 }
245
246 pub fn handle_order_canceled(&mut self, canceled: OrderCanceled) -> Vec<OrderManagerAction> {
248 self.handle_terminal_event(&canceled)
249 }
250
251 pub fn handle_order_expired(&mut self, expired: OrderExpired) -> Vec<OrderManagerAction> {
253 self.handle_terminal_event(&expired)
254 }
255
256 pub fn handle_order_updated(&mut self, updated: OrderUpdated) -> Vec<OrderManagerAction> {
257 let Some(order) = self.cache.borrow().order_owned(&updated.client_order_id) else {
258 log::error!(
259 "Cannot handle `OrderUpdated`: order for client_order_id: {} not found, {}",
260 updated.client_order_id,
261 updated
262 );
263 return Vec::new();
264 };
265
266 let mut actions = Vec::new();
267
268 if self.should_manage_order(&order) && !order.is_closed() {
269 if let Some(quantity) = self
270 .oto_target_quantities
271 .get(&updated.client_order_id)
272 .copied()
273 .filter(|quantity| *quantity != order.quantity())
274 .filter(|quantity| order.filled_qty() < *quantity)
275 {
276 actions.extend(self.modify_order_quantity(&order, quantity));
277 }
278 } else {
279 self.oto_target_quantities.remove(&updated.client_order_id);
280 }
281
282 if order.contingency_type().is_some() {
283 actions.extend(self.handle_contingencies_update(&order));
284 }
285
286 actions
287 }
288
289 pub fn handle_order_filled(&mut self, filled: &OrderFilled) -> Vec<OrderManagerAction> {
291 let Some(order) = self.cache.borrow().order_owned(&filled.client_order_id) else {
292 log::error!(
293 "Cannot handle `OrderFilled`: order for client_order_id: {} not found, {}",
294 filled.client_order_id,
295 filled
296 );
297 return Vec::new();
298 };
299
300 let mut actions = Vec::new();
301
302 if !self.should_manage_order(&order) || order.is_closed() {
303 self.oto_target_quantities.remove(&filled.client_order_id);
304 }
305
306 match order.contingency_type() {
307 Some(ContingencyType::Oto) => {
308 let cached_position_id = self
309 .cache
310 .borrow()
311 .position_id(&order.client_order_id())
312 .copied();
313
314 if let (Some(fill_position_id), Some(cached_position_id)) =
315 (filled.position_id, cached_position_id)
316 && fill_position_id != cached_position_id
317 {
318 log::error!(
319 "Cannot handle OTO fill: event position {fill_position_id} does not match cached position {cached_position_id}"
320 );
321 return actions;
322 }
323
324 let position_id = filled.position_id.or(cached_position_id);
325 let client_id = self
326 .cache
327 .borrow()
328 .client_id(&order.client_order_id())
329 .copied();
330
331 let (parent_filled_qty, is_spawn_active) = match order.exec_spawn_id() {
332 Some(spawn_id) => {
333 let cache = self.cache.borrow();
334 let Some(filled_qty) = cache.exec_spawn_total_filled_qty(&spawn_id, false)
335 else {
336 log::error!("Failed to get spawn filled quantity for {spawn_id}");
337 return actions;
338 };
339 let is_spawn_active = cache
340 .exec_spawn_total_leaves_qty(&spawn_id, true)
341 .is_some_and(|leaves_qty| leaves_qty.is_positive());
342 (filled_qty, is_spawn_active)
343 }
344 None => (order.filled_qty(), false),
345 };
346
347 let Some(linked_orders) = order.linked_order_ids() else {
348 log::error!("No linked orders found for OTO order");
349 return actions;
350 };
351
352 for client_order_id in linked_orders {
353 if order.parent_order_id().as_ref() == Some(client_order_id) {
354 continue;
355 }
356
357 let Some(mut child_order) = self.cache.borrow().order_owned(client_order_id)
358 else {
359 log::error!(
360 "Cannot find OTO child order for client_order_id: {client_order_id}"
361 );
362 continue;
363 };
364
365 if !self.should_manage_order(&child_order) || child_order.is_closed() {
366 self.oto_target_quantities.remove(client_order_id);
367 continue;
368 }
369
370 if self.active_local && child_order.position_id().is_none() {
371 child_order.set_position_id(position_id);
372 }
373
374 let Some(child_quantity) = self.position_adjusted_oto_quantity(
375 &order,
376 &child_order,
377 parent_filled_qty,
378 position_id,
379 ) else {
380 continue;
381 };
382
383 if child_quantity.is_zero() {
384 self.oto_target_quantities.remove(client_order_id);
385
386 if order.is_closed() && !is_spawn_active {
387 actions.extend(self.cancel_order(&child_order));
388 }
389 continue;
390 }
391
392 actions.extend(self.sync_oto_quantity(&child_order, child_quantity));
393
394 if child_quantity.is_positive()
395 && self.active_local
396 && !self
397 .submit_order_commands
398 .contains_key(&child_order.client_order_id())
399 {
400 match self.create_new_submit_order(
401 &child_order,
402 position_id,
403 client_id,
404 None,
405 ) {
406 Ok(new_actions) => actions.extend(new_actions),
407 Err(e) => log::error!("Failed to create new submit order: {e}"),
408 }
409 }
410 }
411 }
412 Some(ContingencyType::Oco) => {
413 let Some(linked_orders) = order.linked_order_ids() else {
414 log::error!("No linked orders found for OCO order");
415 return actions;
416 };
417
418 for client_order_id in linked_orders {
419 let Some(contingent_order) = self.cache.borrow().order_owned(client_order_id)
420 else {
421 log::error!(
422 "Cannot find OCO contingent order for client_order_id: {client_order_id}"
423 );
424 continue;
425 };
426
427 if !self.should_manage_order(&contingent_order) || contingent_order.is_closed()
429 {
430 continue;
431 }
432
433 if contingent_order.client_order_id() != order.client_order_id() {
434 actions.extend(self.cancel_order(&contingent_order));
435 }
436 }
437 }
438 Some(ContingencyType::Ouo) => actions.extend(self.handle_contingencies(&order)),
439 _ => {}
440 }
441
442 actions
443 }
444
445 pub fn handle_contingencies(&mut self, order: &OrderAny) -> Vec<OrderManagerAction> {
447 let mut actions = Vec::new();
448
449 let (filled_qty, leaves_qty, is_spawn_active) =
450 if let Some(exec_spawn_id) = order.exec_spawn_id() {
451 let cache = self.cache.borrow();
452 let Some(filled) = cache.exec_spawn_total_filled_qty(&exec_spawn_id, false) else {
453 log::error!("Failed to get spawn filled quantity for {exec_spawn_id}");
454 return actions;
455 };
456 let leaves = cache
457 .exec_spawn_total_leaves_qty(&exec_spawn_id, true)
458 .unwrap_or_else(|| Quantity::zero(filled.precision));
459
460 (filled, leaves, leaves.is_positive())
461 } else {
462 (order.filled_qty(), order.leaves_qty(), false)
463 };
464
465 let Some(linked_orders) = order.linked_order_ids() else {
466 log::error!("No linked orders found");
467 return actions;
468 };
469
470 for client_order_id in linked_orders {
471 if order.contingency_type() == Some(ContingencyType::Oto)
472 && order.parent_order_id().as_ref() == Some(client_order_id)
473 {
474 continue;
475 }
476
477 let Some(contingent_order) = self.cache.borrow().order_owned(client_order_id) else {
478 log::error!("Cannot find contingent order for client_order_id: {client_order_id}");
479 continue;
480 };
481
482 if !self.should_manage_order(&contingent_order) {
483 self.oto_target_quantities.remove(client_order_id);
484 continue;
485 }
486
487 if client_order_id == &order.client_order_id() {
488 continue;
489 }
490
491 if contingent_order.is_closed() {
492 self.submit_order_commands.remove(client_order_id);
493 self.oto_target_quantities.remove(client_order_id);
494 continue;
495 }
496
497 match order.contingency_type() {
498 Some(ContingencyType::Oto) => {
499 if filled_qty.is_zero()
500 && order.is_closed()
501 && (order.exec_spawn_id().is_none() || !is_spawn_active)
502 {
503 self.oto_target_quantities.remove(client_order_id);
504 actions.extend(self.cancel_order(&contingent_order));
505 continue;
506 }
507
508 let position_id = self.oto_parent_position_id(order);
509
510 let Some(child_quantity) = self.position_adjusted_oto_quantity(
511 order,
512 &contingent_order,
513 filled_qty,
514 position_id,
515 ) else {
516 continue;
517 };
518
519 if child_quantity.is_zero() {
520 self.oto_target_quantities.remove(client_order_id);
521
522 if order.is_closed()
523 && (order.exec_spawn_id().is_none() || !is_spawn_active)
524 {
525 actions.extend(self.cancel_order(&contingent_order));
526 }
527 } else {
528 actions.extend(self.sync_oto_quantity(&contingent_order, child_quantity));
529 }
530 }
531 Some(ContingencyType::Oco)
532 if order.is_closed()
533 && (order.exec_spawn_id().is_none() || !is_spawn_active) =>
534 {
535 actions.extend(self.cancel_order(&contingent_order));
536 }
537 Some(ContingencyType::Ouo) => {
538 if (leaves_qty.is_zero() && order.exec_spawn_id().is_some())
539 || (order.is_closed()
540 && (order.exec_spawn_id().is_none() || !is_spawn_active))
541 || contingent_order.filled_qty() >= leaves_qty
542 {
543 actions.extend(self.cancel_order(&contingent_order));
544 } else if leaves_qty != contingent_order.leaves_qty() {
545 actions.extend(self.modify_order_quantity(&contingent_order, leaves_qty));
546 }
547 }
548 _ => {}
549 }
550 }
551
552 actions
553 }
554
555 pub fn handle_contingencies_update(&mut self, order: &OrderAny) -> Vec<OrderManagerAction> {
557 let mut actions = Vec::new();
558 let contingency_type = order.contingency_type();
559
560 let quantity = match order.exec_spawn_id() {
561 Some(exec_spawn_id) => {
562 if let Some(qty) = self
563 .cache
564 .borrow()
565 .exec_spawn_total_quantity(&exec_spawn_id, true)
566 {
567 qty
568 } else {
569 log::error!("Failed to get spawn total quantity for {exec_spawn_id}");
570 return actions;
571 }
572 }
573 None => order.quantity(),
574 };
575
576 if quantity.is_zero() {
577 return actions;
578 }
579
580 let leaves_qty = self.ouo_leaves_qty(order);
581
582 let oto_filled_qty = if contingency_type == Some(ContingencyType::Oto) {
583 Some(match order.exec_spawn_id() {
584 Some(exec_spawn_id) => {
585 if let Some(qty) = self
586 .cache
587 .borrow()
588 .exec_spawn_total_filled_qty(&exec_spawn_id, false)
589 {
590 qty
591 } else {
592 log::error!("Failed to get spawn filled quantity for {exec_spawn_id}");
593 return actions;
594 }
595 }
596 None => order.filled_qty(),
597 })
598 } else {
599 None
600 };
601
602 let Some(linked_orders) = order.linked_order_ids() else {
603 log::error!("No linked orders found for contingent order");
604 return actions;
605 };
606
607 for client_order_id in linked_orders {
608 if contingency_type == Some(ContingencyType::Oto)
609 && order.parent_order_id().as_ref() == Some(client_order_id)
610 {
611 continue;
612 }
613
614 let Some(contingent_order) = self.cache.borrow().order_owned(client_order_id) else {
615 log::error!(
616 "Cannot find OCO contingent order for client_order_id: {client_order_id}"
617 );
618 continue;
619 };
620
621 if !self.should_manage_order(&contingent_order) {
622 self.oto_target_quantities.remove(client_order_id);
623 continue;
624 }
625
626 if client_order_id == &order.client_order_id() || contingent_order.is_closed() {
627 self.oto_target_quantities.remove(client_order_id);
628 continue;
629 }
630
631 match contingency_type {
632 Some(ContingencyType::Oto) => {
633 let child_quantity =
634 if let Some(filled_qty) = oto_filled_qty.filter(Quantity::is_positive) {
635 let position_id = self.oto_parent_position_id(order);
636
637 let Some(quantity) = self.position_adjusted_oto_quantity(
638 order,
639 &contingent_order,
640 filled_qty,
641 position_id,
642 ) else {
643 continue;
644 };
645 quantity
646 } else {
647 quantity
648 };
649
650 actions.extend(self.sync_oto_quantity(&contingent_order, child_quantity));
651 }
652 Some(ContingencyType::Ouo) if leaves_qty == contingent_order.leaves_qty() => {}
655 Some(ContingencyType::Ouo) if contingent_order.filled_qty() >= quantity => {
656 actions.extend(self.cancel_order(&contingent_order));
657 }
658 Some(ContingencyType::Ouo) => {
659 let quantity = contingent_order.filled_qty() + leaves_qty;
661 actions.extend(self.modify_order_quantity(&contingent_order, quantity));
662 }
663 _ => {}
664 }
665 }
666
667 actions
668 }
669
670 fn handle_terminal_event(
671 &mut self,
672 event: &(impl OrderEvent + Display),
673 ) -> Vec<OrderManagerAction> {
674 let client_order_id = event.client_order_id();
675 self.oto_target_quantities.remove(&client_order_id);
676
677 let Some(order) = self.cache.borrow().order_owned(&client_order_id) else {
678 log::error!(
679 "Cannot handle `{}`: order for client_order_id: {client_order_id} not found, {event}",
680 event.type_name(),
681 );
682 return Vec::new();
683 };
684
685 if order.contingency_type().is_some() {
686 self.handle_contingencies(&order)
687 } else {
688 Vec::new()
689 }
690 }
691
692 fn ouo_leaves_qty(&self, order: &OrderAny) -> Quantity {
694 match order.exec_spawn_id() {
695 Some(exec_spawn_id) => self
696 .cache
697 .borrow()
698 .exec_spawn_total_leaves_qty(&exec_spawn_id, true)
699 .unwrap_or_else(|| Quantity::zero(order.quantity().precision)),
700 None => order.leaves_qty(),
701 }
702 }
703
704 fn oto_parent_position_id(&self, order: &OrderAny) -> Option<PositionId> {
705 if let Some(position_id) = order.position_id() {
706 return Some(position_id);
707 }
708
709 let cache = self.cache.borrow();
710
711 cache
712 .position_id(&order.client_order_id())
713 .copied()
714 .or_else(|| {
715 order.exec_spawn_id().and_then(|spawn_id| {
716 cache
717 .orders_for_exec_spawn(&spawn_id)
718 .into_iter()
719 .find_map(|spawn_order| spawn_order.position_id())
720 })
721 })
722 }
723
724 fn position_adjusted_oto_quantity(
725 &self,
726 parent_order: &OrderAny,
727 child_order: &OrderAny,
728 filled_qty: Quantity,
729 position_id: Option<PositionId>,
730 ) -> Option<Quantity> {
731 let Some(position_id) = position_id else {
732 return Some(filled_qty);
733 };
734
735 let cache = self.cache.borrow();
736 let Some(parent_instrument) = cache.instrument(&parent_order.instrument_id()) else {
737 log::error!(
738 "Cannot size OTO orders: instrument {} not found in cache",
739 parent_order.instrument_id()
740 );
741 return None;
742 };
743
744 let Some(child_instrument) = cache.instrument(&child_order.instrument_id()) else {
745 log::error!(
746 "Cannot size OTO order {}: instrument {} not found in cache",
747 child_order.client_order_id(),
748 child_order.instrument_id()
749 );
750 return None;
751 };
752
753 let increment = child_instrument.size_increment();
754 if increment.is_zero() {
755 log::error!(
756 "Cannot size OTO orders: size increment is zero for {}",
757 child_order.instrument_id()
758 );
759 return None;
760 }
761
762 let capped = if parent_instrument.is_spread() || !child_order.is_reduce_only() {
763 filled_qty
764 } else {
765 let Some(position) = cache.position(&position_id) else {
766 log::error!("Cannot size OTO orders: position {position_id} not found in cache");
767 return None;
768 };
769
770 let child_filled_qty = child_order.filled_qty();
771 let precision = child_filled_qty.precision.max(position.quantity.precision);
772
773 let (Some(child_filled_qty), Some(position_qty)) = (
774 child_filled_qty.checked_rescale(precision),
775 position.quantity.checked_rescale(precision),
776 ) else {
777 log::error!("Cannot size OTO orders: position quantity scale alignment overflow");
778 return None;
779 };
780
781 let position_cap = child_filled_qty.saturating_add(position_qty);
782 filled_qty.min(position_cap)
783 };
784
785 let Some(target) = capped.checked_floor_to_increment(increment) else {
786 log::error!("Cannot size OTO orders: quantity scale alignment overflow");
787 return None;
788 };
789
790 if child_instrument
791 .min_quantity()
792 .is_some_and(|min_quantity| target < min_quantity)
793 {
794 return Some(Quantity::zero(child_instrument.size_precision()));
795 }
796
797 Some(target)
798 }
799
800 fn sync_oto_quantity(
801 &mut self,
802 order: &OrderAny,
803 quantity: Quantity,
804 ) -> Vec<OrderManagerAction> {
805 let client_order_id = order.client_order_id();
806
807 if quantity.is_zero() {
808 self.oto_target_quantities.remove(&client_order_id);
809 return Vec::new();
810 }
811
812 if order.filled_qty() >= quantity {
813 self.oto_target_quantities.remove(&client_order_id);
814 return self.cancel_order(order);
815 }
816
817 match self.oto_target_quantities.get(&client_order_id).copied() {
818 Some(target) if target == quantity => return Vec::new(),
819 Some(_) if order.quantity() == quantity && !order.is_pending_update() => {
820 self.oto_target_quantities.insert(client_order_id, quantity);
821 return Vec::new();
822 }
823 Some(_) => {}
824 None if order.quantity() == quantity => return Vec::new(),
825 None => {}
826 }
827
828 self.oto_target_quantities.insert(client_order_id, quantity);
829 self.modify_order_quantity(order, quantity)
830 }
831}