Skip to main content

nautilus_interactive_brokers/python/
config.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 for Interactive Brokers configuration types.
17
18use std::str::FromStr;
19
20use nautilus_common::python::config_error_to_pyvalue_err;
21use nautilus_core::{python::to_pyvalue_err, string::secret::SecretString};
22use nautilus_model::{
23    identifiers::{InstrumentId, futures::FuturesYearDigits},
24    types::Currency,
25};
26use pyo3::prelude::*;
27
28use crate::{
29    common::{
30        consts::{DEFAULT_CLIENT_ID, DEFAULT_HOST, DEFAULT_PORT},
31        contracts::parse_configured_contract_from_json,
32        enums::IbSecurityType,
33    },
34    config::{
35        DockerizedIBGatewayConfig, InteractiveBrokersDataClientConfig,
36        InteractiveBrokersExecutionClientConfig, InteractiveBrokersInstrumentProviderConfig,
37        MarketDataType, SymbologyMethod, TradingMode,
38    },
39    python::conversion::py_list_to_json_values,
40};
41
42fn validate_order_id_client_slot(client_id: i32) -> PyResult<()> {
43    if client_id.unsigned_abs().is_multiple_of(1000) {
44        return Err(to_pyvalue_err(format!(
45            "`client_id` must not be a multiple of 1000 for the Rust/PyO3 IB execution client because order ID partitioning uses client_id % 1000; got {client_id}"
46        )));
47    }
48
49    Ok(())
50}
51
52#[pymethods]
53#[pyo3_stub_gen::derive::gen_stub_pymethods]
54impl InteractiveBrokersDataClientConfig {
55    /// Creates a new `InteractiveBrokersDataClientConfig` instance.
56    #[new]
57    #[pyo3(signature = (host=None, port=None, client_id=None, use_regular_trading_hours=None, market_data_type=None, ignore_quote_tick_size_updates=None, connection_timeout=None, request_timeout=None, handle_revised_bars=None, batch_quotes=None, instrument_provider=None, dockerized_gateway=None, all_last_trades=None, subscription_idle_timeout_secs=None, max_reconnect_attempts=None))]
58    #[allow(clippy::too_many_arguments)]
59    fn py_new(
60        host: Option<String>,
61        port: Option<u16>,
62        client_id: Option<i32>,
63        use_regular_trading_hours: Option<bool>,
64        market_data_type: Option<MarketDataType>,
65        ignore_quote_tick_size_updates: Option<bool>,
66        connection_timeout: Option<u64>,
67        request_timeout: Option<u64>,
68        handle_revised_bars: Option<bool>,
69        batch_quotes: Option<bool>,
70        instrument_provider: Option<InteractiveBrokersInstrumentProviderConfig>,
71        dockerized_gateway: Option<&DockerizedIBGatewayConfig>,
72        all_last_trades: Option<bool>,
73        subscription_idle_timeout_secs: Option<u64>,
74        max_reconnect_attempts: Option<u32>,
75    ) -> PyResult<Self> {
76        if dockerized_gateway.is_some() {
77            return Err(to_pyvalue_err(
78                "`dockerized_gateway` is not wired into the Rust/PyO3 IB data client; start `DockerizedIBGateway` separately and pass `host`/`port`",
79            ));
80        }
81
82        let host = host.unwrap_or_else(|| DEFAULT_HOST.to_string());
83        let port = port.unwrap_or(DEFAULT_PORT);
84        let client_id = client_id.unwrap_or(DEFAULT_CLIENT_ID);
85        let request_timeout = request_timeout.unwrap_or(60);
86
87        let config = Self {
88            host,
89            port,
90            client_id,
91            use_regular_trading_hours: use_regular_trading_hours.unwrap_or(true),
92            market_data_type: market_data_type.unwrap_or_default(),
93            ignore_quote_tick_size_updates: ignore_quote_tick_size_updates.unwrap_or(false),
94            connection_timeout: connection_timeout.unwrap_or(300),
95            request_timeout,
96            handle_revised_bars: handle_revised_bars.unwrap_or(false),
97            batch_quotes: batch_quotes.unwrap_or(true),
98            all_last_trades: all_last_trades.unwrap_or_else(|| Self::default().all_last_trades),
99            subscription_idle_timeout_secs,
100            max_reconnect_attempts,
101            instrument_provider: instrument_provider.unwrap_or_default(),
102        };
103
104        config.validate().map_err(to_pyvalue_err)?;
105        Ok(config)
106    }
107
108    /// Returns the host.
109    #[getter]
110    fn host(&self) -> &str {
111        &self.host
112    }
113
114    /// Returns the port.
115    #[getter]
116    fn port(&self) -> u16 {
117        self.port
118    }
119
120    /// Returns the client ID.
121    #[getter]
122    fn client_id(&self) -> i32 {
123        self.client_id
124    }
125
126    /// Returns whether to use regular trading hours only.
127    #[getter]
128    fn use_regular_trading_hours(&self) -> bool {
129        self.use_regular_trading_hours
130    }
131
132    /// Returns the market data type.
133    #[getter]
134    fn market_data_type(&self) -> MarketDataType {
135        self.market_data_type
136    }
137
138    /// Returns whether to ignore quote tick size updates.
139    #[getter]
140    fn ignore_quote_tick_size_updates(&self) -> bool {
141        self.ignore_quote_tick_size_updates
142    }
143
144    /// Returns the connection timeout in seconds.
145    #[getter]
146    fn connection_timeout(&self) -> u64 {
147        self.connection_timeout
148    }
149
150    /// Returns the request timeout in seconds.
151    #[getter]
152    fn request_timeout(&self) -> u64 {
153        self.request_timeout
154    }
155
156    /// Returns whether to handle revised bars.
157    #[getter]
158    fn handle_revised_bars(&self) -> bool {
159        self.handle_revised_bars
160    }
161
162    /// Returns whether to use batch quotes.
163    #[getter]
164    fn batch_quotes(&self) -> bool {
165        self.batch_quotes
166    }
167
168    /// Returns whether tick-by-tick subscriptions include special-condition trades.
169    #[getter]
170    fn all_last_trades(&self) -> bool {
171        self.all_last_trades
172    }
173
174    /// Returns the optional subscription idle interval in seconds.
175    #[getter]
176    fn subscription_idle_timeout_secs(&self) -> Option<u64> {
177        self.subscription_idle_timeout_secs
178    }
179
180    /// Returns the optional bound on ibapi's automatic reconnect attempts.
181    #[getter]
182    fn max_reconnect_attempts(&self) -> Option<u32> {
183        self.max_reconnect_attempts
184    }
185
186    /// Returns the instrument provider configuration.
187    #[getter]
188    fn instrument_provider(&self) -> InteractiveBrokersInstrumentProviderConfig {
189        self.instrument_provider.clone()
190    }
191
192    /// Sets the instrument provider configuration.
193    #[setter]
194    fn set_instrument_provider(
195        &mut self,
196        instrument_provider: InteractiveBrokersInstrumentProviderConfig,
197    ) {
198        self.instrument_provider = instrument_provider;
199    }
200}
201
202#[pymethods]
203#[pyo3_stub_gen::derive::gen_stub_pymethods]
204impl InteractiveBrokersExecutionClientConfig {
205    /// Creates a new `InteractiveBrokersExecutionClientConfig` instance.
206    #[new]
207    #[pyo3(signature = (host=None, port=None, client_id=None, account_id=None, connection_timeout=None, request_timeout=None, fetch_all_open_orders=None, track_option_exercise_from_position_update=None, instrument_provider=None, dockerized_gateway=None, base_currency=None, max_reconnect_attempts=None))]
208    #[allow(clippy::too_many_arguments)]
209    fn py_new(
210        host: Option<String>,
211        port: Option<u16>,
212        client_id: Option<i32>,
213        account_id: Option<String>,
214        connection_timeout: Option<u64>,
215        request_timeout: Option<u64>,
216        fetch_all_open_orders: Option<bool>,
217        track_option_exercise_from_position_update: Option<bool>,
218        instrument_provider: Option<InteractiveBrokersInstrumentProviderConfig>,
219        dockerized_gateway: Option<&DockerizedIBGatewayConfig>,
220        base_currency: Option<Currency>,
221        max_reconnect_attempts: Option<u32>,
222    ) -> PyResult<Self> {
223        if dockerized_gateway.is_some() {
224            return Err(to_pyvalue_err(
225                "`dockerized_gateway` is not wired into the Rust/PyO3 IB execution client; start `DockerizedIBGateway` separately and pass `host`/`port`",
226            ));
227        }
228
229        let host = host.unwrap_or_else(|| DEFAULT_HOST.to_string());
230        let port = port.unwrap_or(DEFAULT_PORT);
231        let client_id = client_id.unwrap_or(DEFAULT_CLIENT_ID);
232        validate_order_id_client_slot(client_id)?;
233        let request_timeout = request_timeout.unwrap_or(60);
234
235        let config = Self {
236            host,
237            port,
238            client_id,
239            account_id,
240            base_currency,
241            connection_timeout: connection_timeout.unwrap_or(300),
242            request_timeout,
243            fetch_all_open_orders: fetch_all_open_orders.unwrap_or(false),
244            track_option_exercise_from_position_update: track_option_exercise_from_position_update
245                .unwrap_or(false),
246            max_reconnect_attempts,
247            instrument_provider: instrument_provider.unwrap_or_default(),
248        };
249
250        config.validate().map_err(config_error_to_pyvalue_err)?;
251        Ok(config)
252    }
253
254    /// Returns the host.
255    #[getter]
256    fn host(&self) -> &str {
257        &self.host
258    }
259
260    /// Returns the port.
261    #[getter]
262    fn port(&self) -> u16 {
263        self.port
264    }
265
266    /// Returns the client ID.
267    #[getter]
268    fn client_id(&self) -> i32 {
269        self.client_id
270    }
271
272    /// Returns the raw IB account code.
273    #[getter]
274    fn account_id(&self) -> Option<String> {
275        self.account_id.clone()
276    }
277
278    /// Returns the account base currency.
279    #[getter]
280    fn base_currency(&self) -> Option<Currency> {
281        self.base_currency
282    }
283
284    /// Returns the connection timeout in seconds.
285    #[getter]
286    fn connection_timeout(&self) -> u64 {
287        self.connection_timeout
288    }
289
290    /// Returns the request timeout in seconds.
291    #[getter]
292    fn request_timeout(&self) -> u64 {
293        self.request_timeout
294    }
295
296    /// Returns whether to fetch all open orders.
297    #[getter]
298    fn fetch_all_open_orders(&self) -> bool {
299        self.fetch_all_open_orders
300    }
301
302    /// Returns whether to track option exercise from position updates.
303    #[getter]
304    fn track_option_exercise_from_position_update(&self) -> bool {
305        self.track_option_exercise_from_position_update
306    }
307
308    /// Returns the optional bound on ibapi's automatic reconnect attempts.
309    #[getter]
310    fn max_reconnect_attempts(&self) -> Option<u32> {
311        self.max_reconnect_attempts
312    }
313
314    /// Returns the instrument provider configuration.
315    #[getter]
316    fn instrument_provider(&self) -> InteractiveBrokersInstrumentProviderConfig {
317        self.instrument_provider.clone()
318    }
319
320    /// Sets the instrument provider configuration.
321    #[setter]
322    fn set_instrument_provider(
323        &mut self,
324        instrument_provider: InteractiveBrokersInstrumentProviderConfig,
325    ) {
326        self.instrument_provider = instrument_provider;
327    }
328}
329
330#[pymethods]
331#[pyo3_stub_gen::derive::gen_stub_pymethods]
332impl InteractiveBrokersInstrumentProviderConfig {
333    /// Creates a new `InteractiveBrokersInstrumentProviderConfig` instance.
334    #[new]
335    #[pyo3(signature = (symbology_method=None, load_ids=None, load_contracts=None, min_expiry_days=None, max_expiry_days=None, build_options_chain=None, build_futures_chain=None, cache_validity_days=None, convert_exchange_to_mic_venue=None, symbol_to_mic_venue=None, filter_sec_types=None, filter_callable=None, cache_path=None, futures_year_digits=None, share_class_space=None))]
336    #[allow(clippy::too_many_arguments)]
337    fn py_new(
338        py: Python<'_>,
339        symbology_method: Option<SymbologyMethod>,
340        load_ids: Option<std::collections::HashSet<InstrumentId>>,
341        load_contracts: Option<Py<pyo3::types::PyList>>,
342        min_expiry_days: Option<u32>,
343        max_expiry_days: Option<u32>,
344        build_options_chain: Option<bool>,
345        build_futures_chain: Option<bool>,
346        cache_validity_days: Option<u32>,
347        convert_exchange_to_mic_venue: Option<bool>,
348        symbol_to_mic_venue: Option<std::collections::HashMap<String, String>>,
349        filter_sec_types: Option<std::collections::HashSet<String>>,
350        filter_callable: Option<String>,
351        cache_path: Option<String>,
352        futures_year_digits: Option<u8>,
353        share_class_space: Option<bool>,
354    ) -> PyResult<Self> {
355        let futures_year_digits = futures_year_digits
356            .map(FuturesYearDigits::try_from)
357            .transpose()
358            .map_err(to_pyvalue_err)?
359            .unwrap_or_default();
360
361        let config = Self {
362            symbology_method: symbology_method.unwrap_or_default(),
363            load_ids: load_ids.unwrap_or_default(),
364            load_contracts: if let Some(c) = load_contracts {
365                py_list_to_json_values(c.bind(py))?
366                    .iter()
367                    .enumerate()
368                    .map(|(index, value)| {
369                        parse_configured_contract_from_json(value).map_err(|e| {
370                            to_pyvalue_err(format!(
371                                "Invalid load_contracts entry at index {index}: {e}"
372                            ))
373                        })
374                    })
375                    .collect::<PyResult<Vec<_>>>()?
376            } else {
377                Vec::new()
378            },
379            min_expiry_days,
380            max_expiry_days,
381            build_options_chain,
382            build_futures_chain,
383            cache_validity_days,
384            convert_exchange_to_mic_venue: convert_exchange_to_mic_venue.unwrap_or(false),
385            symbol_to_mic_venue: symbol_to_mic_venue.unwrap_or_default(),
386            filter_sec_types: filter_sec_types
387                .unwrap_or_default()
388                .into_iter()
389                .map(|value| IbSecurityType::from_str(&value).map_err(to_pyvalue_err))
390                .collect::<PyResult<_>>()?,
391            filter_callable,
392            cache_path,
393            futures_year_digits,
394            share_class_space: share_class_space.unwrap_or(true),
395        };
396
397        config.validate().map_err(config_error_to_pyvalue_err)?;
398        Ok(config)
399    }
400
401    #[getter]
402    fn futures_year_digits(&self) -> u8 {
403        self.futures_year_digits.into()
404    }
405
406    /// Returns whether simplified stock IDs keep IB's share-class space.
407    #[getter]
408    fn share_class_space(&self) -> bool {
409        self.share_class_space
410    }
411
412    /// Returns the symbology method.
413    #[getter]
414    fn symbology_method(&self) -> SymbologyMethod {
415        self.symbology_method
416    }
417
418    /// Returns the instrument IDs to load on startup.
419    #[getter]
420    fn load_ids(&self) -> std::collections::HashSet<InstrumentId> {
421        self.load_ids.clone()
422    }
423
424    /// Returns the IB contracts to load on startup.
425    #[getter]
426    fn load_contracts(&self, py: Python<'_>) -> PyResult<Py<pyo3::types::PyList>> {
427        let json_mod = py.import("json")?;
428        let list = pyo3::types::PyList::empty(py);
429
430        for contract in &self.load_contracts {
431            let json_str = contract.to_json_value().to_string();
432            let dict = json_mod.call_method1("loads", (json_str,))?;
433            list.append(dict)?;
434        }
435
436        Ok(list.unbind())
437    }
438
439    /// Returns the minimum expiry days.
440    #[getter]
441    fn min_expiry_days(&self) -> Option<u32> {
442        self.min_expiry_days
443    }
444
445    /// Returns the maximum expiry days.
446    #[getter]
447    fn max_expiry_days(&self) -> Option<u32> {
448        self.max_expiry_days
449    }
450
451    /// Returns whether to build full options chain.
452    #[getter]
453    fn build_options_chain(&self) -> Option<bool> {
454        self.build_options_chain
455    }
456
457    /// Returns whether to build full futures chain.
458    #[getter]
459    fn build_futures_chain(&self) -> Option<bool> {
460        self.build_futures_chain
461    }
462
463    /// Returns the cache validity in days.
464    #[getter]
465    fn cache_validity_days(&self) -> Option<u32> {
466        self.cache_validity_days
467    }
468
469    /// Returns whether to convert IB exchanges to MIC venues.
470    #[getter]
471    fn convert_exchange_to_mic_venue(&self) -> bool {
472        self.convert_exchange_to_mic_venue
473    }
474
475    /// Returns the symbol to MIC venue mapping.
476    #[getter]
477    fn symbol_to_mic_venue(&self) -> std::collections::HashMap<String, String> {
478        self.symbol_to_mic_venue.clone()
479    }
480
481    /// Returns the filter security types.
482    #[getter]
483    fn filter_sec_types(&self) -> Vec<String> {
484        self.filter_sec_types
485            .iter()
486            .map(ToString::to_string)
487            .collect()
488    }
489
490    /// Returns the custom instrument filter callable path.
491    #[getter]
492    fn filter_callable(&self) -> Option<String> {
493        self.filter_callable.clone()
494    }
495
496    /// Returns the cache path for persistent instrument caching.
497    #[getter]
498    fn cache_path(&self) -> Option<String> {
499        self.cache_path.clone()
500    }
501
502    /// Sets the cache path for persistent instrument caching.
503    #[setter]
504    fn set_cache_path(&mut self, cache_path: Option<String>) {
505        self.cache_path = cache_path;
506    }
507}
508
509#[pymethods]
510#[pyo3_stub_gen::derive::gen_stub_pymethods]
511impl DockerizedIBGatewayConfig {
512    /// Creates a new `DockerizedIBGatewayConfig` instance.
513    #[new]
514    #[pyo3(signature = (username=None, password=None, trading_mode=None, read_only_api=None, timeout=None, container_image=None, vnc_port=None))]
515    fn py_new(
516        username: Option<String>,
517        password: Option<String>,
518        trading_mode: Option<TradingMode>,
519        read_only_api: Option<bool>,
520        timeout: Option<u64>,
521        container_image: Option<String>,
522        vnc_port: Option<u16>,
523    ) -> Self {
524        Self {
525            username: username.map(SecretString::from),
526            password: password.map(SecretString::from),
527            trading_mode: trading_mode.unwrap_or_default(),
528            read_only_api: read_only_api.unwrap_or(true),
529            timeout: timeout.unwrap_or(300),
530            container_image: container_image
531                .unwrap_or_else(|| "ghcr.io/gnzsnz/ib-gateway:stable".to_string()),
532            vnc_port,
533        }
534    }
535
536    /// Returns the username.
537    #[getter]
538    fn username(&self) -> Option<&str> {
539        self.username.as_ref().map(SecretString::expose_secret)
540    }
541
542    #[getter]
543    const fn has_password(&self) -> bool {
544        self.password.is_some()
545    }
546
547    /// Returns the trading mode.
548    #[getter]
549    fn trading_mode(&self) -> TradingMode {
550        self.trading_mode
551    }
552
553    /// Returns whether read-only API is enabled.
554    #[getter]
555    fn read_only_api(&self) -> bool {
556        self.read_only_api
557    }
558
559    /// Returns the timeout in seconds.
560    #[getter]
561    fn timeout(&self) -> u64 {
562        self.timeout
563    }
564
565    /// Returns the container image.
566    #[getter]
567    fn container_image(&self) -> &str {
568        &self.container_image
569    }
570
571    /// Returns the VNC port.
572    #[getter]
573    fn vnc_port(&self) -> Option<u16> {
574        self.vnc_port
575    }
576}
577
578#[cfg(test)]
579mod tests {
580    use pyo3::{prelude::*, types::PyDict};
581    use rstest::rstest;
582
583    use super::InteractiveBrokersInstrumentProviderConfig;
584
585    #[rstest]
586    #[case(None, 2)]
587    #[case(Some(1), 1)]
588    #[case(Some(2), 2)]
589    fn test_python_futures_year_digits(#[case] configured: Option<u8>, #[case] expected: u8) {
590        Python::initialize();
591        Python::attach(|py| {
592            let kwargs = PyDict::new(py);
593            if let Some(digits) = configured {
594                kwargs.set_item("futures_year_digits", digits).unwrap();
595            }
596
597            let config = py
598                .get_type::<InteractiveBrokersInstrumentProviderConfig>()
599                .call((), Some(&kwargs))
600                .unwrap();
601            assert_eq!(
602                config
603                    .getattr("futures_year_digits")
604                    .unwrap()
605                    .extract::<u8>()
606                    .unwrap(),
607                expected
608            );
609        });
610    }
611
612    #[rstest]
613    #[case(0)]
614    #[case(3)]
615    #[case(4)]
616    #[case(u8::MAX)]
617    fn test_python_rejects_invalid_futures_year_digits(#[case] digits: u8) {
618        Python::initialize();
619        Python::attach(|py| {
620            let kwargs = PyDict::new(py);
621            kwargs.set_item("futures_year_digits", digits).unwrap();
622            let error = py
623                .get_type::<InteractiveBrokersInstrumentProviderConfig>()
624                .call((), Some(&kwargs))
625                .unwrap_err();
626            assert!(error.is_instance_of::<pyo3::exceptions::PyValueError>(py));
627            assert_eq!(
628                error.value(py).to_string(),
629                "`futures_year_digits` must be either 1 or 2"
630            );
631        });
632    }
633
634    #[rstest]
635    #[case(None, true)]
636    #[case(Some(true), true)]
637    #[case(Some(false), false)]
638    fn test_python_share_class_space(#[case] configured: Option<bool>, #[case] expected: bool) {
639        Python::initialize();
640        Python::attach(|py| {
641            let kwargs = PyDict::new(py);
642            if let Some(share_class_space) = configured {
643                kwargs
644                    .set_item("share_class_space", share_class_space)
645                    .unwrap();
646            }
647
648            let config = py
649                .get_type::<InteractiveBrokersInstrumentProviderConfig>()
650                .call((), Some(&kwargs))
651                .unwrap();
652            assert_eq!(
653                config
654                    .getattr("share_class_space")
655                    .unwrap()
656                    .extract::<bool>()
657                    .unwrap(),
658                expected
659            );
660        });
661    }
662}