Skip to main content

nautilus_interactive_brokers/
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//! Configuration types for the Interactive Brokers adapter.
17
18use std::{
19    collections::{HashMap, HashSet},
20    fmt::Debug,
21};
22
23use nautilus_common::config::{ConfigResult, check_unique_values};
24use nautilus_core::string::secret::SecretString;
25use nautilus_model::{
26    identifiers::{InstrumentId, futures::FuturesYearDigits},
27    types::Currency,
28};
29use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error};
30
31use crate::common::{
32    consts::{DEFAULT_CLIENT_ID, DEFAULT_HOST, DEFAULT_PORT},
33    contracts::{ConfiguredContract, parse_configured_contract_from_json},
34    enums::IbSecurityType,
35};
36
37/// Market data type for switching between real-time and frozen/delayed.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39#[cfg_attr(
40    feature = "python",
41    pyo3::pyclass(
42        module = "nautilus_trader.adapters.interactive_brokers",
43        from_py_object,
44        rename_all = "SCREAMING_SNAKE_CASE"
45    )
46)]
47#[cfg_attr(
48    feature = "python",
49    pyo3_stub_gen::derive::gen_stub_pyclass_enum(
50        module = "nautilus_trader.adapters.interactive_brokers"
51    )
52)]
53#[derive(Default)]
54pub enum MarketDataType {
55    /// Live market data
56    #[default]
57    Realtime = 1,
58    /// Frozen market data (for when market is closed)
59    Frozen = 2,
60    /// Delayed market data (usually 15-20 minutes)
61    Delayed = 3,
62    /// Delayed frozen market data
63    DelayedFrozen = 4,
64}
65
66impl From<MarketDataType> for ibapi::market_data::MarketDataType {
67    fn from(data_type: MarketDataType) -> Self {
68        match data_type {
69            MarketDataType::Realtime => Self::Realtime,
70            MarketDataType::Frozen => Self::Frozen,
71            MarketDataType::Delayed => Self::Delayed,
72            MarketDataType::DelayedFrozen => Self::DelayedFrozen,
73        }
74    }
75}
76
77/// Configuration for Interactive Brokers data client.
78#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
79#[serde(default)]
80#[cfg_attr(
81    feature = "python",
82    pyo3::pyclass(
83        module = "nautilus_trader.adapters.interactive_brokers",
84        subclass,
85        from_py_object
86    )
87)]
88#[cfg_attr(
89    feature = "python",
90    pyo3_stub_gen::derive::gen_stub_pyclass(
91        module = "nautilus_trader.adapters.interactive_brokers"
92    )
93)]
94pub struct InteractiveBrokersDataClientConfig {
95    /// Host for IB Gateway/TWS.
96    #[builder(default = DEFAULT_HOST.to_string())]
97    pub host: String,
98    /// Port for IB Gateway/TWS.
99    #[builder(default = DEFAULT_PORT)]
100    pub port: u16,
101    /// Client ID.
102    #[builder(default = DEFAULT_CLIENT_ID)]
103    pub client_id: i32,
104    /// Whether to use regular trading hours only (RTH filtering).
105    #[builder(default = true)]
106    pub use_regular_trading_hours: bool,
107    /// Market data type (realtime, delayed, frozen).
108    #[builder(default)]
109    pub market_data_type: MarketDataType,
110    /// Whether to ignore quote tick size updates (filters size-only updates).
111    #[builder(default)]
112    pub ignore_quote_tick_size_updates: bool,
113    /// Connection timeout in seconds.
114    #[builder(default = 300)]
115    pub connection_timeout: u64,
116    /// Request timeout in seconds. Applied to IB API requests (open orders, executions, positions,
117    /// account summary, order update stream, next order id). See execution/core.rs and
118    /// execution/account.rs for call sites.
119    #[builder(default = 60)]
120    pub request_timeout: u64,
121    /// Whether to publish every revision of an open bar.
122    ///
123    /// When `false`, a bar that IB keeps up to date is published once it completes: on IB's
124    /// update after the bar closes, 2 seconds after the close, or on the next bar's first update,
125    /// whichever comes first.
126    #[builder(default)]
127    pub handle_revised_bars: bool,
128    /// Whether to use batch quotes (reqMktData) by default instead of tick-by-tick.
129    #[builder(default = true)]
130    pub batch_quotes: bool,
131    /// Whether to include special-condition trades in tick-by-tick subscriptions.
132    #[builder(default = true)]
133    pub all_last_trades: bool,
134    /// Optional interval without incoming market data before emitting a subscription idle event.
135    pub subscription_idle_timeout_secs: Option<u64>,
136    /// Bound on ibapi's automatic reconnect attempts for the shared client connection
137    /// (`ClientBuilder::max_reconnect_attempts`). `None` keeps ibapi's default. `Some(0)`
138    /// disables reconnection; `Some(u32::MAX)` retries for practical purposes forever.
139    pub max_reconnect_attempts: Option<u32>,
140    /// Instrument provider configuration.
141    #[builder(default)]
142    pub instrument_provider: InteractiveBrokersInstrumentProviderConfig,
143}
144
145impl InteractiveBrokersDataClientConfig {
146    pub(crate) fn validate(&self) -> anyhow::Result<()> {
147        self.instrument_provider.validate()?;
148
149        anyhow::ensure!(
150            self.subscription_idle_timeout_secs != Some(0),
151            "subscription_idle_timeout_secs must be positive when set",
152        );
153
154        if let Some(timeout) = self.subscription_idle_timeout_secs {
155            anyhow::ensure!(
156                std::time::Instant::now()
157                    .checked_add(std::time::Duration::from_secs(timeout))
158                    .is_some(),
159                "subscription_idle_timeout_secs exceeds the supported clock range",
160            );
161        }
162
163        Ok(())
164    }
165}
166
167impl Default for InteractiveBrokersDataClientConfig {
168    fn default() -> Self {
169        Self::builder().build()
170    }
171}
172
173/// Configuration for Interactive Brokers execution client.
174#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
175#[serde(default)]
176#[cfg_attr(
177    feature = "python",
178    pyo3::pyclass(
179        module = "nautilus_trader.adapters.interactive_brokers",
180        subclass,
181        from_py_object
182    )
183)]
184#[cfg_attr(
185    feature = "python",
186    pyo3_stub_gen::derive::gen_stub_pyclass(
187        module = "nautilus_trader.adapters.interactive_brokers"
188    )
189)]
190pub struct InteractiveBrokersExecutionClientConfig {
191    /// Host for IB Gateway/TWS.
192    #[builder(default = DEFAULT_HOST.to_string())]
193    pub host: String,
194    /// Port for IB Gateway/TWS.
195    #[builder(default = DEFAULT_PORT)]
196    pub port: u16,
197    /// Client ID.
198    #[builder(default = DEFAULT_CLIENT_ID)]
199    pub client_id: i32,
200    /// Raw IB account code, such as `DU123456`. The Nautilus account ID becomes
201    /// `{client name}-{code}`.
202    pub account_id: Option<String>,
203    /// Base currency for the account, normally the currency IB reports the account summary in.
204    /// `None` keeps a multi-currency account with one balance per currency.
205    pub base_currency: Option<Currency>,
206    /// Connection timeout in seconds.
207    #[builder(default = 300)]
208    pub connection_timeout: u64,
209    /// Request timeout in seconds for IB API requests (open orders, executions, positions, etc.).
210    #[builder(default = 60)]
211    pub request_timeout: u64,
212    /// Whether to fetch all open orders (reqAllOpenOrders vs reqOpenOrders).
213    #[builder(default)]
214    pub fetch_all_open_orders: bool,
215    /// Whether to track option exercise from position updates.
216    #[builder(default)]
217    pub track_option_exercise_from_position_update: bool,
218    /// Bound on ibapi's automatic reconnect attempts, see the field of the same name on
219    /// [`InteractiveBrokersDataClientConfig`]. The shared-client registry connects once
220    /// per `(host, port, client_id)`, so when data and exec share a connection the first
221    /// creator's value wins.
222    pub max_reconnect_attempts: Option<u32>,
223    /// Instrument provider configuration.
224    #[builder(default)]
225    pub instrument_provider: InteractiveBrokersInstrumentProviderConfig,
226}
227
228impl Default for InteractiveBrokersExecutionClientConfig {
229    fn default() -> Self {
230        Self::builder().build()
231    }
232}
233
234/// Symbology method for converting between IB contracts and Nautilus instrument IDs.
235#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
236#[cfg_attr(
237    feature = "python",
238    pyo3::pyclass(
239        module = "nautilus_trader.adapters.interactive_brokers",
240        from_py_object,
241        rename_all = "SCREAMING_SNAKE_CASE"
242    )
243)]
244#[cfg_attr(
245    feature = "python",
246    pyo3_stub_gen::derive::gen_stub_pyclass_enum(
247        module = "nautilus_trader.adapters.interactive_brokers"
248    )
249)]
250#[derive(Default)]
251pub enum SymbologyMethod {
252    /// Simplified symbology: clean, readable symbols (e.g., "EUR/USD", "ESM23")
253    #[serde(rename = "simplified")]
254    #[default]
255    Simplified,
256    /// Raw symbology: preserves IB raw format with security type suffix (e.g., "EUR.USD=CASH", "AAPL=STK")
257    #[serde(rename = "raw")]
258    Raw,
259}
260
261/// Configuration for Interactive Brokers instrument provider.
262#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
263#[serde(default)]
264#[cfg_attr(
265    feature = "python",
266    pyo3::pyclass(
267        module = "nautilus_trader.adapters.interactive_brokers",
268        subclass,
269        from_py_object
270    )
271)]
272#[cfg_attr(
273    feature = "python",
274    pyo3_stub_gen::derive::gen_stub_pyclass(
275        module = "nautilus_trader.adapters.interactive_brokers"
276    )
277)]
278pub struct InteractiveBrokersInstrumentProviderConfig {
279    /// Symbology method to use for instrument ID conversion.
280    #[builder(default)]
281    pub symbology_method: SymbologyMethod,
282    /// Instrument IDs to load on startup.
283    #[builder(default)]
284    pub load_ids: HashSet<InstrumentId>,
285    /// IB contracts to load on startup.
286    #[builder(default)]
287    #[serde(
288        deserialize_with = "deserialize_configured_contracts",
289        serialize_with = "serialize_configured_contracts"
290    )]
291    pub load_contracts: Vec<ConfiguredContract>,
292    /// Minimum expiry days for options and futures chains.
293    pub min_expiry_days: Option<u32>,
294    /// Maximum expiry days for options and futures chains.
295    pub max_expiry_days: Option<u32>,
296    /// Whether to build full options chain.
297    pub build_options_chain: Option<bool>,
298    /// Whether to build full futures chain.
299    pub build_futures_chain: Option<bool>,
300    /// Cache validity in days (None means no caching).
301    pub cache_validity_days: Option<u32>,
302    /// Whether to convert IB exchanges to MIC venues.
303    #[builder(default)]
304    pub convert_exchange_to_mic_venue: bool,
305    /// Symbol to MIC venue mapping override.
306    #[builder(default)]
307    pub symbol_to_mic_venue: HashMap<String, String>,
308    /// Security types to filter out.
309    #[builder(default)]
310    pub filter_sec_types: HashSet<IbSecurityType>,
311    /// Fully-qualified Python callable path for custom instrument filtering.
312    ///
313    /// Configuring this without the Python feature enabled is an error.
314    pub filter_callable: Option<String>,
315    /// Path to cache file for persistent instrument caching (equivalent to pickle_path in Python).
316    /// If provided, instruments will be cached to disk and loaded from cache if still valid.
317    pub cache_path: Option<String>,
318    /// Year digits in futures IDs: 2 by default, or 1 for existing catalogs and caches.
319    #[builder(default)]
320    pub futures_year_digits: FuturesYearDigits,
321    /// Whether simplified stock IDs keep IB's share-class space (`BRK B`), true by default,
322    /// or use a hyphen (`BRK-B`) for existing catalogs and caches.
323    #[builder(default = true)]
324    pub share_class_space: bool,
325}
326
327impl Default for InteractiveBrokersInstrumentProviderConfig {
328    fn default() -> Self {
329        Self::builder().build()
330    }
331}
332
333fn deserialize_configured_contracts<'de, D>(
334    deserializer: D,
335) -> Result<Vec<ConfiguredContract>, D::Error>
336where
337    D: Deserializer<'de>,
338{
339    Vec::<serde_json::Value>::deserialize(deserializer)?
340        .iter()
341        .map(parse_configured_contract_from_json)
342        .collect::<anyhow::Result<Vec<_>>>()
343        .map_err(D::Error::custom)
344}
345
346fn serialize_configured_contracts<S>(
347    contracts: &[ConfiguredContract],
348    serializer: S,
349) -> Result<S::Ok, S::Error>
350where
351    S: Serializer,
352{
353    contracts
354        .iter()
355        .map(ConfiguredContract::to_json_value)
356        .collect::<Vec<_>>()
357        .serialize(serializer)
358}
359
360/// Trading mode for Dockerized IB Gateway.
361#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
362#[cfg_attr(
363    feature = "python",
364    pyo3::pyclass(
365        module = "nautilus_trader.adapters.interactive_brokers",
366        from_py_object,
367        rename_all = "SCREAMING_SNAKE_CASE"
368    )
369)]
370#[cfg_attr(
371    feature = "python",
372    pyo3_stub_gen::derive::gen_stub_pyclass_enum(
373        module = "nautilus_trader.adapters.interactive_brokers"
374    )
375)]
376#[derive(Default)]
377pub enum TradingMode {
378    /// Paper trading mode.
379    #[serde(rename = "paper")]
380    #[default]
381    Paper,
382    /// Live trading mode.
383    #[serde(rename = "live")]
384    Live,
385}
386
387/// Configuration for Dockerized IB Gateway.
388///
389/// This configuration is for managing containerized IB Gateway instances.
390/// It supports environment variable loading and sensitive data masking.
391#[derive(Clone, Serialize, Deserialize, bon::Builder)]
392#[serde(default)]
393#[cfg_attr(
394    feature = "python",
395    pyo3::pyclass(
396        module = "nautilus_trader.adapters.interactive_brokers",
397        subclass,
398        from_py_object
399    )
400)]
401#[cfg_attr(
402    feature = "python",
403    pyo3_stub_gen::derive::gen_stub_pyclass(
404        module = "nautilus_trader.adapters.interactive_brokers"
405    )
406)]
407pub struct DockerizedIBGatewayConfig {
408    /// Username for IB account (falls back to `TWS_USERNAME` env var via [`Default`]).
409    pub username: Option<SecretString>,
410    /// Password for IB account (falls back to `TWS_PASSWORD` env var via [`Default`]).
411    #[serde(skip_serializing)]
412    pub password: Option<SecretString>,
413    /// Trading mode (paper or live).
414    #[builder(default)]
415    pub trading_mode: TradingMode,
416    /// Whether to enable read-only API mode.
417    #[builder(default = true)]
418    pub read_only_api: bool,
419    /// Timeout in seconds for container startup.
420    #[builder(default = 300)]
421    pub timeout: u64,
422    /// Container image reference.
423    #[builder(default = "ghcr.io/gnzsnz/ib-gateway:stable".to_string())]
424    pub container_image: String,
425    /// VNC port for remote desktop access (None to disable).
426    pub vnc_port: Option<u16>,
427}
428
429impl DockerizedIBGatewayConfig {
430    /// Validate configuration.
431    ///
432    /// # Errors
433    ///
434    /// Returns an error if validation fails.
435    pub fn validate(&self) -> anyhow::Result<()> {
436        if self.timeout == 0 {
437            anyhow::bail!("Timeout must be greater than 0");
438        }
439
440        if self.timeout > 3600 {
441            anyhow::bail!("Timeout must be less than 3600 seconds");
442        }
443
444        if let Some(port) = self.vnc_port
445            && (!(5900..=5999).contains(&port))
446        {
447            anyhow::bail!("VNC port must be between 5900 and 5999");
448        }
449
450        Ok(())
451    }
452}
453
454impl Debug for DockerizedIBGatewayConfig {
455    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
456        f.debug_struct(stringify!(DockerizedIBGatewayConfig))
457            .field("username", &self.username)
458            .field("password", &self.password.as_ref().map(|_| "<redacted>"))
459            .field("trading_mode", &self.trading_mode)
460            .field("read_only_api", &self.read_only_api)
461            .field("timeout", &self.timeout)
462            .field("container_image", &self.container_image)
463            .field("vnc_port", &self.vnc_port)
464            .finish()
465    }
466}
467
468impl Default for DockerizedIBGatewayConfig {
469    fn default() -> Self {
470        Self::builder()
471            .maybe_username(std::env::var("TWS_USERNAME").ok().map(SecretString::from))
472            .maybe_password(std::env::var("TWS_PASSWORD").ok().map(SecretString::from))
473            .build()
474    }
475}
476
477impl InteractiveBrokersInstrumentProviderConfig {
478    /// Validates configured selections.
479    ///
480    /// # Errors
481    ///
482    /// Returns an error if a selection repeats a value.
483    pub fn validate(&self) -> ConfigResult<()> {
484        check_unique_values("load_contracts", &self.load_contracts)
485    }
486}
487
488impl InteractiveBrokersExecutionClientConfig {
489    /// Validates that configured selections contain no duplicates.
490    ///
491    /// # Errors
492    ///
493    /// Returns an error if a selection repeats a value.
494    pub fn validate(&self) -> ConfigResult<()> {
495        self.instrument_provider.validate()
496    }
497}
498
499#[cfg(test)]
500mod tests {
501    use nautilus_common::config::ConfigError;
502    use nautilus_model::{identifiers::futures::FuturesYearDigits, types::Currency};
503    use rstest::rstest;
504
505    use super::{
506        DockerizedIBGatewayConfig, InteractiveBrokersExecutionClientConfig,
507        InteractiveBrokersInstrumentProviderConfig,
508    };
509    use crate::common::enums::IbSecurityType;
510
511    #[rstest]
512    fn test_gateway_password_is_redacted_from_debug_and_serialization() {
513        let config = DockerizedIBGatewayConfig::builder()
514            .username(String::from("user").into())
515            .password(String::from("secret-password").into())
516            .build();
517
518        let debug = format!("{config:?}");
519        let json = serde_json::to_string(&config).unwrap();
520
521        assert!(!debug.contains("secret-password"));
522        assert!(debug.contains("<redacted>"));
523        assert!(!json.contains("secret-password"));
524        assert!(!json.contains("password"));
525    }
526
527    #[rstest]
528    fn test_execution_client_config_base_currency() {
529        let config: InteractiveBrokersExecutionClientConfig =
530            serde_json::from_value(serde_json::json!({"base_currency": "EUR"})).unwrap();
531
532        assert_eq!(config.base_currency, Some(Currency::EUR()));
533        assert_eq!(
534            InteractiveBrokersExecutionClientConfig::default().base_currency,
535            None
536        );
537    }
538
539    #[rstest]
540    fn test_instrument_provider_config_decodes_typed_contracts_and_filters() {
541        let config: InteractiveBrokersInstrumentProviderConfig =
542            serde_json::from_value(serde_json::json!({
543                "load_contracts": [{
544                    "secType": "STK",
545                    "symbol": "AAPL",
546                    "exchange": "SMART",
547                    "conId": 265598
548                }],
549                "filter_sec_types": ["opt"]
550            }))
551            .unwrap();
552
553        assert_eq!(config.load_contracts.len(), 1);
554        assert_eq!(config.load_contracts[0].contract.contract_id, 265598);
555        assert_eq!(
556            config.load_contracts[0].contract.security_type,
557            ibapi::contracts::SecurityType::Stock
558        );
559        assert!(config.filter_sec_types.contains(&IbSecurityType::Option));
560    }
561
562    #[rstest]
563    fn test_instrument_provider_config_keeps_per_contract_chain_settings() {
564        let config: InteractiveBrokersInstrumentProviderConfig =
565            serde_json::from_value(serde_json::json!({
566                "build_futures_chain": true,
567                "load_contracts": [
568                    {
569                        "secType": "STK",
570                        "symbol": "SPY",
571                        "exchange": "SMART",
572                        "primaryExchange": "ARCA",
573                        "build_options_chain": true,
574                        "min_expiry_days": 7,
575                        "max_expiry_days": 14
576                    },
577                    {
578                        "secType": "FUT",
579                        "exchange": "NYMEX",
580                        "localSymbol": "CLZ6",
581                        "build_futures_chain": false
582                    }
583                ]
584            }))
585            .unwrap();
586
587        let spy = &config.load_contracts[0];
588        assert_eq!(spy.build_options_chain, Some(true));
589        assert_eq!(spy.build_futures_chain, None);
590        assert_eq!(spy.min_expiry_days, Some(7));
591        assert_eq!(spy.max_expiry_days, Some(14));
592        assert_eq!(spy.options_chain_exchange, None);
593        assert_eq!(
594            spy.chain_spec_json().unwrap(),
595            serde_json::json!({
596                "build_options_chain": true,
597                "min_expiry_days": 7,
598                "max_expiry_days": 14
599            })
600        );
601
602        let cl = &config.load_contracts[1];
603        assert_eq!(cl.build_futures_chain, Some(false));
604        assert_eq!(
605            cl.chain_spec_json().unwrap(),
606            serde_json::json!({"build_futures_chain": false})
607        );
608
609        let round_trip = serde_json::to_value(&config).unwrap();
610        assert_eq!(
611            round_trip["load_contracts"][0]["build_options_chain"],
612            serde_json::json!(true)
613        );
614        assert_eq!(
615            round_trip["load_contracts"][1]["build_futures_chain"],
616            serde_json::json!(false)
617        );
618    }
619
620    #[rstest]
621    fn test_instrument_provider_config_accepts_con_id_only_contract() {
622        let config: InteractiveBrokersInstrumentProviderConfig =
623            serde_json::from_value(serde_json::json!({
624                "load_contracts": [{"conId": 265598}]
625            }))
626            .unwrap();
627
628        assert_eq!(config.load_contracts[0].contract.contract_id, 265598);
629        assert_eq!(
630            config.load_contracts[0].contract.security_type,
631            ibapi::contracts::SecurityType::Stock
632        );
633    }
634
635    #[rstest]
636    #[case(
637        serde_json::json!({"load_contracts": [{"secType": "UNKNOWN"}]}),
638        "Unknown IB security type: UNKNOWN"
639    )]
640    #[case(
641        serde_json::json!({"load_contracts": [{"secType": "STK", "conId": "265598"}]}),
642        "Configured contract field 'conId' must be an integer"
643    )]
644    #[case(
645        serde_json::json!({"load_contracts": [{"symbol": "SPY"}]}),
646        "Configured contract requires 'secType' as a known IB security type string, or a positive 'conId'"
647    )]
648    #[case(
649        serde_json::json!({"load_contracts": [{"secType": "STK", "build_options_chain": "yes"}]}),
650        "Configured contract field 'build_options_chain' must be a boolean"
651    )]
652    #[case(
653        serde_json::json!({"load_contracts": [{"secType": "STK", "min_expiry_days": -1}]}),
654        "Configured contract field 'min_expiry_days' must be a non-negative integer"
655    )]
656    #[case(
657        serde_json::json!({"filter_sec_types": ["UNKNOWN"]}),
658        "Unknown IB security type: UNKNOWN"
659    )]
660    fn test_instrument_provider_config_rejects_invalid_typed_values(
661        #[case] value: serde_json::Value,
662        #[case] expected: &str,
663    ) {
664        let error = serde_json::from_value::<InteractiveBrokersInstrumentProviderConfig>(value)
665            .unwrap_err();
666
667        assert!(error.to_string().contains(expected), "{error}");
668    }
669
670    #[rstest]
671    #[case("load_contracts", serde_json::json!([{"secType": "STK", "conId": 265598}, {"secType": "STK", "conId": 756733}]))]
672    fn test_instrument_provider_selection_uniqueness(
673        #[case] field: &str,
674        #[case] mut values: serde_json::Value,
675        #[values(false, true)] duplicate: bool,
676    ) {
677        if duplicate {
678            let entries = values.as_array_mut().unwrap();
679            entries.push(entries[0].clone());
680        }
681
682        let mut input =
683            serde_json::to_value(InteractiveBrokersInstrumentProviderConfig::default()).unwrap();
684        input[field] = values;
685        let config: InteractiveBrokersInstrumentProviderConfig =
686            serde_json::from_value(input).unwrap();
687        let original = serde_json::to_value(&config).unwrap();
688
689        let expected = if duplicate {
690            Err(ConfigError::duplicate(field, None))
691        } else {
692            Ok(())
693        };
694
695        let result = config.validate();
696
697        assert_eq!(result, expected);
698        assert_eq!(serde_json::to_value(&config).unwrap(), original);
699    }
700
701    #[rstest]
702    fn test_client_configs_reject_duplicate_provider_selections() {
703        let provider: InteractiveBrokersInstrumentProviderConfig = serde_json::from_value(serde_json::json!({
704            "load_contracts": [{"secType": "STK", "conId": 265598}, {"secType": "STK", "conId": 265598}]
705        })).unwrap();
706
707        let data = super::InteractiveBrokersDataClientConfig {
708            instrument_provider: provider.clone(),
709            ..Default::default()
710        };
711
712        let execution = InteractiveBrokersExecutionClientConfig {
713            instrument_provider: provider,
714            ..Default::default()
715        };
716
717        let data_result = data
718            .validate()
719            .map_err(|e| e.downcast::<ConfigError>().unwrap());
720        let execution_result = execution.validate();
721        let expected = Err(ConfigError::duplicate("load_contracts", None));
722
723        assert_eq!(data_result, expected);
724        assert_eq!(execution_result, expected);
725    }
726
727    #[rstest]
728    #[case::data(false)]
729    #[case::execution(true)]
730    fn test_client_constructor_rejects_duplicate_config_before_setup(#[case] execution: bool) {
731        use std::{cell::RefCell, rc::Rc, sync::Arc};
732
733        use nautilus_common::cache::Cache;
734        use nautilus_live::ExecutionClientCore;
735        use nautilus_model::{
736            enums::{AccountType, OmsType},
737            identifiers::{AccountId, ClientId, TraderId, Venue},
738        };
739
740        use crate::{
741            data::InteractiveBrokersDataClient, execution::InteractiveBrokersExecutionClient,
742            providers::instruments::InteractiveBrokersInstrumentProvider,
743        };
744
745        let duplicate_config: InteractiveBrokersInstrumentProviderConfig =
746            serde_json::from_value(serde_json::json!({
747                "load_contracts": [{"conId": 265598}, {"conId": 265598}]
748            }))
749            .unwrap();
750        let provider =
751            Arc::new(InteractiveBrokersInstrumentProvider::new(Default::default()).unwrap());
752
753        let error = if execution {
754            let core = ExecutionClientCore::new(
755                TraderId::from("TESTER-001"),
756                ClientId::from("IB"),
757                Venue::from("IB"),
758                OmsType::Netting,
759                AccountId::from("IB-001"),
760                AccountType::Margin,
761                None,
762                Rc::new(RefCell::new(Cache::default())),
763            );
764
765            let config = InteractiveBrokersExecutionClientConfig {
766                client_id: 1,
767                instrument_provider: duplicate_config,
768                ..Default::default()
769            };
770
771            InteractiveBrokersExecutionClient::new(core, config, provider).err()
772        } else {
773            InteractiveBrokersDataClient::new(
774                ClientId::from("IB"),
775                super::InteractiveBrokersDataClientConfig {
776                    instrument_provider: duplicate_config,
777                    ..Default::default()
778                },
779                provider,
780            )
781            .err()
782        }
783        .expect("duplicate config must fail before client setup or connection");
784
785        assert_eq!(
786            error.downcast_ref::<ConfigError>(),
787            Some(&ConfigError::duplicate("load_contracts", None))
788        );
789    }
790
791    #[rstest]
792    fn test_provider_constructor_rejects_duplicate_config() {
793        let config = serde_json::from_value(serde_json::json!({
794            "load_contracts": [{"conId": 265598}, {"conId": 265598}]
795        }))
796        .unwrap();
797
798        let error =
799            crate::providers::instruments::InteractiveBrokersInstrumentProvider::new(config)
800                .unwrap_err();
801
802        assert_eq!(error, ConfigError::duplicate("load_contracts", None));
803    }
804
805    #[rstest]
806    fn test_provider_defaults_to_two_digit_futures_years() {
807        let config = InteractiveBrokersInstrumentProviderConfig::default();
808        let decoded: InteractiveBrokersInstrumentProviderConfig =
809            serde_json::from_str("{}").unwrap();
810        assert_eq!(config.futures_year_digits, FuturesYearDigits::Two);
811        assert_eq!(decoded.futures_year_digits, FuturesYearDigits::Two);
812    }
813
814    #[rstest]
815    #[case(1, FuturesYearDigits::One)]
816    #[case(2, FuturesYearDigits::Two)]
817    fn test_provider_deserializes_futures_year_digits(
818        #[case] digits: u8,
819        #[case] expected: FuturesYearDigits,
820    ) {
821        let config: InteractiveBrokersInstrumentProviderConfig =
822            serde_json::from_value(serde_json::json!({"futures_year_digits": digits})).unwrap();
823        assert_eq!(config.futures_year_digits, expected);
824        assert_eq!(
825            serde_json::to_value(&config).unwrap()["futures_year_digits"],
826            serde_json::json!(digits)
827        );
828    }
829
830    #[rstest]
831    #[case(0)]
832    #[case(3)]
833    #[case(4)]
834    #[case(u8::MAX)]
835    fn test_provider_rejects_invalid_serialized_futures_year_digits(#[case] digits: u8) {
836        let error = serde_json::from_value::<InteractiveBrokersInstrumentProviderConfig>(
837            serde_json::json!({"futures_year_digits": digits}),
838        )
839        .unwrap_err();
840        assert_eq!(
841            error.to_string(),
842            "`futures_year_digits` must be either 1 or 2"
843        );
844    }
845
846    #[rstest]
847    fn test_provider_share_class_space_defaults_on_and_round_trips() {
848        let default = InteractiveBrokersInstrumentProviderConfig::default();
849        let decoded: InteractiveBrokersInstrumentProviderConfig =
850            serde_json::from_value(serde_json::json!({"share_class_space": false})).unwrap();
851
852        assert!(default.share_class_space);
853        assert!(!decoded.share_class_space);
854        assert_eq!(
855            serde_json::to_value(&decoded).unwrap()["share_class_space"],
856            serde_json::json!(false)
857        );
858    }
859}