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}
322
323impl Default for InteractiveBrokersInstrumentProviderConfig {
324    fn default() -> Self {
325        Self::builder().build()
326    }
327}
328
329fn deserialize_configured_contracts<'de, D>(
330    deserializer: D,
331) -> Result<Vec<ConfiguredContract>, D::Error>
332where
333    D: Deserializer<'de>,
334{
335    Vec::<serde_json::Value>::deserialize(deserializer)?
336        .iter()
337        .map(parse_configured_contract_from_json)
338        .collect::<anyhow::Result<Vec<_>>>()
339        .map_err(D::Error::custom)
340}
341
342fn serialize_configured_contracts<S>(
343    contracts: &[ConfiguredContract],
344    serializer: S,
345) -> Result<S::Ok, S::Error>
346where
347    S: Serializer,
348{
349    contracts
350        .iter()
351        .map(ConfiguredContract::to_json_value)
352        .collect::<Vec<_>>()
353        .serialize(serializer)
354}
355
356/// Trading mode for Dockerized IB Gateway.
357#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
358#[cfg_attr(
359    feature = "python",
360    pyo3::pyclass(
361        module = "nautilus_trader.adapters.interactive_brokers",
362        from_py_object,
363        rename_all = "SCREAMING_SNAKE_CASE"
364    )
365)]
366#[cfg_attr(
367    feature = "python",
368    pyo3_stub_gen::derive::gen_stub_pyclass_enum(
369        module = "nautilus_trader.adapters.interactive_brokers"
370    )
371)]
372#[derive(Default)]
373pub enum TradingMode {
374    /// Paper trading mode.
375    #[serde(rename = "paper")]
376    #[default]
377    Paper,
378    /// Live trading mode.
379    #[serde(rename = "live")]
380    Live,
381}
382
383/// Configuration for Dockerized IB Gateway.
384///
385/// This configuration is for managing containerized IB Gateway instances.
386/// It supports environment variable loading and sensitive data masking.
387#[derive(Clone, Serialize, Deserialize, bon::Builder)]
388#[serde(default)]
389#[cfg_attr(
390    feature = "python",
391    pyo3::pyclass(
392        module = "nautilus_trader.adapters.interactive_brokers",
393        subclass,
394        from_py_object
395    )
396)]
397#[cfg_attr(
398    feature = "python",
399    pyo3_stub_gen::derive::gen_stub_pyclass(
400        module = "nautilus_trader.adapters.interactive_brokers"
401    )
402)]
403pub struct DockerizedIBGatewayConfig {
404    /// Username for IB account (falls back to `TWS_USERNAME` env var via [`Default`]).
405    pub username: Option<SecretString>,
406    /// Password for IB account (falls back to `TWS_PASSWORD` env var via [`Default`]).
407    #[serde(skip_serializing)]
408    pub password: Option<SecretString>,
409    /// Trading mode (paper or live).
410    #[builder(default)]
411    pub trading_mode: TradingMode,
412    /// Whether to enable read-only API mode.
413    #[builder(default = true)]
414    pub read_only_api: bool,
415    /// Timeout in seconds for container startup.
416    #[builder(default = 300)]
417    pub timeout: u64,
418    /// Container image reference.
419    #[builder(default = "ghcr.io/gnzsnz/ib-gateway:stable".to_string())]
420    pub container_image: String,
421    /// VNC port for remote desktop access (None to disable).
422    pub vnc_port: Option<u16>,
423}
424
425impl DockerizedIBGatewayConfig {
426    /// Validate configuration.
427    ///
428    /// # Errors
429    ///
430    /// Returns an error if validation fails.
431    pub fn validate(&self) -> anyhow::Result<()> {
432        if self.timeout == 0 {
433            anyhow::bail!("Timeout must be greater than 0");
434        }
435
436        if self.timeout > 3600 {
437            anyhow::bail!("Timeout must be less than 3600 seconds");
438        }
439
440        if let Some(port) = self.vnc_port
441            && (!(5900..=5999).contains(&port))
442        {
443            anyhow::bail!("VNC port must be between 5900 and 5999");
444        }
445
446        Ok(())
447    }
448}
449
450impl Debug for DockerizedIBGatewayConfig {
451    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
452        f.debug_struct(stringify!(DockerizedIBGatewayConfig))
453            .field("username", &self.username)
454            .field("password", &self.password.as_ref().map(|_| "<redacted>"))
455            .field("trading_mode", &self.trading_mode)
456            .field("read_only_api", &self.read_only_api)
457            .field("timeout", &self.timeout)
458            .field("container_image", &self.container_image)
459            .field("vnc_port", &self.vnc_port)
460            .finish()
461    }
462}
463
464impl Default for DockerizedIBGatewayConfig {
465    fn default() -> Self {
466        Self::builder()
467            .maybe_username(std::env::var("TWS_USERNAME").ok().map(SecretString::from))
468            .maybe_password(std::env::var("TWS_PASSWORD").ok().map(SecretString::from))
469            .build()
470    }
471}
472
473impl InteractiveBrokersInstrumentProviderConfig {
474    /// Validates configured selections.
475    ///
476    /// # Errors
477    ///
478    /// Returns an error if a selection repeats a value.
479    pub fn validate(&self) -> ConfigResult<()> {
480        check_unique_values("load_contracts", &self.load_contracts)
481    }
482}
483
484impl InteractiveBrokersExecutionClientConfig {
485    /// Validates that configured selections contain no duplicates.
486    ///
487    /// # Errors
488    ///
489    /// Returns an error if a selection repeats a value.
490    pub fn validate(&self) -> ConfigResult<()> {
491        self.instrument_provider.validate()
492    }
493}
494
495#[cfg(test)]
496mod tests {
497    use nautilus_common::config::ConfigError;
498    use nautilus_model::{identifiers::futures::FuturesYearDigits, types::Currency};
499    use rstest::rstest;
500
501    use super::{
502        DockerizedIBGatewayConfig, InteractiveBrokersExecutionClientConfig,
503        InteractiveBrokersInstrumentProviderConfig,
504    };
505    use crate::common::enums::IbSecurityType;
506
507    #[rstest]
508    fn test_gateway_password_is_redacted_from_debug_and_serialization() {
509        let config = DockerizedIBGatewayConfig::builder()
510            .username(String::from("user").into())
511            .password(String::from("secret-password").into())
512            .build();
513
514        let debug = format!("{config:?}");
515        let json = serde_json::to_string(&config).unwrap();
516
517        assert!(!debug.contains("secret-password"));
518        assert!(debug.contains("<redacted>"));
519        assert!(!json.contains("secret-password"));
520        assert!(!json.contains("password"));
521    }
522
523    #[rstest]
524    fn test_execution_client_config_base_currency() {
525        let config: InteractiveBrokersExecutionClientConfig =
526            serde_json::from_value(serde_json::json!({"base_currency": "EUR"})).unwrap();
527
528        assert_eq!(config.base_currency, Some(Currency::EUR()));
529        assert_eq!(
530            InteractiveBrokersExecutionClientConfig::default().base_currency,
531            None
532        );
533    }
534
535    #[rstest]
536    fn test_instrument_provider_config_decodes_typed_contracts_and_filters() {
537        let config: InteractiveBrokersInstrumentProviderConfig =
538            serde_json::from_value(serde_json::json!({
539                "load_contracts": [{
540                    "secType": "STK",
541                    "symbol": "AAPL",
542                    "exchange": "SMART",
543                    "conId": 265598
544                }],
545                "filter_sec_types": ["opt"]
546            }))
547            .unwrap();
548
549        assert_eq!(config.load_contracts.len(), 1);
550        assert_eq!(config.load_contracts[0].contract.contract_id, 265598);
551        assert_eq!(
552            config.load_contracts[0].contract.security_type,
553            ibapi::contracts::SecurityType::Stock
554        );
555        assert!(config.filter_sec_types.contains(&IbSecurityType::Option));
556    }
557
558    #[rstest]
559    fn test_instrument_provider_config_keeps_per_contract_chain_settings() {
560        let config: InteractiveBrokersInstrumentProviderConfig =
561            serde_json::from_value(serde_json::json!({
562                "build_futures_chain": true,
563                "load_contracts": [
564                    {
565                        "secType": "STK",
566                        "symbol": "SPY",
567                        "exchange": "SMART",
568                        "primaryExchange": "ARCA",
569                        "build_options_chain": true,
570                        "min_expiry_days": 7,
571                        "max_expiry_days": 14
572                    },
573                    {
574                        "secType": "FUT",
575                        "exchange": "NYMEX",
576                        "localSymbol": "CLZ6",
577                        "build_futures_chain": false
578                    }
579                ]
580            }))
581            .unwrap();
582
583        let spy = &config.load_contracts[0];
584        assert_eq!(spy.build_options_chain, Some(true));
585        assert_eq!(spy.build_futures_chain, None);
586        assert_eq!(spy.min_expiry_days, Some(7));
587        assert_eq!(spy.max_expiry_days, Some(14));
588        assert_eq!(spy.options_chain_exchange, None);
589        assert_eq!(
590            spy.chain_spec_json().unwrap(),
591            serde_json::json!({
592                "build_options_chain": true,
593                "min_expiry_days": 7,
594                "max_expiry_days": 14
595            })
596        );
597
598        let cl = &config.load_contracts[1];
599        assert_eq!(cl.build_futures_chain, Some(false));
600        assert_eq!(
601            cl.chain_spec_json().unwrap(),
602            serde_json::json!({"build_futures_chain": false})
603        );
604
605        let round_trip = serde_json::to_value(&config).unwrap();
606        assert_eq!(
607            round_trip["load_contracts"][0]["build_options_chain"],
608            serde_json::json!(true)
609        );
610        assert_eq!(
611            round_trip["load_contracts"][1]["build_futures_chain"],
612            serde_json::json!(false)
613        );
614    }
615
616    #[rstest]
617    fn test_instrument_provider_config_accepts_con_id_only_contract() {
618        let config: InteractiveBrokersInstrumentProviderConfig =
619            serde_json::from_value(serde_json::json!({
620                "load_contracts": [{"conId": 265598}]
621            }))
622            .unwrap();
623
624        assert_eq!(config.load_contracts[0].contract.contract_id, 265598);
625        assert_eq!(
626            config.load_contracts[0].contract.security_type,
627            ibapi::contracts::SecurityType::Stock
628        );
629    }
630
631    #[rstest]
632    #[case(
633        serde_json::json!({"load_contracts": [{"secType": "UNKNOWN"}]}),
634        "Unknown IB security type: UNKNOWN"
635    )]
636    #[case(
637        serde_json::json!({"load_contracts": [{"secType": "STK", "conId": "265598"}]}),
638        "Configured contract field 'conId' must be an integer"
639    )]
640    #[case(
641        serde_json::json!({"load_contracts": [{"symbol": "SPY"}]}),
642        "Configured contract requires 'secType' as a known IB security type string, or a positive 'conId'"
643    )]
644    #[case(
645        serde_json::json!({"load_contracts": [{"secType": "STK", "build_options_chain": "yes"}]}),
646        "Configured contract field 'build_options_chain' must be a boolean"
647    )]
648    #[case(
649        serde_json::json!({"load_contracts": [{"secType": "STK", "min_expiry_days": -1}]}),
650        "Configured contract field 'min_expiry_days' must be a non-negative integer"
651    )]
652    #[case(
653        serde_json::json!({"filter_sec_types": ["UNKNOWN"]}),
654        "Unknown IB security type: UNKNOWN"
655    )]
656    fn test_instrument_provider_config_rejects_invalid_typed_values(
657        #[case] value: serde_json::Value,
658        #[case] expected: &str,
659    ) {
660        let error = serde_json::from_value::<InteractiveBrokersInstrumentProviderConfig>(value)
661            .unwrap_err();
662
663        assert!(error.to_string().contains(expected), "{error}");
664    }
665
666    #[rstest]
667    #[case("load_contracts", serde_json::json!([{"secType": "STK", "conId": 265598}, {"secType": "STK", "conId": 756733}]))]
668    fn test_instrument_provider_selection_uniqueness(
669        #[case] field: &str,
670        #[case] mut values: serde_json::Value,
671        #[values(false, true)] duplicate: bool,
672    ) {
673        if duplicate {
674            let entries = values.as_array_mut().unwrap();
675            entries.push(entries[0].clone());
676        }
677
678        let mut input =
679            serde_json::to_value(InteractiveBrokersInstrumentProviderConfig::default()).unwrap();
680        input[field] = values;
681        let config: InteractiveBrokersInstrumentProviderConfig =
682            serde_json::from_value(input).unwrap();
683        let original = serde_json::to_value(&config).unwrap();
684
685        let expected = if duplicate {
686            Err(ConfigError::duplicate(field, None))
687        } else {
688            Ok(())
689        };
690
691        let result = config.validate();
692
693        assert_eq!(result, expected);
694        assert_eq!(serde_json::to_value(&config).unwrap(), original);
695    }
696
697    #[rstest]
698    fn test_client_configs_reject_duplicate_provider_selections() {
699        let provider: InteractiveBrokersInstrumentProviderConfig = serde_json::from_value(serde_json::json!({
700            "load_contracts": [{"secType": "STK", "conId": 265598}, {"secType": "STK", "conId": 265598}]
701        })).unwrap();
702
703        let data = super::InteractiveBrokersDataClientConfig {
704            instrument_provider: provider.clone(),
705            ..Default::default()
706        };
707
708        let execution = InteractiveBrokersExecutionClientConfig {
709            instrument_provider: provider,
710            ..Default::default()
711        };
712
713        let data_result = data
714            .validate()
715            .map_err(|e| e.downcast::<ConfigError>().unwrap());
716        let execution_result = execution.validate();
717        let expected = Err(ConfigError::duplicate("load_contracts", None));
718
719        assert_eq!(data_result, expected);
720        assert_eq!(execution_result, expected);
721    }
722
723    #[rstest]
724    #[case::data(false)]
725    #[case::execution(true)]
726    fn test_client_constructor_rejects_duplicate_config_before_setup(#[case] execution: bool) {
727        use std::{cell::RefCell, rc::Rc, sync::Arc};
728
729        use nautilus_common::cache::Cache;
730        use nautilus_live::ExecutionClientCore;
731        use nautilus_model::{
732            enums::{AccountType, OmsType},
733            identifiers::{AccountId, ClientId, TraderId, Venue},
734        };
735
736        use crate::{
737            data::InteractiveBrokersDataClient, execution::InteractiveBrokersExecutionClient,
738            providers::instruments::InteractiveBrokersInstrumentProvider,
739        };
740
741        let duplicate_config: InteractiveBrokersInstrumentProviderConfig =
742            serde_json::from_value(serde_json::json!({
743                "load_contracts": [{"conId": 265598}, {"conId": 265598}]
744            }))
745            .unwrap();
746        let provider =
747            Arc::new(InteractiveBrokersInstrumentProvider::new(Default::default()).unwrap());
748
749        let error = if execution {
750            let core = ExecutionClientCore::new(
751                TraderId::from("TESTER-001"),
752                ClientId::from("IB"),
753                Venue::from("IB"),
754                OmsType::Netting,
755                AccountId::from("IB-001"),
756                AccountType::Margin,
757                None,
758                Rc::new(RefCell::new(Cache::default())),
759            );
760
761            let config = InteractiveBrokersExecutionClientConfig {
762                client_id: 1,
763                instrument_provider: duplicate_config,
764                ..Default::default()
765            };
766
767            InteractiveBrokersExecutionClient::new(core, config, provider).err()
768        } else {
769            InteractiveBrokersDataClient::new(
770                ClientId::from("IB"),
771                super::InteractiveBrokersDataClientConfig {
772                    instrument_provider: duplicate_config,
773                    ..Default::default()
774                },
775                provider,
776            )
777            .err()
778        }
779        .expect("duplicate config must fail before client setup or connection");
780
781        assert_eq!(
782            error.downcast_ref::<ConfigError>(),
783            Some(&ConfigError::duplicate("load_contracts", None))
784        );
785    }
786
787    #[rstest]
788    fn test_provider_constructor_rejects_duplicate_config() {
789        let config = serde_json::from_value(serde_json::json!({
790            "load_contracts": [{"conId": 265598}, {"conId": 265598}]
791        }))
792        .unwrap();
793
794        let error =
795            crate::providers::instruments::InteractiveBrokersInstrumentProvider::new(config)
796                .unwrap_err();
797
798        assert_eq!(error, ConfigError::duplicate("load_contracts", None));
799    }
800
801    #[rstest]
802    fn test_provider_defaults_to_two_digit_futures_years() {
803        let config = InteractiveBrokersInstrumentProviderConfig::default();
804        let decoded: InteractiveBrokersInstrumentProviderConfig =
805            serde_json::from_str("{}").unwrap();
806        assert_eq!(config.futures_year_digits, FuturesYearDigits::Two);
807        assert_eq!(decoded.futures_year_digits, FuturesYearDigits::Two);
808    }
809
810    #[rstest]
811    #[case(1, FuturesYearDigits::One)]
812    #[case(2, FuturesYearDigits::Two)]
813    fn test_provider_deserializes_futures_year_digits(
814        #[case] digits: u8,
815        #[case] expected: FuturesYearDigits,
816    ) {
817        let config: InteractiveBrokersInstrumentProviderConfig =
818            serde_json::from_value(serde_json::json!({"futures_year_digits": digits})).unwrap();
819        assert_eq!(config.futures_year_digits, expected);
820        assert_eq!(
821            serde_json::to_value(&config).unwrap()["futures_year_digits"],
822            serde_json::json!(digits)
823        );
824    }
825
826    #[rstest]
827    #[case(0)]
828    #[case(3)]
829    #[case(4)]
830    #[case(u8::MAX)]
831    fn test_provider_rejects_invalid_serialized_futures_year_digits(#[case] digits: u8) {
832        let error = serde_json::from_value::<InteractiveBrokersInstrumentProviderConfig>(
833            serde_json::json!({"futures_year_digits": digits}),
834        )
835        .unwrap_err();
836        assert_eq!(
837            error.to_string(),
838            "`futures_year_digits` must be either 1 or 2"
839        );
840    }
841}