nautilus_common/python/
handler.rs1use 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 #[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 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 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}