nautilus_core/python/mod.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
16#![allow(clippy::doc_markdown, reason = "Python docstrings")]
17
18//! Python bindings and interoperability built using [`PyO3`](https://pyo3.rs).
19
20#![allow(
21 deprecated,
22 reason = "pyo3-stub-gen currently relies on PyO3 initialization helpers marked as deprecated"
23)]
24//!
25//! This sub-module groups together the Rust code that is *only* required when compiling the
26//! `python` feature flag. It provides thin adapters so that NautilusTrader functionality can be
27//! consumed from the `nautilus_trader` Python package without sacrificing type-safety or
28//! performance.
29
30pub mod casing;
31pub mod datetime;
32pub mod enums;
33pub mod parsing;
34pub mod serialization;
35pub mod uuid;
36pub mod version;
37
38use std::fmt::Display;
39
40use pyo3::{
41 Py,
42 conversion::IntoPyObjectExt,
43 exceptions::{PyRuntimeError, PyTypeError, PyValueError},
44 prelude::*,
45 types::PyString,
46 wrap_pyfunction,
47};
48use pyo3_stub_gen::derive::gen_stub_pyfunction;
49
50use crate::{
51 UUID4,
52 consts::{NAUTILUS_USER_AGENT, NAUTILUS_VERSION},
53 datetime::{
54 MILLISECONDS_IN_SECOND, NANOSECONDS_IN_MICROSECOND, NANOSECONDS_IN_MILLISECOND,
55 NANOSECONDS_IN_SECOND,
56 },
57};
58
59/// Safely clones a Python object by acquiring the GIL and properly managing reference counts.
60///
61/// This function exists to break reference cycles between Rust and Python that can occur
62/// when using `Arc<Py<PyAny>>` in callback-holding structs. The original design wrapped
63/// Python callbacks in `Arc` for thread-safe sharing, but this created circular references:
64///
65/// 1. Rust `Arc` holds Python objects → increases Python reference count.
66/// 2. Python objects might reference Rust objects → creates cycles.
67/// 3. Neither side can be garbage collected → memory leak.
68///
69/// By using plain `Py<PyAny>` with GIL-based cloning instead of `Arc<Py<PyAny>>`, we:
70/// - Avoid circular references between Rust and Python memory management.
71/// - Ensure proper Python reference counting under the GIL.
72/// - Allow both Rust and Python garbage collectors to work correctly.
73///
74/// # Safety
75///
76/// This function properly acquires the Python GIL before performing the clone operation,
77/// ensuring thread-safe access to the Python object and correct reference counting.
78#[must_use]
79pub fn clone_py_object(obj: &Py<PyAny>) -> Py<PyAny> {
80 Python::attach(|py| obj.clone_ref(py))
81}
82
83/// Extend `IntoPyObjectExt` helper trait to unwrap `Py<PyAny>` after conversion.
84pub trait IntoPyObjectNautilusExt<'py>: IntoPyObjectExt<'py> {
85 /// Convert `self` into a [`Py<PyAny>`] while *panicking* if the conversion fails.
86 ///
87 /// This is a convenience wrapper around [`IntoPyObjectExt::into_py_any`] that avoids the
88 /// cumbersome `Result` handling when we are certain that the conversion cannot fail (for
89 /// instance when we are converting primitives or other types that already implement the
90 /// necessary PyO3 traits).
91 #[inline]
92 fn into_py_any_unwrap(self, py: Python<'py>) -> Py<PyAny> {
93 self.into_py_any(py)
94 .expect("Failed to convert type to Py<PyAny>")
95 }
96}
97
98impl<'py, T> IntoPyObjectNautilusExt<'py> for T where T: IntoPyObjectExt<'py> {}
99
100/// Gets the type name for the given Python `obj`.
101///
102/// # Errors
103///
104/// Returns a error if accessing the type name fails.
105pub fn get_pytype_name<'py>(obj: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyString>> {
106 obj.get_type().name()
107}
108
109/// Converts any type that implements `Display` to a Python `ValueError`.
110///
111/// # Errors
112///
113/// Returns a Python error with the error string.
114pub fn to_pyvalue_err(e: impl Display) -> PyErr {
115 PyValueError::new_err(e.to_string())
116}
117
118/// Converts any type that implements `Display` to a Python `TypeError`.
119///
120/// # Errors
121///
122/// Returns a Python error with the error string.
123pub fn to_pytype_err(e: impl Display) -> PyErr {
124 PyTypeError::new_err(e.to_string())
125}
126
127/// Converts any type that implements `Display` to a Python `RuntimeError`.
128///
129/// # Errors
130///
131/// Returns a Python error with the error string.
132pub fn to_pyruntime_err(e: impl Display) -> PyErr {
133 PyRuntimeError::new_err(e.to_string())
134}
135
136/// Return a value indicating whether the `obj` is a `PyCapsule`.
137///
138/// Parameters
139/// ----------
140/// obj : Any
141/// The object to check.
142///
143/// Returns
144/// -------
145/// bool
146#[gen_stub_pyfunction(module = "nautilus_trader.core")]
147#[pyfunction(name = "is_pycapsule")]
148#[allow(clippy::needless_pass_by_value)]
149#[allow(unsafe_code)]
150fn py_is_pycapsule(obj: Py<PyAny>) -> bool {
151 unsafe {
152 // PyCapsule_CheckExact checks if the object is exactly a PyCapsule
153 pyo3::ffi::PyCapsule_CheckExact(obj.as_ptr()) != 0
154 }
155}
156
157/// Loaded as `nautilus_pyo3.core`.
158///
159/// # Errors
160///
161/// Returns a `PyErr` if registering any module components fails.
162#[pymodule]
163#[rustfmt::skip]
164pub fn core(_: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
165 m.add(stringify!(NAUTILUS_VERSION), NAUTILUS_VERSION)?;
166 m.add(stringify!(NAUTILUS_USER_AGENT), NAUTILUS_USER_AGENT)?;
167 m.add(stringify!(MILLISECONDS_IN_SECOND), MILLISECONDS_IN_SECOND)?;
168 m.add(stringify!(NANOSECONDS_IN_SECOND), NANOSECONDS_IN_SECOND)?;
169 m.add(stringify!(NANOSECONDS_IN_MILLISECOND), NANOSECONDS_IN_MILLISECOND)?;
170 m.add(stringify!(NANOSECONDS_IN_MICROSECOND), NANOSECONDS_IN_MICROSECOND)?;
171 m.add_class::<UUID4>()?;
172 m.add_function(wrap_pyfunction!(py_is_pycapsule, m)?)?;
173 m.add_function(wrap_pyfunction!(casing::py_convert_to_snake_case, m)?)?;
174 m.add_function(wrap_pyfunction!(datetime::py_secs_to_nanos, m)?)?;
175 m.add_function(wrap_pyfunction!(datetime::py_secs_to_millis, m)?)?;
176 m.add_function(wrap_pyfunction!(datetime::py_millis_to_nanos, m)?)?;
177 m.add_function(wrap_pyfunction!(datetime::py_micros_to_nanos, m)?)?;
178 m.add_function(wrap_pyfunction!(datetime::py_nanos_to_secs, m)?)?;
179 m.add_function(wrap_pyfunction!(datetime::py_nanos_to_millis, m)?)?;
180 m.add_function(wrap_pyfunction!(datetime::py_nanos_to_micros, m)?)?;
181 m.add_function(wrap_pyfunction!(datetime::py_unix_nanos_to_iso8601, m)?)?;
182 m.add_function(wrap_pyfunction!(datetime::py_last_weekday_nanos, m)?)?;
183 m.add_function(wrap_pyfunction!(datetime::py_is_within_last_24_hours, m)?)?;
184 Ok(())
185}