Skip to main content

nautilus_pyo3/
lib.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 aggregator crate for [NautilusTrader](https://nautilustrader.io).
17//!
18//! The `nautilus-pyo3` crate collects the Python bindings generated across the NautilusTrader workspace
19//! and re-exports them through a single shared library that can be included in binary wheels.
20//!
21//! # NautilusTrader
22//!
23//! [NautilusTrader](https://nautilustrader.io) is an open-source, production-grade, Rust-native
24//! engine for multi-asset, multi-venue trading systems.
25//!
26//! The system spans research, deterministic simulation, and live execution within a single
27//! event-driven architecture, providing research-to-live semantic parity.
28//!
29//! # Feature Flags
30//!
31//! This crate is primarily intended to be built for Python via
32//! [maturin](https://github.com/PyO3/maturin) and therefore provides a broad set of feature flags
33//! to toggle bindings and optional dependencies:
34//!
35//! - `adapters` (default): Enables all adapter Python bindings except blockchain.
36//! - `arrow`: Enables Apache Arrow support in dependent crates.
37//! - `defi`: Enables DeFi (Decentralized Finance) support, including blockchain adapters.
38//! - `extension-module`: Builds as a Python extension module and is automatically enabled by
39//!   `maturin`.
40//! - `high-precision`: Uses 128-bit value types throughout the workspace.
41//! - `hypersync`: Enables [`hypersync-client`](https://crates.io/crates/hypersync-client)
42//!   support for the blockchain adapter.
43//! - `mimalloc`: Sets [mimalloc](https://crates.io/crates/mimalloc) as Rust's global allocator.
44//! - `postgres`: Enables PostgreSQL (sqlx) back-ends in dependent crates.
45//! - `redis`: Enables Redis based infrastructure in dependent crates.
46//! - `tracing-bridge`: Enables the `tracing` subscriber bridge for log integration.
47
48#![warn(rustc::all)]
49#![deny(unsafe_code)]
50#![deny(unsafe_op_in_unsafe_fn)]
51#![deny(nonstandard_style)]
52#![deny(missing_debug_implementations)]
53#![deny(clippy::missing_errors_doc)]
54#![deny(clippy::missing_panics_doc)]
55#![deny(rustdoc::broken_intra_doc_links)]
56
57use std::{path::Path, time::Duration};
58
59#[cfg(feature = "mimalloc")]
60use mimalloc::MiMalloc;
61use nautilus_common::live::runtime::shutdown_runtime;
62use nautilus_system::python::controller::PyController;
63use pyo3::{prelude::*, pyfunction};
64
65#[cfg(feature = "mimalloc")]
66#[global_allocator]
67static GLOBAL: MiMalloc = MiMalloc;
68
69const RUNTIME_SHUTDOWN_TIMEOUT_SECS: u64 = 10;
70
71#[pyfunction]
72fn _shutdown_nautilus_runtime() {
73    shutdown_runtime(Duration::from_secs(RUNTIME_SHUTDOWN_TIMEOUT_SECS));
74}
75
76/// Registers the NautilusTrader bindings for an embedded Python interpreter.
77///
78/// The embedding binary calls this function before Python initializes, then imports `_libnautilus`
79/// after initialization, before importing `nautilus_trader` or any strategy module.
80/// This exposes `nautilus_trader._libnautilus`. The matching Python
81/// package must be on the import path. The bindings share the embedding binary's
82/// NautilusTrader types and runtime.
83///
84/// # Panics
85///
86/// Panics if Python has already been initialized.
87pub fn register_embedded_module() {
88    pyo3::append_to_inittab!(_libnautilus);
89}
90
91/// Adds each wrapped module to `sys.modules` so Python can import it as a submodule.
92///
93/// See <https://github.com/PyO3/pyo3/issues/2644>.
94#[pymodule] // The name of the function must match `lib.name` in `Cargo.toml`
95fn _libnautilus(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
96    #[cfg(feature = "mimalloc")]
97    nautilus_common::logging::headers::register_allocator_mimalloc();
98
99    let sys = PyModule::import(py, "sys")?;
100    let modules = sys.getattr("modules")?;
101    let sys_modules: &Bound<'_, PyAny> = modules.cast()?;
102
103    let module_name = "nautilus_trader._libnautilus";
104
105    // Set pyo3_nautilus to be recognized as a subpackage
106    sys_modules.set_item(module_name, m)?;
107
108    // nautilus-import-ok: wrap_pymodule! requires fully qualified paths
109    let n = "analysis";
110    let submodule = pyo3::wrap_pymodule!(nautilus_analysis::python::analysis);
111    m.add_wrapped(submodule)?;
112    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
113
114    let n = "core";
115    let submodule = pyo3::wrap_pymodule!(nautilus_core::python::core);
116    m.add_wrapped(submodule)?;
117    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
118
119    let n = "common";
120    let submodule = pyo3::wrap_pymodule!(nautilus_common::python::common);
121    m.add_wrapped(submodule)?;
122    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
123
124    let n = "data";
125    let submodule = pyo3::wrap_pymodule!(nautilus_data::python::data);
126    m.add_wrapped(submodule)?;
127    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
128
129    let n = "execution";
130    let submodule = pyo3::wrap_pymodule!(nautilus_execution::python::execution);
131    m.add_wrapped(submodule)?;
132    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
133
134    let n = "indicators";
135    let submodule = pyo3::wrap_pymodule!(nautilus_indicators::python::indicators);
136    m.add_wrapped(submodule)?;
137    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
138
139    let n = "infrastructure";
140    let submodule = pyo3::wrap_pymodule!(nautilus_infrastructure::python::infrastructure);
141    m.add_wrapped(submodule)?;
142    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
143
144    let n = "live";
145    let submodule = pyo3::wrap_pymodule!(nautilus_live::python::live);
146    m.add_wrapped(submodule)?;
147    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
148
149    let n = "model";
150    let submodule = pyo3::wrap_pymodule!(nautilus_model::python::model);
151    m.add_wrapped(submodule)?;
152    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
153
154    let n = "network";
155    let submodule = pyo3::wrap_pymodule!(nautilus_network::python::network);
156    m.add_wrapped(submodule)?;
157    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
158
159    let n = "persistence";
160    let submodule = pyo3::wrap_pymodule!(nautilus_persistence::python::persistence);
161    m.add_wrapped(submodule)?;
162    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
163
164    let n = "portfolio";
165    let submodule = pyo3::wrap_pymodule!(nautilus_portfolio::python::portfolio);
166    m.add_wrapped(submodule)?;
167    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
168
169    let n = "risk";
170    let submodule = pyo3::wrap_pymodule!(nautilus_risk::python::risk);
171    m.add_wrapped(submodule)?;
172    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
173
174    let n = "serialization";
175    let submodule = pyo3::wrap_pymodule!(nautilus_serialization::python::serialization);
176    m.add_wrapped(submodule)?;
177    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
178
179    let n = "testkit";
180    let submodule = pyo3::wrap_pymodule!(nautilus_testkit::python::testkit);
181    m.add_wrapped(submodule)?;
182    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
183
184    let n = "trading";
185    let submodule = pyo3::wrap_pymodule!(nautilus_trading::python::trading);
186    m.add_wrapped(submodule)?;
187
188    // `Controller` drives the trader, so it lives in nautilus-system which depends on
189    // nautilus-trading and therefore cannot register itself from the trading module
190    m.getattr(n)?
191        .cast::<PyModule>()?
192        .add_class::<PyController>()?;
193    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
194
195    let n = "backtest";
196    let submodule = pyo3::wrap_pymodule!(nautilus_backtest::python::backtest);
197    m.add_wrapped(submodule)?;
198    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
199
200    ////////////////////////////////////////////////////////////////////////////////
201    // Adapters
202    ////////////////////////////////////////////////////////////////////////////////
203
204    #[cfg(feature = "adapters")]
205    {
206        let n = "architect_ax";
207        let submodule = pyo3::wrap_pymodule!(nautilus_architect_ax::python::architect_ax);
208        m.add_wrapped(submodule)?;
209        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
210    }
211
212    #[cfg(feature = "adapters")]
213    {
214        let n = "betfair";
215        let submodule = pyo3::wrap_pymodule!(nautilus_betfair::python::betfair);
216        m.add_wrapped(submodule)?;
217        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
218    }
219
220    #[cfg(feature = "adapters")]
221    {
222        let n = "binance";
223        let submodule = pyo3::wrap_pymodule!(nautilus_binance::python::binance);
224        m.add_wrapped(submodule)?;
225        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
226    }
227
228    #[cfg(feature = "adapters")]
229    {
230        let n = "bybit";
231        let submodule = pyo3::wrap_pymodule!(nautilus_bybit::python::bybit);
232        m.add_wrapped(submodule)?;
233        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
234    }
235
236    #[cfg(feature = "adapters")]
237    {
238        let n = "coinapi";
239        let submodule = pyo3::wrap_pymodule!(nautilus_coinapi::python::coinapi);
240        m.add_wrapped(submodule)?;
241        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
242    }
243
244    #[cfg(feature = "adapters")]
245    {
246        let n = "coinbase";
247        let submodule = pyo3::wrap_pymodule!(nautilus_coinbase::python::coinbase);
248        m.add_wrapped(submodule)?;
249        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
250    }
251
252    #[cfg(feature = "adapters")]
253    {
254        let n = "databento";
255        let submodule = pyo3::wrap_pymodule!(nautilus_databento::python::databento);
256        m.add_wrapped(submodule)?;
257        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
258    }
259
260    #[cfg(feature = "adapters")]
261    {
262        let n = "deribit";
263        let submodule = pyo3::wrap_pymodule!(nautilus_deribit::python::deribit);
264        m.add_wrapped(submodule)?;
265        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
266    }
267
268    #[cfg(feature = "adapters")]
269    {
270        let n = "derive";
271        let submodule = pyo3::wrap_pymodule!(nautilus_derive::python::derive);
272        m.add_wrapped(submodule)?;
273        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
274    }
275
276    #[cfg(feature = "adapters")]
277    {
278        let n = "dydx";
279        let submodule = pyo3::wrap_pymodule!(nautilus_dydx::python::dydx);
280        m.add_wrapped(submodule)?;
281        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
282    }
283
284    #[cfg(feature = "adapters")]
285    {
286        let n = "finfeed";
287        let submodule = pyo3::wrap_pymodule!(nautilus_finfeed::python::finfeed);
288        m.add_wrapped(submodule)?;
289        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
290    }
291
292    #[cfg(feature = "adapters")]
293    {
294        let n = "hyperliquid";
295        let submodule = pyo3::wrap_pymodule!(nautilus_hyperliquid::python::hyperliquid);
296        m.add_wrapped(submodule)?;
297        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
298    }
299
300    #[cfg(feature = "adapters")]
301    {
302        let n = "kalshi";
303        let submodule = pyo3::wrap_pymodule!(nautilus_kalshi::python::kalshi);
304        m.add_wrapped(submodule)?;
305        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
306    }
307
308    #[cfg(feature = "adapters")]
309    {
310        let n = "kraken";
311        let submodule = pyo3::wrap_pymodule!(nautilus_kraken::python::kraken);
312        m.add_wrapped(submodule)?;
313        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
314    }
315
316    #[cfg(feature = "adapters")]
317    {
318        let n = "lighter";
319        let submodule = pyo3::wrap_pymodule!(nautilus_lighter::python::lighter);
320        m.add_wrapped(submodule)?;
321        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
322    }
323
324    #[cfg(feature = "adapters")]
325    {
326        let n = "interactive_brokers";
327        let submodule =
328            pyo3::wrap_pymodule!(nautilus_interactive_brokers::python::interactive_brokers);
329        m.add_wrapped(submodule)?;
330        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
331    }
332
333    #[cfg(feature = "adapters")]
334    {
335        let n = "okx";
336        let submodule = pyo3::wrap_pymodule!(nautilus_okx::python::okx);
337        m.add_wrapped(submodule)?;
338        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
339    }
340
341    #[cfg(feature = "adapters")]
342    {
343        let n = "polymarket";
344        let submodule = pyo3::wrap_pymodule!(nautilus_polymarket::python::polymarket);
345        m.add_wrapped(submodule)?;
346        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
347    }
348
349    #[cfg(feature = "adapters")]
350    {
351        let n = "sandbox";
352        let submodule = pyo3::wrap_pymodule!(nautilus_sandbox::python::sandbox);
353        m.add_wrapped(submodule)?;
354        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
355    }
356
357    #[cfg(feature = "adapters")]
358    {
359        let n = "tardis";
360        let submodule = pyo3::wrap_pymodule!(nautilus_tardis::python::tardis);
361        m.add_wrapped(submodule)?;
362        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
363    }
364
365    #[cfg(feature = "defi")]
366    {
367        // nautilus-import-ok: wrap_pymodule! requires fully qualified paths
368        let n = "blockchain";
369        let submodule = pyo3::wrap_pymodule!(nautilus_blockchain::python::blockchain);
370        m.add_wrapped(submodule)?;
371        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
372    }
373
374    // Register a lightweight shutdown hook so the interpreter waits for the Tokio
375    // runtime to yield once before `Py_Finalize` tears it down.
376    m.add_function(pyo3::wrap_pyfunction!(_shutdown_nautilus_runtime, m)?)?;
377    let shutdown_callable = m.getattr("_shutdown_nautilus_runtime")?;
378    let atexit = PyModule::import(py, "atexit")?;
379    atexit.call_method1("register", (shutdown_callable,))?;
380
381    Ok(())
382}
383
384/// Generate Python type stub info for PyO3 bindings.
385///
386/// Assumes the pyproject.toml is located in the python/ directory relative to the workspace root.
387///
388/// # Panics
389///
390/// Panics if the path locating the pyproject.toml is incorrect.
391///
392/// # Errors
393///
394/// Returns an error if stub information generation fails.
395///
396/// # Reference
397///
398/// - <https://pyo3.rs/latest/python-typing-hints>
399/// - <https://crates.io/crates/pyo3-stub-gen>
400/// - <https://github.com/Jij-Inc/pyo3-stub-gen>
401pub fn stub_info() -> pyo3_stub_gen::Result<pyo3_stub_gen::StubInfo> {
402    let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR"))
403        .parent()
404        .unwrap()
405        .parent()
406        .unwrap();
407    let pyproject_path = workspace_root.join("python").join("pyproject.toml");
408
409    pyo3_stub_gen::StubInfo::from_pyproject_toml(&pyproject_path)
410}