nautilus_execution/order_emulator/
handlers.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::any::Any;
17
18use nautilus_common::{messages::execution::TradingCommand, msgbus::handler::MessageHandler};
19use nautilus_core::WeakCell;
20use nautilus_model::events::OrderEventAny;
21use ustr::Ustr;
22
23use super::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 MessageHandler 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    fn as_any(&self) -> &dyn Any {
55        self
56    }
57}
58
59#[derive(Debug)]
60pub struct OrderEmulatorOnEventHandler {
61    id: Ustr,
62    emulator: WeakCell<OrderEmulator>,
63}
64
65impl OrderEmulatorOnEventHandler {
66    #[inline]
67    #[must_use]
68    pub const fn new(id: Ustr, emulator: WeakCell<OrderEmulator>) -> Self {
69        Self { id, emulator }
70    }
71}
72
73impl MessageHandler for OrderEmulatorOnEventHandler {
74    fn id(&self) -> Ustr {
75        self.id
76    }
77
78    fn handle(&self, msg: &dyn Any) {
79        if let Some(emulator) = self.emulator.upgrade() {
80            if let Some(event) = msg.downcast_ref::<OrderEventAny>() {
81                emulator.borrow_mut().on_event(event.clone());
82            } else {
83                log::error!("OrderEmulator on_event received unexpected message type");
84            }
85        }
86    }
87
88    fn as_any(&self) -> &dyn Any {
89        self
90    }
91}