Skip to main content

nautilus_common/python/
mod.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
16//! Python bindings from [PyO3](https://pyo3.rs).
17
18#![expect(
19    clippy::missing_errors_doc,
20    reason = "errors documented on underlying Rust methods"
21)]
22#![allow(
23    clippy::unused_self,
24    reason = "PyO3 stub methods take &self for Python API parity even when the body is empty"
25)]
26
27pub mod actor;
28pub mod cache;
29pub mod clock;
30pub mod custom;
31pub mod enums;
32pub mod factory;
33pub mod fifo;
34pub mod greeks;
35pub mod indicators;
36pub mod listener;
37pub mod logging;
38pub mod msgbus;
39pub mod order_factory;
40pub mod runtime;
41pub mod signal;
42pub mod system;
43pub mod timer;
44pub mod wrappers;
45pub mod xrate;
46
47use nautilus_core::python::to_pyvalue_err;
48use pyo3::{PyErr, prelude::*};
49
50use crate::config::ConfigError;
51
52/// Converts a config validation failure to a Python `ValueError`.
53#[must_use]
54#[allow(
55    clippy::needless_pass_by_value,
56    reason = "Result::map_err passes owned errors to conversion functions"
57)]
58pub fn config_error_to_pyvalue_err(e: ConfigError) -> PyErr {
59    to_pyvalue_err(e)
60}
61
62/// Exposed through `nautilus_trader.common`.
63///
64/// # Errors
65///
66/// Returns a `PyErr` if registering any module components fails.
67#[rustfmt::skip]
68#[pymodule]
69pub fn common(_: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
70    m.add_class::<crate::custom::CustomData>()?;
71    m.add_class::<crate::signal::Signal>()?;
72    m.add_class::<crate::runner::SystemChannel>()?;
73    m.add_class::<crate::messages::system::QueueCondition>()?;
74    m.add_class::<crate::messages::system::QueueState>()?;
75    m.add_class::<crate::messages::system::QueueStateChanged>()?;
76    m.add_class::<crate::messages::system::SocketState>()?;
77    m.add_class::<crate::messages::system::SocketStateChanged>()?;
78    m.add_class::<crate::messages::system::ReconnectSocket>()?;
79    m.add_class::<crate::timer::TimeEvent>()?;
80    m.add_class::<crate::cache::CacheConfig>()?;
81    m.add_class::<crate::python::actor::PyDataActor>()?;
82    m.add_class::<crate::python::cache::PyCache>()?;
83    m.add_class::<crate::python::fifo::PyFifoCache>()?;
84    m.add_class::<crate::python::clock::PyClock>()?;
85    m.add_class::<crate::python::order_factory::PyOrderFactory>()?;
86    m.add_class::<crate::python::greeks::PyGreeksCalculator>()?;
87    m.add_class::<crate::python::logging::PyLogger>()?;
88    m.add_class::<crate::actor::data_actor::DataActorConfig>()?;
89    m.add_class::<crate::actor::data_actor::ImportableActorConfig>()?;
90    m.add_class::<crate::msgbus::BusMessage>()?;
91    m.add_class::<crate::msgbus::config::MessageBusConfig>()?;
92    m.add_class::<crate::python::msgbus::PyMessageBus>()?;
93    m.add_class::<crate::enums::ComponentState>()?;
94    m.add_class::<crate::enums::ComponentTrigger>()?;
95    m.add_class::<crate::enums::Environment>()?;
96    m.add_class::<crate::enums::LogColor>()?;
97    m.add_class::<crate::enums::LogLevel>()?;
98    m.add_class::<crate::enums::LogFormat>()?;
99    m.add_class::<crate::enums::SerializationEncoding>()?;
100    m.add_class::<crate::logging::logger::LoggerConfig>()?;
101    m.add_class::<crate::logging::logger::LogGuard>()?;
102    m.add_class::<crate::logging::writer::FileWriterConfig>()?;
103    m.add_function(wrap_pyfunction!(logging::py_init_logging, m)?)?;
104    m.add_function(wrap_pyfunction!(logging::py_logger_flush, m)?)?;
105    m.add_function(wrap_pyfunction!(logging::py_logging_sync_to_disk, m)?)?;
106    m.add_function(wrap_pyfunction!(logging::py_logger_log, m)?)?;
107    m.add_function(wrap_pyfunction!(logging::py_log_header, m)?)?;
108    m.add_function(wrap_pyfunction!(logging::py_log_sysinfo, m)?)?;
109    m.add_function(wrap_pyfunction!(logging::py_logging_clock_set_static_mode, m)?)?;
110    m.add_function(wrap_pyfunction!(logging::py_logging_clock_set_realtime_mode, m)?)?;
111    m.add_function(wrap_pyfunction!(logging::py_logging_clock_set_static_time, m)?)?;
112    #[cfg(feature = "tracing-bridge")]
113    m.add_function(wrap_pyfunction!(logging::py_tracing_is_initialized, m)?)?;
114    #[cfg(feature = "tracing-bridge")]
115    m.add_function(wrap_pyfunction!(logging::py_init_tracing, m)?)?;
116    m.add_function(wrap_pyfunction!(xrate::py_get_exchange_rate, m)?)?;
117
118    #[cfg(feature = "live")]
119    m.add_class::<crate::live::listener::MessageBusListener>()?;
120
121    Ok(())
122}
123
124#[cfg(test)]
125mod tests {
126    use std::sync::Once;
127
128    use pyo3::{Python, exceptions::PyValueError};
129    use rstest::rstest;
130
131    use super::*;
132
133    fn ensure_python_initialized() {
134        static INIT: Once = Once::new();
135        INIT.call_once(|| {
136            Python::initialize();
137        });
138    }
139
140    #[rstest]
141    fn test_config_error_to_pyvalue_err_preserves_display_text() {
142        ensure_python_initialized();
143
144        let error = ConfigError::invalid_format("rate_limit", "expected 'limit/HH:MM:SS'");
145
146        Python::attach(|py| {
147            let py_err = config_error_to_pyvalue_err(error);
148
149            assert!(py_err.is_instance_of::<PyValueError>(py));
150            assert_eq!(
151                py_err.value(py).to_string(),
152                "invalid rate_limit: expected 'limit/HH:MM:SS'"
153            );
154        });
155    }
156}