nautilus_common/python/
handler.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 2Nautech 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, sync::Arc};
17
18use nautilus_model::data::Data;
19use pyo3::prelude::*;
20use ustr::Ustr;
21
22use crate::{messages::data::DataResponse, msgbus::handler::MessageHandler};
23
24#[cfg_attr(
25    feature = "python",
26    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.common")
27)]
28#[derive(Debug, Clone)]
29pub struct PythonMessageHandler {
30    id: Ustr,
31    handler: Arc<PyObject>,
32}
33
34#[pymethods]
35impl PythonMessageHandler {
36    /// Creates a new [`PythonMessageHandler`] instance.
37    #[new]
38    #[must_use]
39    pub fn new(id: &str, handler: PyObject) -> Self {
40        let id = Ustr::from(id);
41        Self {
42            id,
43            handler: Arc::new(handler),
44        }
45    }
46}
47
48impl MessageHandler for PythonMessageHandler {
49    #[allow(unused_variables)]
50    fn handle(&self, message: &dyn Any) {
51        // TODO: convert message to PyObject
52        let py_event = ();
53        let result =
54            pyo3::Python::with_gil(|py| self.handler.call_method1(py, "handle", (py_event,)));
55        if let Err(e) = result {
56            eprintln!("Error calling handle method: {e:?}");
57        }
58    }
59
60    fn id(&self) -> Ustr {
61        self.id
62    }
63
64    fn handle_response(&self, _resp: DataResponse) {
65        // TODO: convert message to PyObject
66        let py_event = ();
67        let result =
68            pyo3::Python::with_gil(|py| self.handler.call_method1(py, "handle", (py_event,)));
69        if let Err(e) = result {
70            eprintln!("Error calling handle method: {e:?}");
71        }
72    }
73
74    fn handle_data(&self, _data: Data) {
75        let py_event = ();
76        let result =
77            pyo3::Python::with_gil(|py| self.handler.call_method1(py, "handle", (py_event,)));
78        if let Err(e) = result {
79            eprintln!("Error calling handle method: {e:?}");
80        }
81    }
82
83    fn as_any(&self) -> &dyn Any {
84        self
85    }
86}