nautilus_execution/order_emulator/
handlers.rs1use std::{any::Any, collections::VecDeque};
17
18use nautilus_common::{messages::execution::TradingCommand, msgbus::Handler};
19use nautilus_core::WeakCell;
20use nautilus_model::events::OrderEventAny;
21use ustr::Ustr;
22
23use super::{PendingMessage, emulator::OrderEmulator};
24
25#[derive(Debug)]
26pub struct OrderEmulatorExecuteHandler {
27 id: Ustr,
28 emulator: WeakCell<OrderEmulator>,
29}
30
31impl OrderEmulatorExecuteHandler {
32 #[inline]
33 #[must_use]
34 pub const fn new(id: Ustr, emulator: WeakCell<OrderEmulator>) -> Self {
35 Self { id, emulator }
36 }
37}
38
39impl Handler<dyn Any> for OrderEmulatorExecuteHandler {
40 fn id(&self) -> Ustr {
41 self.id
42 }
43
44 fn handle(&self, msg: &dyn Any) {
45 if let Some(emulator) = self.emulator.upgrade() {
46 if let Some(command) = msg.downcast_ref::<TradingCommand>() {
47 emulator.borrow_mut().execute(command.clone());
48 } else {
49 log::error!("OrderEmulator received unexpected message type");
50 }
51 }
52 }
53}
54
55#[derive(Debug)]
56pub struct OrderEmulatorOnEventHandler {
57 id: Ustr,
58 emulator: WeakCell<OrderEmulator>,
59 pending_messages: WeakCell<VecDeque<PendingMessage>>,
60}
61
62impl OrderEmulatorOnEventHandler {
63 #[inline]
64 #[must_use]
65 pub(crate) const fn new(
66 id: Ustr,
67 emulator: WeakCell<OrderEmulator>,
68 pending_messages: WeakCell<VecDeque<PendingMessage>>,
69 ) -> Self {
70 Self {
71 id,
72 emulator,
73 pending_messages,
74 }
75 }
76}
77
78impl Handler<OrderEventAny> for OrderEmulatorOnEventHandler {
79 fn id(&self) -> Ustr {
80 self.id
81 }
82
83 fn handle(&self, event: &OrderEventAny) {
84 if let Some(emulator) = self.emulator.upgrade() {
85 match emulator.try_borrow_mut() {
86 Ok(mut emulator) => emulator.on_event(event),
87 Err(_) => {
88 if let Some(pending) = self.pending_messages.upgrade() {
91 pending
92 .borrow_mut()
93 .push_back(PendingMessage::Event(Box::new(event.clone())));
94 }
95 }
96 }
97 }
98 }
99}