1use 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 #[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 #[getter]
110 fn host(&self) -> &str {
111 &self.host
112 }
113
114 #[getter]
116 fn port(&self) -> u16 {
117 self.port
118 }
119
120 #[getter]
122 fn client_id(&self) -> i32 {
123 self.client_id
124 }
125
126 #[getter]
128 fn use_regular_trading_hours(&self) -> bool {
129 self.use_regular_trading_hours
130 }
131
132 #[getter]
134 fn market_data_type(&self) -> MarketDataType {
135 self.market_data_type
136 }
137
138 #[getter]
140 fn ignore_quote_tick_size_updates(&self) -> bool {
141 self.ignore_quote_tick_size_updates
142 }
143
144 #[getter]
146 fn connection_timeout(&self) -> u64 {
147 self.connection_timeout
148 }
149
150 #[getter]
152 fn request_timeout(&self) -> u64 {
153 self.request_timeout
154 }
155
156 #[getter]
158 fn handle_revised_bars(&self) -> bool {
159 self.handle_revised_bars
160 }
161
162 #[getter]
164 fn batch_quotes(&self) -> bool {
165 self.batch_quotes
166 }
167
168 #[getter]
170 fn all_last_trades(&self) -> bool {
171 self.all_last_trades
172 }
173
174 #[getter]
176 fn subscription_idle_timeout_secs(&self) -> Option<u64> {
177 self.subscription_idle_timeout_secs
178 }
179
180 #[getter]
182 fn max_reconnect_attempts(&self) -> Option<u32> {
183 self.max_reconnect_attempts
184 }
185
186 #[getter]
188 fn instrument_provider(&self) -> InteractiveBrokersInstrumentProviderConfig {
189 self.instrument_provider.clone()
190 }
191
192 #[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 #[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 #[getter]
256 fn host(&self) -> &str {
257 &self.host
258 }
259
260 #[getter]
262 fn port(&self) -> u16 {
263 self.port
264 }
265
266 #[getter]
268 fn client_id(&self) -> i32 {
269 self.client_id
270 }
271
272 #[getter]
274 fn account_id(&self) -> Option<String> {
275 self.account_id.clone()
276 }
277
278 #[getter]
280 fn base_currency(&self) -> Option<Currency> {
281 self.base_currency
282 }
283
284 #[getter]
286 fn connection_timeout(&self) -> u64 {
287 self.connection_timeout
288 }
289
290 #[getter]
292 fn request_timeout(&self) -> u64 {
293 self.request_timeout
294 }
295
296 #[getter]
298 fn fetch_all_open_orders(&self) -> bool {
299 self.fetch_all_open_orders
300 }
301
302 #[getter]
304 fn track_option_exercise_from_position_update(&self) -> bool {
305 self.track_option_exercise_from_position_update
306 }
307
308 #[getter]
310 fn max_reconnect_attempts(&self) -> Option<u32> {
311 self.max_reconnect_attempts
312 }
313
314 #[getter]
316 fn instrument_provider(&self) -> InteractiveBrokersInstrumentProviderConfig {
317 self.instrument_provider.clone()
318 }
319
320 #[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 #[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))]
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 ) -> PyResult<Self> {
354 let futures_year_digits = futures_year_digits
355 .map(FuturesYearDigits::try_from)
356 .transpose()
357 .map_err(to_pyvalue_err)?
358 .unwrap_or_default();
359
360 let config = Self {
361 symbology_method: symbology_method.unwrap_or_default(),
362 load_ids: load_ids.unwrap_or_default(),
363 load_contracts: if let Some(c) = load_contracts {
364 py_list_to_json_values(c.bind(py))?
365 .iter()
366 .enumerate()
367 .map(|(index, value)| {
368 parse_configured_contract_from_json(value).map_err(|e| {
369 to_pyvalue_err(format!(
370 "Invalid load_contracts entry at index {index}: {e}"
371 ))
372 })
373 })
374 .collect::<PyResult<Vec<_>>>()?
375 } else {
376 Vec::new()
377 },
378 min_expiry_days,
379 max_expiry_days,
380 build_options_chain,
381 build_futures_chain,
382 cache_validity_days,
383 convert_exchange_to_mic_venue: convert_exchange_to_mic_venue.unwrap_or(false),
384 symbol_to_mic_venue: symbol_to_mic_venue.unwrap_or_default(),
385 filter_sec_types: filter_sec_types
386 .unwrap_or_default()
387 .into_iter()
388 .map(|value| IbSecurityType::from_str(&value).map_err(to_pyvalue_err))
389 .collect::<PyResult<_>>()?,
390 filter_callable,
391 cache_path,
392 futures_year_digits,
393 };
394
395 config.validate().map_err(config_error_to_pyvalue_err)?;
396 Ok(config)
397 }
398
399 #[getter]
400 fn futures_year_digits(&self) -> u8 {
401 self.futures_year_digits.into()
402 }
403
404 #[getter]
406 fn symbology_method(&self) -> SymbologyMethod {
407 self.symbology_method
408 }
409
410 #[getter]
412 fn load_ids(&self) -> std::collections::HashSet<InstrumentId> {
413 self.load_ids.clone()
414 }
415
416 #[getter]
418 fn load_contracts(&self, py: Python<'_>) -> PyResult<Py<pyo3::types::PyList>> {
419 let json_mod = py.import("json")?;
420 let list = pyo3::types::PyList::empty(py);
421
422 for contract in &self.load_contracts {
423 let json_str = contract.to_json_value().to_string();
424 let dict = json_mod.call_method1("loads", (json_str,))?;
425 list.append(dict)?;
426 }
427
428 Ok(list.unbind())
429 }
430
431 #[getter]
433 fn min_expiry_days(&self) -> Option<u32> {
434 self.min_expiry_days
435 }
436
437 #[getter]
439 fn max_expiry_days(&self) -> Option<u32> {
440 self.max_expiry_days
441 }
442
443 #[getter]
445 fn build_options_chain(&self) -> Option<bool> {
446 self.build_options_chain
447 }
448
449 #[getter]
451 fn build_futures_chain(&self) -> Option<bool> {
452 self.build_futures_chain
453 }
454
455 #[getter]
457 fn cache_validity_days(&self) -> Option<u32> {
458 self.cache_validity_days
459 }
460
461 #[getter]
463 fn convert_exchange_to_mic_venue(&self) -> bool {
464 self.convert_exchange_to_mic_venue
465 }
466
467 #[getter]
469 fn symbol_to_mic_venue(&self) -> std::collections::HashMap<String, String> {
470 self.symbol_to_mic_venue.clone()
471 }
472
473 #[getter]
475 fn filter_sec_types(&self) -> Vec<String> {
476 self.filter_sec_types
477 .iter()
478 .map(ToString::to_string)
479 .collect()
480 }
481
482 #[getter]
484 fn filter_callable(&self) -> Option<String> {
485 self.filter_callable.clone()
486 }
487
488 #[getter]
490 fn cache_path(&self) -> Option<String> {
491 self.cache_path.clone()
492 }
493
494 #[setter]
496 fn set_cache_path(&mut self, cache_path: Option<String>) {
497 self.cache_path = cache_path;
498 }
499}
500
501#[pymethods]
502#[pyo3_stub_gen::derive::gen_stub_pymethods]
503impl DockerizedIBGatewayConfig {
504 #[new]
506 #[pyo3(signature = (username=None, password=None, trading_mode=None, read_only_api=None, timeout=None, container_image=None, vnc_port=None))]
507 fn py_new(
508 username: Option<String>,
509 password: Option<String>,
510 trading_mode: Option<TradingMode>,
511 read_only_api: Option<bool>,
512 timeout: Option<u64>,
513 container_image: Option<String>,
514 vnc_port: Option<u16>,
515 ) -> Self {
516 Self {
517 username: username.map(SecretString::from),
518 password: password.map(SecretString::from),
519 trading_mode: trading_mode.unwrap_or_default(),
520 read_only_api: read_only_api.unwrap_or(true),
521 timeout: timeout.unwrap_or(300),
522 container_image: container_image
523 .unwrap_or_else(|| "ghcr.io/gnzsnz/ib-gateway:stable".to_string()),
524 vnc_port,
525 }
526 }
527
528 #[getter]
530 fn username(&self) -> Option<&str> {
531 self.username.as_ref().map(SecretString::expose_secret)
532 }
533
534 #[getter]
535 const fn has_password(&self) -> bool {
536 self.password.is_some()
537 }
538
539 #[getter]
541 fn trading_mode(&self) -> TradingMode {
542 self.trading_mode
543 }
544
545 #[getter]
547 fn read_only_api(&self) -> bool {
548 self.read_only_api
549 }
550
551 #[getter]
553 fn timeout(&self) -> u64 {
554 self.timeout
555 }
556
557 #[getter]
559 fn container_image(&self) -> &str {
560 &self.container_image
561 }
562
563 #[getter]
565 fn vnc_port(&self) -> Option<u16> {
566 self.vnc_port
567 }
568}
569
570#[cfg(test)]
571mod tests {
572 use pyo3::{prelude::*, types::PyDict};
573 use rstest::rstest;
574
575 use super::InteractiveBrokersInstrumentProviderConfig;
576
577 #[rstest]
578 #[case(None, 2)]
579 #[case(Some(1), 1)]
580 #[case(Some(2), 2)]
581 fn test_python_futures_year_digits(#[case] configured: Option<u8>, #[case] expected: u8) {
582 Python::initialize();
583 Python::attach(|py| {
584 let kwargs = PyDict::new(py);
585 if let Some(digits) = configured {
586 kwargs.set_item("futures_year_digits", digits).unwrap();
587 }
588
589 let config = py
590 .get_type::<InteractiveBrokersInstrumentProviderConfig>()
591 .call((), Some(&kwargs))
592 .unwrap();
593 assert_eq!(
594 config
595 .getattr("futures_year_digits")
596 .unwrap()
597 .extract::<u8>()
598 .unwrap(),
599 expected
600 );
601 });
602 }
603
604 #[rstest]
605 #[case(0)]
606 #[case(3)]
607 #[case(4)]
608 #[case(u8::MAX)]
609 fn test_python_rejects_invalid_futures_year_digits(#[case] digits: u8) {
610 Python::initialize();
611 Python::attach(|py| {
612 let kwargs = PyDict::new(py);
613 kwargs.set_item("futures_year_digits", digits).unwrap();
614 let error = py
615 .get_type::<InteractiveBrokersInstrumentProviderConfig>()
616 .call((), Some(&kwargs))
617 .unwrap_err();
618 assert!(error.is_instance_of::<pyo3::exceptions::PyValueError>(py));
619 assert_eq!(
620 error.value(py).to_string(),
621 "`futures_year_digits` must be either 1 or 2"
622 );
623 });
624 }
625}