Skip to main content

nautilus_coinapi/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
18pub mod config;
19pub mod csv;
20pub mod factories;
21pub mod loaders;
22
23use nautilus_common::factories::{ClientConfig, DataClientFactory};
24use nautilus_core::python::{to_pyruntime_err, to_pyvalue_err};
25use nautilus_system::get_global_pyo3_registry;
26use pyo3::prelude::*;
27
28use crate::{
29    common::consts::{COINAPI, COINAPI_CLIENT_ID},
30    config::{CoinApiDataClientConfig, CoinApiInstrumentSelection},
31    factories::CoinApiDataClientFactory,
32};
33
34#[expect(clippy::needless_pass_by_value)]
35fn extract_coinapi_data_factory(
36    py: Python<'_>,
37    factory: Py<PyAny>,
38) -> PyResult<Box<dyn DataClientFactory>> {
39    match factory.extract::<CoinApiDataClientFactory>(py) {
40        Ok(f) => Ok(Box::new(f)),
41        Err(e) => Err(to_pyvalue_err(format!(
42            "Failed to extract CoinApiDataClientFactory: {e}"
43        ))),
44    }
45}
46
47#[expect(clippy::needless_pass_by_value)]
48fn extract_coinapi_data_config(
49    py: Python<'_>,
50    config: Py<PyAny>,
51) -> PyResult<Box<dyn ClientConfig>> {
52    match config.extract::<CoinApiDataClientConfig>(py) {
53        Ok(c) => Ok(Box::new(c)),
54        Err(e) => Err(to_pyvalue_err(format!(
55            "Failed to extract CoinApiDataClientConfig: {e}"
56        ))),
57    }
58}
59
60/// CoinAPI Python module exposed as `nautilus_trader._libnautilus.coinapi`.
61///
62/// # Errors
63///
64/// Returns an error if adding module attributes or registering an extractor fails.
65#[pymodule]
66pub fn coinapi(m: &Bound<'_, PyModule>) -> PyResult<()> {
67    m.add(stringify!(COINAPI), COINAPI)?;
68    m.add(stringify!(COINAPI_CLIENT_ID), *COINAPI_CLIENT_ID)?;
69    m.add_class::<CoinApiDataClientConfig>()?;
70    m.add_class::<CoinApiDataClientFactory>()?;
71    m.add_class::<loaders::PyCoinApiDataLoader>()?;
72    m.add_class::<CoinApiInstrumentSelection>()?;
73    m.add_class::<csv::CoinApiDeltaStreamIterator>()?;
74    m.add_class::<csv::CoinApiQuoteStreamIterator>()?;
75    m.add_class::<csv::CoinApiTradeStreamIterator>()?;
76
77    let registry = get_global_pyo3_registry();
78
79    if let Err(e) =
80        registry.register_factory_extractor(COINAPI.to_string(), extract_coinapi_data_factory)
81    {
82        return Err(to_pyruntime_err(format!(
83            "Failed to register CoinAPI data factory extractor: {e}"
84        )));
85    }
86
87    if let Err(e) = registry.register_config_extractor(
88        "CoinApiDataClientConfig".to_string(),
89        extract_coinapi_data_config,
90    ) {
91        return Err(to_pyruntime_err(format!(
92            "Failed to register CoinAPI data config extractor: {e}"
93        )));
94    }
95
96    Ok(())
97}
98
99#[cfg(test)]
100mod tests {
101    use nautilus_model::identifiers::ClientId;
102    use pyo3::prelude::*;
103    use rstest::rstest;
104
105    #[rstest]
106    fn test_module_registration() {
107        Python::initialize();
108        Python::attach(|py| {
109            let module = pyo3::wrap_pymodule!(super::coinapi)(py);
110            let module = module.bind(py);
111
112            assert_eq!(module.name().unwrap(), "coinapi");
113            assert_eq!(
114                module
115                    .getattr("COINAPI")
116                    .unwrap()
117                    .extract::<String>()
118                    .unwrap(),
119                "COINAPI",
120            );
121            assert_eq!(
122                module
123                    .getattr("COINAPI_CLIENT_ID")
124                    .unwrap()
125                    .extract::<ClientId>()
126                    .unwrap(),
127                ClientId::from("COINAPI"),
128            );
129
130            for name in [
131                "CoinApiDataLoader",
132                "CoinApiDeltaStreamIterator",
133                "CoinApiQuoteStreamIterator",
134                "CoinApiTradeStreamIterator",
135            ] {
136                assert!(module.hasattr(name).unwrap(), "missing {name}");
137            }
138        });
139    }
140}