Skip to main content

nautilus_interactive_brokers/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`.
17
18use nautilus_common::factories::{ClientConfig, DataClientFactory, ExecutionClientFactory};
19use nautilus_core::python::{to_pyruntime_err, to_pyvalue_err};
20use nautilus_model::data::ensure_rust_extractor_registered;
21use nautilus_system::get_global_pyo3_registry;
22use pyo3::prelude::*;
23
24#[cfg(feature = "gateway")]
25use crate::gateway::dockerized::{ContainerStatus, DockerizedIBGateway};
26use crate::{
27    common::{consts::IB, enums::*},
28    config::{
29        DockerizedIBGatewayConfig, InteractiveBrokersDataClientConfig,
30        InteractiveBrokersExecutionClientConfig, InteractiveBrokersInstrumentProviderConfig,
31        MarketDataType, SymbologyMethod, TradingMode,
32    },
33    data_types::{InteractiveBrokersSubscriptionIdle, register_ib_custom_data},
34    factories::{InteractiveBrokersDataClientFactory, InteractiveBrokersExecutionClientFactory},
35    historical::HistoricalInteractiveBrokersClient,
36    providers::instruments::InteractiveBrokersInstrumentProvider,
37};
38
39pub mod config;
40pub mod conversion;
41pub mod enums;
42pub mod factories;
43pub mod historical;
44pub mod providers;
45
46#[cfg(feature = "gateway")]
47pub mod gateway;
48
49#[expect(
50    clippy::needless_pass_by_value,
51    reason = "Signature must match the registry `FactoryExtractor` function pointer"
52)]
53fn extract_interactive_brokers_data_factory(
54    py: Python<'_>,
55    factory: Py<PyAny>,
56) -> PyResult<Box<dyn DataClientFactory>> {
57    factory
58        .extract::<InteractiveBrokersDataClientFactory>(py)
59        .map(|factory| Box::new(factory) as Box<dyn DataClientFactory>)
60        .map_err(|e| {
61            to_pyvalue_err(format!(
62                "Failed to extract InteractiveBrokersDataClientFactory: {e}"
63            ))
64        })
65}
66
67#[expect(
68    clippy::needless_pass_by_value,
69    reason = "Signature must match the registry `ExecutionFactoryExtractor` function pointer"
70)]
71fn extract_interactive_brokers_exec_factory(
72    py: Python<'_>,
73    factory: Py<PyAny>,
74) -> PyResult<Box<dyn ExecutionClientFactory>> {
75    factory
76        .extract::<InteractiveBrokersExecutionClientFactory>(py)
77        .map(|factory| Box::new(factory) as Box<dyn ExecutionClientFactory>)
78        .map_err(|e| {
79            to_pyvalue_err(format!(
80                "Failed to extract InteractiveBrokersExecutionClientFactory: {e}"
81            ))
82        })
83}
84
85#[expect(
86    clippy::needless_pass_by_value,
87    reason = "Signature must match the registry `ConfigExtractor` function pointer"
88)]
89fn extract_interactive_brokers_data_config(
90    py: Python<'_>,
91    config: Py<PyAny>,
92) -> PyResult<Box<dyn ClientConfig>> {
93    config
94        .extract::<InteractiveBrokersDataClientConfig>(py)
95        .map(|config| Box::new(config) as Box<dyn ClientConfig>)
96        .map_err(|e| {
97            to_pyvalue_err(format!(
98                "Failed to extract InteractiveBrokersDataClientConfig: {e}"
99            ))
100        })
101}
102
103#[expect(
104    clippy::needless_pass_by_value,
105    reason = "Signature must match the registry `ConfigExtractor` function pointer"
106)]
107fn extract_interactive_brokers_exec_config(
108    py: Python<'_>,
109    config: Py<PyAny>,
110) -> PyResult<Box<dyn ClientConfig>> {
111    config
112        .extract::<InteractiveBrokersExecutionClientConfig>(py)
113        .map(|config| Box::new(config) as Box<dyn ClientConfig>)
114        .map_err(|e| {
115            to_pyvalue_err(format!(
116                "Failed to extract InteractiveBrokersExecutionClientConfig: {e}"
117            ))
118        })
119}
120
121/// Exposed through `nautilus_trader.adapters.interactive_brokers`.
122///
123/// # Errors
124///
125/// Returns an error if any bindings fail to register with the Python module.
126#[pymodule]
127pub fn interactive_brokers(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
128    m.add_class::<MarketDataType>()?;
129    m.add_class::<IbAction>()?;
130    m.add_class::<IbArticleType>()?;
131    m.add_class::<IbAuctionStrategy>()?;
132    m.add_class::<IbAuctionType>()?;
133    m.add_class::<IbBondIdentifierKind>()?;
134    m.add_class::<IbBuilderTimeInForce>()?;
135    m.add_class::<IbComboLegOpenClose>()?;
136    m.add_class::<IbConditionConjunction>()?;
137    m.add_class::<IbConditionKind>()?;
138    m.add_class::<IbExerciseAction>()?;
139    m.add_class::<IbFundAssetType>()?;
140    m.add_class::<IbFundDistributionPolicyIndicator>()?;
141    m.add_class::<IbHistoricalBarSize>()?;
142    m.add_class::<IbHistoricalTickType>()?;
143    m.add_class::<IbHistoricalWhatToShow>()?;
144    m.add_class::<IbLegAction>()?;
145    m.add_class::<IbLiquidity>()?;
146    m.add_class::<IbOcaType>()?;
147    m.add_class::<IbOrderOpenClose>()?;
148    m.add_class::<IbOrderOrigin>()?;
149    m.add_class::<IbOptionRight>()?;
150    m.add_class::<IbOrderStatus>()?;
151    m.add_class::<IbOrderType>()?;
152    m.add_class::<IbRealtimeBarSize>()?;
153    m.add_class::<IbRealtimeWhatToShow>()?;
154    m.add_class::<IbReferencePriceType>()?;
155    m.add_class::<IbRiskAversion>()?;
156    m.add_class::<IbRule80A>()?;
157    m.add_class::<IbSecurityType>()?;
158    m.add_class::<IbShortSaleSlot>()?;
159    m.add_class::<IbTickType>()?;
160    m.add_class::<IbTimeInForce>()?;
161    m.add_class::<IbTradingHours>()?;
162    m.add_class::<IbTriggerMethod>()?;
163    m.add_class::<IbTwapStrategyType>()?;
164    m.add_class::<IbVolatilityType>()?;
165    m.add_class::<SymbologyMethod>()?;
166    m.add_class::<InteractiveBrokersSubscriptionIdle>()?;
167    register_ib_custom_data();
168    let _ = ensure_rust_extractor_registered::<InteractiveBrokersSubscriptionIdle>();
169    m.add_class::<InteractiveBrokersDataClientConfig>()?;
170    m.add_class::<InteractiveBrokersExecutionClientConfig>()?;
171    m.add_class::<InteractiveBrokersInstrumentProviderConfig>()?;
172    m.add_class::<DockerizedIBGatewayConfig>()?;
173    m.add_class::<TradingMode>()?;
174    m.add_class::<InteractiveBrokersDataClientFactory>()?;
175    m.add_class::<InteractiveBrokersExecutionClientFactory>()?;
176    m.add_class::<HistoricalInteractiveBrokersClient>()?;
177    m.add_class::<InteractiveBrokersInstrumentProvider>()?;
178
179    #[cfg(feature = "gateway")]
180    {
181        m.add_class::<ContainerStatus>()?;
182        m.add_class::<DockerizedIBGateway>()?;
183    }
184
185    let registry = get_global_pyo3_registry();
186
187    if let Err(e) = registry
188        .register_factory_extractor(IB.to_string(), extract_interactive_brokers_data_factory)
189    {
190        return Err(to_pyruntime_err(format!(
191            "Failed to register Interactive Brokers data factory extractor: {e}"
192        )));
193    }
194
195    if let Err(e) = registry
196        .register_exec_factory_extractor(IB.to_string(), extract_interactive_brokers_exec_factory)
197    {
198        return Err(to_pyruntime_err(format!(
199            "Failed to register Interactive Brokers exec factory extractor: {e}"
200        )));
201    }
202
203    if let Err(e) = registry.register_config_extractor(
204        "InteractiveBrokersDataClientConfig".to_string(),
205        extract_interactive_brokers_data_config,
206    ) {
207        return Err(to_pyruntime_err(format!(
208            "Failed to register Interactive Brokers data config extractor: {e}"
209        )));
210    }
211
212    if let Err(e) = registry.register_config_extractor(
213        "InteractiveBrokersExecutionClientConfig".to_string(),
214        extract_interactive_brokers_exec_config,
215    ) {
216        return Err(to_pyruntime_err(format!(
217            "Failed to register Interactive Brokers exec config extractor: {e}"
218        )));
219    }
220
221    Ok(())
222}