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 = "cryptography";
125    let submodule = pyo3::wrap_pymodule!(nautilus_cryptography::python::cryptography);
126    m.add_wrapped(submodule)?;
127    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
128
129    let n = "data";
130    let submodule = pyo3::wrap_pymodule!(nautilus_data::python::data);
131    m.add_wrapped(submodule)?;
132    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
133
134    let n = "execution";
135    let submodule = pyo3::wrap_pymodule!(nautilus_execution::python::execution);
136    m.add_wrapped(submodule)?;
137    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
138
139    let n = "indicators";
140    let submodule = pyo3::wrap_pymodule!(nautilus_indicators::python::indicators);
141    m.add_wrapped(submodule)?;
142    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
143
144    let n = "infrastructure";
145    let submodule = pyo3::wrap_pymodule!(nautilus_infrastructure::python::infrastructure);
146    m.add_wrapped(submodule)?;
147    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
148
149    let n = "live";
150    let submodule = pyo3::wrap_pymodule!(nautilus_live::python::live);
151    m.add_wrapped(submodule)?;
152    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
153
154    let n = "model";
155    let submodule = pyo3::wrap_pymodule!(nautilus_model::python::model);
156    m.add_wrapped(submodule)?;
157    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
158
159    let n = "network";
160    let submodule = pyo3::wrap_pymodule!(nautilus_network::python::network);
161    m.add_wrapped(submodule)?;
162    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
163
164    let n = "persistence";
165    let submodule = pyo3::wrap_pymodule!(nautilus_persistence::python::persistence);
166    m.add_wrapped(submodule)?;
167    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
168
169    let n = "portfolio";
170    let submodule = pyo3::wrap_pymodule!(nautilus_portfolio::python::portfolio);
171    m.add_wrapped(submodule)?;
172    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
173
174    let n = "risk";
175    let submodule = pyo3::wrap_pymodule!(nautilus_risk::python::risk);
176    m.add_wrapped(submodule)?;
177    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
178
179    let n = "serialization";
180    let submodule = pyo3::wrap_pymodule!(nautilus_serialization::python::serialization);
181    m.add_wrapped(submodule)?;
182    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
183
184    let n = "testkit";
185    let submodule = pyo3::wrap_pymodule!(nautilus_testkit::python::testkit);
186    m.add_wrapped(submodule)?;
187    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
188
189    let n = "trading";
190    let submodule = pyo3::wrap_pymodule!(nautilus_trading::python::trading);
191    m.add_wrapped(submodule)?;
192
193    // `Controller` drives the trader, so it lives in nautilus-system which depends on
194    // nautilus-trading and therefore cannot register itself from the trading module
195    m.getattr(n)?
196        .cast::<PyModule>()?
197        .add_class::<PyController>()?;
198    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
199
200    let n = "backtest";
201    let submodule = pyo3::wrap_pymodule!(nautilus_backtest::python::backtest);
202    m.add_wrapped(submodule)?;
203    sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
204
205    ////////////////////////////////////////////////////////////////////////////////
206    // Adapters
207    ////////////////////////////////////////////////////////////////////////////////
208
209    #[cfg(feature = "adapters")]
210    {
211        let n = "architect_ax";
212        let submodule = pyo3::wrap_pymodule!(nautilus_architect_ax::python::architect_ax);
213        m.add_wrapped(submodule)?;
214        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
215    }
216
217    #[cfg(feature = "adapters")]
218    {
219        let n = "betfair";
220        let submodule = pyo3::wrap_pymodule!(nautilus_betfair::python::betfair);
221        m.add_wrapped(submodule)?;
222        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
223    }
224
225    #[cfg(feature = "adapters")]
226    {
227        let n = "binance";
228        let submodule = pyo3::wrap_pymodule!(nautilus_binance::python::binance);
229        m.add_wrapped(submodule)?;
230        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
231    }
232
233    #[cfg(feature = "adapters")]
234    {
235        let n = "bybit";
236        let submodule = pyo3::wrap_pymodule!(nautilus_bybit::python::bybit);
237        m.add_wrapped(submodule)?;
238        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
239    }
240
241    #[cfg(feature = "adapters")]
242    {
243        let n = "coinapi";
244        let submodule = pyo3::wrap_pymodule!(nautilus_coinapi::python::coinapi);
245        m.add_wrapped(submodule)?;
246        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
247    }
248
249    #[cfg(feature = "adapters")]
250    {
251        let n = "coinbase";
252        let submodule = pyo3::wrap_pymodule!(nautilus_coinbase::python::coinbase);
253        m.add_wrapped(submodule)?;
254        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
255    }
256
257    #[cfg(feature = "adapters")]
258    {
259        let n = "databento";
260        let submodule = pyo3::wrap_pymodule!(nautilus_databento::python::databento);
261        m.add_wrapped(submodule)?;
262        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
263    }
264
265    #[cfg(feature = "adapters")]
266    {
267        let n = "deribit";
268        let submodule = pyo3::wrap_pymodule!(nautilus_deribit::python::deribit);
269        m.add_wrapped(submodule)?;
270        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
271    }
272
273    #[cfg(feature = "adapters")]
274    {
275        let n = "derive";
276        let submodule = pyo3::wrap_pymodule!(nautilus_derive::python::derive);
277        m.add_wrapped(submodule)?;
278        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
279    }
280
281    #[cfg(feature = "adapters")]
282    {
283        let n = "dydx";
284        let submodule = pyo3::wrap_pymodule!(nautilus_dydx::python::dydx);
285        m.add_wrapped(submodule)?;
286        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
287    }
288
289    #[cfg(feature = "adapters")]
290    {
291        let n = "finfeed";
292        let submodule = pyo3::wrap_pymodule!(nautilus_finfeed::python::finfeed);
293        m.add_wrapped(submodule)?;
294        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
295    }
296
297    #[cfg(feature = "adapters")]
298    {
299        let n = "hyperliquid";
300        let submodule = pyo3::wrap_pymodule!(nautilus_hyperliquid::python::hyperliquid);
301        m.add_wrapped(submodule)?;
302        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
303    }
304
305    #[cfg(feature = "adapters")]
306    {
307        let n = "kalshi";
308        let submodule = pyo3::wrap_pymodule!(nautilus_kalshi::python::kalshi);
309        m.add_wrapped(submodule)?;
310        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
311    }
312
313    #[cfg(feature = "adapters")]
314    {
315        let n = "kraken";
316        let submodule = pyo3::wrap_pymodule!(nautilus_kraken::python::kraken);
317        m.add_wrapped(submodule)?;
318        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
319    }
320
321    #[cfg(feature = "adapters")]
322    {
323        let n = "lighter";
324        let submodule = pyo3::wrap_pymodule!(nautilus_lighter::python::lighter);
325        m.add_wrapped(submodule)?;
326        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
327    }
328
329    #[cfg(feature = "adapters")]
330    {
331        let n = "interactive_brokers";
332        let submodule =
333            pyo3::wrap_pymodule!(nautilus_interactive_brokers::python::interactive_brokers);
334        m.add_wrapped(submodule)?;
335        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
336    }
337
338    #[cfg(feature = "adapters")]
339    {
340        let n = "okx";
341        let submodule = pyo3::wrap_pymodule!(nautilus_okx::python::okx);
342        m.add_wrapped(submodule)?;
343        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
344    }
345
346    #[cfg(feature = "adapters")]
347    {
348        let n = "polymarket";
349        let submodule = pyo3::wrap_pymodule!(nautilus_polymarket::python::polymarket);
350        m.add_wrapped(submodule)?;
351        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
352    }
353
354    #[cfg(feature = "adapters")]
355    {
356        let n = "sandbox";
357        let submodule = pyo3::wrap_pymodule!(nautilus_sandbox::python::sandbox);
358        m.add_wrapped(submodule)?;
359        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
360    }
361
362    #[cfg(feature = "adapters")]
363    {
364        let n = "tardis";
365        let submodule = pyo3::wrap_pymodule!(nautilus_tardis::python::tardis);
366        m.add_wrapped(submodule)?;
367        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
368    }
369
370    #[cfg(feature = "defi")]
371    {
372        // nautilus-import-ok: wrap_pymodule! requires fully qualified paths
373        let n = "blockchain";
374        let submodule = pyo3::wrap_pymodule!(nautilus_blockchain::python::blockchain);
375        m.add_wrapped(submodule)?;
376        sys_modules.set_item(format!("{module_name}.{n}"), m.getattr(n)?)?;
377    }
378
379    // Register a lightweight shutdown hook so the interpreter waits for the Tokio
380    // runtime to yield once before `Py_Finalize` tears it down.
381    m.add_function(pyo3::wrap_pyfunction!(_shutdown_nautilus_runtime, m)?)?;
382    let shutdown_callable = m.getattr("_shutdown_nautilus_runtime")?;
383    let atexit = PyModule::import(py, "atexit")?;
384    atexit.call_method1("register", (shutdown_callable,))?;
385
386    Ok(())
387}
388
389/// Generate Python type stub info for PyO3 bindings.
390///
391/// Assumes the pyproject.toml is located in the python/ directory relative to the workspace root.
392///
393/// # Panics
394///
395/// Panics if the path locating the pyproject.toml is incorrect.
396///
397/// # Errors
398///
399/// Returns an error if stub information generation fails.
400///
401/// # Reference
402///
403/// - <https://pyo3.rs/latest/python-typing-hints>
404/// - <https://crates.io/crates/pyo3-stub-gen>
405/// - <https://github.com/Jij-Inc/pyo3-stub-gen>
406pub fn stub_info() -> pyo3_stub_gen::Result<pyo3_stub_gen::StubInfo> {
407    let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR"))
408        .parent()
409        .unwrap()
410        .parent()
411        .unwrap();
412    let pyproject_path = workspace_root.join("python").join("pyproject.toml");
413
414    pyo3_stub_gen::StubInfo::from_pyproject_toml(&pyproject_path)
415}