Skip to main content

nautilus_execution/order_emulator/
handlers.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 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};
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 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}
60
61impl OrderEmulatorOnEventHandler {
62    #[inline]
63    #[must_use]
64    pub const fn new(id: Ustr, emulator: WeakCell<OrderEmulator>) -> Self {
65        Self { id, emulator }
66    }
67}
68
69impl Handler<OrderEventAny> for OrderEmulatorOnEventHandler {
70    fn id(&self) -> Ustr {
71        self.id
72    }
73
74    fn handle(&self, event: &OrderEventAny) {
75        if let Some(emulator) = self.emulator.upgrade() {
76            emulator.borrow_mut().on_event(event.clone());
77        }
78    }
79}