Skip to main content

nautilus_interactive_brokers/providers/
parse.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//! Instrument parsing utilities for converting IB ContractDetails to Nautilus instruments.
17
18use std::str::FromStr;
19
20use anyhow::Context;
21use ibapi::contracts::SecurityType;
22use indexmap::IndexMap;
23use jiff::{
24    Timestamp,
25    civil::DateTime,
26    tz::{AmbiguousOffset, Offset},
27};
28use nautilus_core::{
29    DurationNanos, UnixNanos, datetime::get_timezone, time::get_atomic_clock_realtime,
30};
31use nautilus_model::{
32    enums::AssetClass,
33    identifiers::{
34        InstrumentId, Symbol,
35        futures::{format_futures_symbol, parse_futures_symbol, resolve_futures_year_from_expiry},
36    },
37    instruments::{
38        Cfd, Commodity, CurrencyPair, Equity, FuturesContract, FuturesSpread, IndexInstrument,
39        InstrumentAny, OptionContract, OptionSpread,
40    },
41    types::{Currency, Price, Quantity},
42};
43use rust_decimal::Decimal;
44use ustr::Ustr;
45
46use crate::common::{
47    contract_to_json_value,
48    enums::{IbOptionRight, IbSecurityType},
49};
50
51const NINETY_DAYS: DurationNanos = DurationNanos::from_days(90);
52
53/// Convert tick size to precision value.
54#[must_use]
55pub fn tick_size_to_precision(tick_size: f64) -> u8 {
56    if tick_size <= 0.0 {
57        return 8; // Default precision for zero or negative tick sizes
58    }
59
60    // Count decimal places
61    let s = format!("{tick_size:.10}");
62    let s = s.trim_end_matches('0');
63    let parts: Vec<&str> = s.split('.').collect();
64    if parts.len() == 2 {
65        parts[1].len().min(8) as u8
66    } else {
67        0
68    }
69}
70
71/// Moves the last trade time and zone that follow the date in `lastTradeDateOrContractMonth`
72/// (`20261218 08:30:00 US/Central`) to `last_trade_time` (`08:30:00 US/Central`), leaving the
73/// date alone in the contract.
74///
75/// IB Gateway 10.51 sends that form over protobuf, ibapi keeps it whole for every contract but a
76/// bond, and IB refuses it when the contract is sent back in a request (error 10372). IB's own
77/// API client moves only the time; the zone moves with it because the contract's `time_zone_id`
78/// may be empty or differ from it, and the expiration must stay the instant IB stated.
79pub(crate) fn split_last_trade_date(details: &mut ibapi::contracts::ContractDetails) {
80    if let Some(time_and_zone) = trim_last_trade_date(&mut details.contract) {
81        details.last_trade_time = time_and_zone;
82    }
83}
84
85/// Cuts `lastTradeDateOrContractMonth` to its date, returning the time and zone that followed
86/// it (see [`split_last_trade_date`]).
87pub(crate) fn trim_last_trade_date(contract: &mut ibapi::contracts::Contract) -> Option<String> {
88    // ibapi reads a bond's maturity, time and zone from the value and keeps it whole, as IB's
89    // own client does
90    if contract.security_type == SecurityType::Bond {
91        return None;
92    }
93
94    let mut parts = contract
95        .last_trade_date_or_contract_month
96        .split_whitespace();
97    let date = parts.next()?.to_string();
98    let time_and_zone = parts.collect::<Vec<_>>().join(" ");
99    if time_and_zone.is_empty() {
100        return None;
101    }
102    contract.last_trade_date_or_contract_month = date;
103
104    Some(time_and_zone)
105}
106
107/// Convert timestamp string to UnixNanos.
108///
109/// Handles formats like "20230101" or "20230101 00:00:00 UTC". A date alone takes its time
110/// from the `last_trade_time` of `details` if it holds one, otherwise from its trading session.
111/// A time without a zone is in the contract's `time_zone_id`, or in UTC if that is empty.
112///
113/// # Errors
114///
115/// Returns an error if the timestamp cannot be parsed.
116pub fn expiry_timestring_to_unix_nanos(
117    expiry: &str,
118    details: Option<&ibapi::contracts::ContractDetails>,
119) -> anyhow::Result<UnixNanos> {
120    if expiry.is_empty() {
121        anyhow::bail!("Empty expiry string");
122    }
123
124    let contract_timezone = details
125        .map(|details| details.time_zone_id.as_str())
126        .filter(|timezone| !timezone.is_empty())
127        .unwrap_or("UTC");
128    let last_trade_time = details
129        .map(|details| details.last_trade_time.as_str())
130        .filter(|time| !time.is_empty());
131
132    let (date, time, timezone) = if expiry.len() == 8
133        && let Some(last_trade_time) = last_trade_time
134    {
135        let (time, timezone) = read_time_and_zone(
136            last_trade_time.split_whitespace(),
137            contract_timezone,
138            last_trade_time,
139        )?;
140        (expiry, time.to_string(), timezone)
141    } else if expiry.len() == 8 {
142        let session_end = details.and_then(|details| {
143            details
144                .trading_hours
145                .iter()
146                .find(|session| session.starts_with(expiry))
147                .and_then(|session| session.split_once('-'))
148                .map(|(_, end)| end)
149        });
150
151        let (date, time) = match session_end {
152            Some(end) => end.split_once(':').unwrap_or((expiry, end)),
153            // IB lists only the coming week of sessions, so a later expiry takes the
154            // closing time of the last listed session
155            None => (
156                expiry,
157                details.and_then(last_session_close).unwrap_or("0000"),
158            ),
159        };
160
161        let time = match time.len() {
162            4 => format!("{}:{}:00", &time[0..2], &time[2..4]),
163            _ => anyhow::bail!("Invalid expiry session end '{time}' for {expiry}"),
164        };
165
166        (date, time, contract_timezone)
167    } else {
168        let mut parts = expiry.split_whitespace();
169        let date = parts.next().context("Expiry timestamp is missing a date")?;
170        let (time, timezone) = read_time_and_zone(parts, contract_timezone, expiry)?;
171
172        (date, time.to_string(), timezone)
173    };
174
175    let datetime = DateTime::strptime("%Y%m%d %H:%M:%S", format!("{date} {time}"))
176        .with_context(|| format!("Invalid expiry timestamp: {expiry}"))?;
177    let timestamp = localize_expiry(datetime, timezone, expiry)?;
178    let nanos = u64::try_from(timestamp.as_nanosecond())
179        .with_context(|| format!("Expiry timestamp precedes the Unix epoch: {expiry}"))?;
180    Ok(UnixNanos::new(nanos))
181}
182
183// Reads `HH:MM:SS [zone]` from the `parts` of `value`, the zone defaulting to
184// `default_timezone`
185fn read_time_and_zone<'a>(
186    mut parts: std::str::SplitWhitespace<'a>,
187    default_timezone: &'a str,
188    value: &str,
189) -> anyhow::Result<(&'a str, &'a str)> {
190    let time = parts.next().context("Expiry timestamp is missing a time")?;
191    let timezone = parts.next().unwrap_or(default_timezone);
192    if parts.next().is_some() {
193        anyhow::bail!("Invalid expiry format: {value}");
194    }
195
196    Ok((time, timezone))
197}
198
199// Returns the `HHMM` closing time of the last listed trading session that is not closed
200fn last_session_close(details: &ibapi::contracts::ContractDetails) -> Option<&str> {
201    details.trading_hours.iter().rev().find_map(|session| {
202        let (_, end) = session.rsplit_once('-')?;
203        let close = end.rsplit_once(':').map_or(end, |(_, time)| time);
204        (close.len() == 4 && close.bytes().all(|byte| byte.is_ascii_digit())).then_some(close)
205    })
206}
207
208fn localize_expiry(datetime: DateTime, timezone: &str, expiry: &str) -> anyhow::Result<Timestamp> {
209    if timezone.eq_ignore_ascii_case("UTC") || timezone.eq_ignore_ascii_case("Z") {
210        return Ok(Offset::UTC.to_timestamp(datetime)?);
211    }
212
213    let zone = get_timezone(timezone).with_context(|| {
214        format!("Unknown IB contract timezone '{timezone}' for expiry {expiry}")
215    })?;
216
217    let ambiguous = zone.to_ambiguous_timestamp(datetime);
218    match ambiguous.offset() {
219        AmbiguousOffset::Unambiguous { .. } => Ok(ambiguous.unambiguous()?),
220        AmbiguousOffset::Fold { .. } => Ok(ambiguous.earlier()?),
221        AmbiguousOffset::Gap { .. } => {
222            anyhow::bail!("Expiry {expiry} does not exist in timezone '{timezone}'")
223        }
224    }
225}
226
227/// Parse an IB ContractDetails to a Nautilus instrument.
228///
229/// # Errors
230///
231/// Returns an error if parsing fails.
232pub fn parse_ib_contract_to_instrument(
233    details: &ibapi::contracts::ContractDetails,
234    instrument_id: InstrumentId,
235) -> anyhow::Result<InstrumentAny> {
236    let sec_type = &details.contract.security_type;
237    match sec_type {
238        SecurityType::Stock => Ok(parse_equity_contract(details, instrument_id)),
239        SecurityType::ForexPair => Ok(parse_forex_contract(details, instrument_id)),
240        SecurityType::Crypto => Ok(parse_crypto_contract(details, instrument_id)),
241        SecurityType::Future | SecurityType::ContinuousFuture => {
242            parse_futures_contract(details, instrument_id)
243        }
244        SecurityType::Option => parse_option_contract(details, instrument_id),
245        SecurityType::FuturesOption => parse_option_contract(details, instrument_id), // FOP uses same parsing as OPT
246        SecurityType::Index => Ok(parse_index_contract(details, instrument_id)),
247        SecurityType::CFD => Ok(parse_cfd_contract(details, instrument_id)),
248        SecurityType::Commodity => Ok(parse_commodity_contract(details, instrument_id)),
249        SecurityType::Bond => Ok(parse_bond_contract(details, instrument_id)),
250        _ => anyhow::bail!("Unsupported security type: {sec_type:?}"),
251    }
252}
253
254fn ib_contract_info(details: &ibapi::contracts::ContractDetails) -> nautilus_core::Params {
255    let mut info = ib_contract_info_for_contract(&details.contract);
256    info.insert(
257        "priceMagnifier".to_string(),
258        serde_json::Value::from(details.price_magnifier),
259    );
260    nautilus_core::Params::new(info)
261}
262
263fn ib_contract_info_for_contract(
264    contract: &ibapi::contracts::Contract,
265) -> IndexMap<String, serde_json::Value> {
266    IndexMap::from([("contract".to_string(), contract_to_json_value(contract))])
267}
268
269fn sec_type_to_asset_class(sec_type: &str) -> AssetClass {
270    match IbSecurityType::from_str(sec_type).ok() {
271        Some(IbSecurityType::Stock) => AssetClass::Equity,
272        Some(IbSecurityType::Index) => AssetClass::Index,
273        Some(IbSecurityType::ForexPair) => AssetClass::FX,
274        Some(IbSecurityType::Bond) => AssetClass::Debt,
275        Some(IbSecurityType::Commodity) => AssetClass::Commodity,
276        Some(IbSecurityType::Future) => AssetClass::Index,
277        _ => AssetClass::Equity,
278    }
279}
280
281/// Parse equity contract (STK).
282fn parse_equity_contract(
283    details: &ibapi::contracts::ContractDetails,
284    instrument_id: InstrumentId,
285) -> InstrumentAny {
286    let price_precision = tick_size_to_precision(details.min_tick);
287    let timestamp = get_atomic_clock_realtime().get_time_ns();
288
289    let instrument = Equity::builder()
290        .instrument_id(instrument_id)
291        .raw_symbol(Symbol::from(details.contract.local_symbol.as_str()))
292        .currency(Currency::from(details.contract.currency.to_string()))
293        .price_precision(price_precision)
294        .price_increment(Price::new(details.min_tick, price_precision))
295        // Standard lot size for stocks
296        .lot_size(Quantity::new(100.0, 0))
297        .info(ib_contract_info(details))
298        .ts_event(timestamp)
299        .ts_init(timestamp)
300        .build()
301        .unwrap();
302
303    InstrumentAny::from(instrument)
304}
305
306/// Parse forex contract (CASH).
307fn parse_forex_contract(
308    details: &ibapi::contracts::ContractDetails,
309    instrument_id: InstrumentId,
310) -> InstrumentAny {
311    let price_precision = tick_size_to_precision(details.min_tick);
312    let (size_precision, size_increment, min_quantity) = parse_contract_size_rules(details, 1.0);
313    let timestamp = get_atomic_clock_realtime().get_time_ns();
314
315    let instrument = CurrencyPair::builder()
316        .instrument_id(instrument_id)
317        .raw_symbol(Symbol::from(details.contract.local_symbol.as_str()))
318        .base_currency(Currency::from(details.contract.symbol.to_string()))
319        .quote_currency(Currency::from(details.contract.currency.to_string()))
320        .price_precision(price_precision)
321        .size_precision(size_precision)
322        .price_increment(Price::new(details.min_tick, price_precision))
323        .size_increment(size_increment)
324        .maybe_min_quantity(min_quantity)
325        .info(ib_contract_info(details))
326        .ts_event(timestamp)
327        .ts_init(timestamp)
328        .build()
329        .unwrap();
330
331    InstrumentAny::from(instrument)
332}
333
334/// Parse crypto contract (CRYPTO).
335fn parse_crypto_contract(
336    details: &ibapi::contracts::ContractDetails,
337    instrument_id: InstrumentId,
338) -> InstrumentAny {
339    let price_precision = tick_size_to_precision(details.min_tick);
340    let (size_precision, size_increment, min_quantity) =
341        parse_contract_size_rules(details, 0.00000001);
342    let timestamp = get_atomic_clock_realtime().get_time_ns();
343
344    let instrument = CurrencyPair::builder()
345        .instrument_id(instrument_id)
346        .raw_symbol(Symbol::from(details.contract.local_symbol.as_str()))
347        .base_currency(Currency::from(details.contract.symbol.to_string()))
348        .quote_currency(Currency::from(details.contract.currency.to_string()))
349        .price_precision(price_precision)
350        .size_precision(size_precision)
351        .price_increment(Price::new(details.min_tick, price_precision))
352        .size_increment(size_increment)
353        .maybe_min_quantity(min_quantity)
354        .info(ib_contract_info(details))
355        .ts_event(timestamp)
356        .ts_init(timestamp)
357        .build()
358        .unwrap();
359
360    InstrumentAny::from(instrument)
361}
362
363fn parse_contract_multiplier(multiplier: &str, default: f64) -> Quantity {
364    if multiplier.is_empty() {
365        return Quantity::new(default, 0);
366    }
367
368    Quantity::from_str(multiplier).unwrap_or_else(|e| {
369        tracing::warn!(
370            "Failed to parse IB contract multiplier '{multiplier}', using default {default}: {e}"
371        );
372        Quantity::new(default, 0)
373    })
374}
375
376/// Parse futures contract (FUT).
377fn parse_futures_contract(
378    details: &ibapi::contracts::ContractDetails,
379    instrument_id: InstrumentId,
380) -> anyhow::Result<InstrumentAny> {
381    let price_precision = tick_size_to_precision(details.min_tick);
382    let timestamp = get_atomic_clock_realtime().get_time_ns();
383
384    let expiry = &details.contract.last_trade_date_or_contract_month;
385
386    let expiration_ns = match expiry_timestring_to_unix_nanos(expiry, Some(details)) {
387        Ok(expiration_ns) => expiration_ns,
388        // Continuous futures can report contract details without a last-trade date.
389        Err(e)
390            if matches!(
391                details.contract.security_type,
392                SecurityType::ContinuousFuture
393            ) =>
394        {
395            tracing::warn!(
396                "Continuous future {} reported expiry '{expiry}', defaulting to 90 days out: {e}",
397                details.contract.symbol.as_str(),
398            );
399            timestamp + NINETY_DAYS
400        }
401        Err(e) => {
402            return Err(e).with_context(|| format!("Failed to parse futures expiry '{expiry}'"));
403        }
404    };
405
406    let activation_ns = activation_from_expiration(expiration_ns);
407
408    let multiplier = parse_contract_multiplier(&details.contract.multiplier, 1.0);
409    let raw_symbol = if matches!(
410        details.contract.security_type,
411        SecurityType::ContinuousFuture
412    ) && !details.contract.symbol.as_str().is_empty()
413    {
414        details.contract.symbol.as_str()
415    } else {
416        details.contract.local_symbol.as_str()
417    };
418
419    let instrument = FuturesContract::builder()
420        .instrument_id(instrument_id)
421        .raw_symbol(Symbol::from(raw_symbol))
422        .asset_class(sec_type_to_asset_class(
423            details.under_security_type.as_str(),
424        ))
425        .underlying(Ustr::from(details.under_symbol.as_str()))
426        .activation_ns(activation_ns)
427        .expiration_ns(expiration_ns)
428        .currency(Currency::from(details.contract.currency.to_string()))
429        .price_precision(price_precision)
430        .price_increment(Price::new(details.min_tick, price_precision))
431        .multiplier(multiplier)
432        .lot_size(Quantity::new(1.0, 0))
433        .info(ib_contract_info(details))
434        .ts_event(timestamp)
435        .ts_init(timestamp)
436        .build()
437        .unwrap();
438
439    Ok(InstrumentAny::from(instrument))
440}
441
442/// Parse option contract (OPT).
443fn parse_option_contract(
444    details: &ibapi::contracts::ContractDetails,
445    instrument_id: InstrumentId,
446) -> anyhow::Result<InstrumentAny> {
447    let price_precision = tick_size_to_precision(details.min_tick);
448    let timestamp = get_atomic_clock_realtime().get_time_ns();
449
450    let expiry = &details.contract.last_trade_date_or_contract_month;
451    let expiration_ns = expiry_timestring_to_unix_nanos(expiry, Some(details))
452        .with_context(|| format!("Failed to parse option expiry '{expiry}'"))?;
453
454    let activation_ns = activation_from_expiration(expiration_ns);
455
456    // Parse option kind (CALL or PUT)
457    let option_kind = details
458        .contract
459        .right
460        .map(|right| IbOptionRight::from_str(right.as_str()))
461        .transpose()?
462        .context("Option contract missing right")?
463        .option_kind();
464
465    let multiplier = parse_contract_multiplier(&details.contract.multiplier, 100.0);
466    let asset_class = sec_type_to_asset_class(details.under_security_type.as_str());
467
468    // IB reports a magnified contract's strike in the same sub-unit as its market data
469    let strike = details.contract.strike / f64::from(details.price_magnifier.max(1));
470
471    let underlying =
472        if details.under_security_type == "IND" && !details.under_symbol.starts_with('^') {
473            format!("^{}", details.under_symbol)
474        } else if details.under_security_type == "FUT" {
475            let option_code = instrument_id
476                .symbol
477                .as_str()
478                .split_once(' ')
479                .map(|(code, _)| code);
480            let digits = option_code
481                .and_then(parse_futures_symbol)
482                .map(|parsed| parsed.year_digits.len());
483
484            if digits == Some(2) {
485                parse_futures_symbol(&details.under_symbol)
486                    .and_then(|parsed| {
487                        let year = resolve_futures_year_from_expiry(
488                            parsed.year_digits,
489                            expiry.get(..4)?.parse::<i32>().ok()?,
490                        )?;
491                        format_futures_symbol(parsed.root, parsed.month_code, year, 2)
492                    })
493                    .unwrap_or_else(|| details.under_symbol.clone())
494            } else {
495                details.under_symbol.clone()
496            }
497        } else {
498            details.under_symbol.clone()
499        };
500
501    let instrument = OptionContract::builder()
502        .instrument_id(instrument_id)
503        .raw_symbol(Symbol::from(details.contract.local_symbol.as_str()))
504        .asset_class(asset_class)
505        .underlying(Ustr::from(underlying.as_str()))
506        .option_kind(option_kind)
507        .strike_price(Price::new(strike, price_precision))
508        .currency(Currency::from(details.contract.currency.to_string()))
509        .activation_ns(activation_ns)
510        .expiration_ns(expiration_ns)
511        .price_precision(price_precision)
512        .price_increment(Price::new(details.min_tick, price_precision))
513        .multiplier(multiplier)
514        .lot_size(multiplier)
515        .info(ib_contract_info(details))
516        .ts_event(timestamp)
517        .ts_init(timestamp)
518        .build()
519        .unwrap();
520
521    Ok(InstrumentAny::from(instrument))
522}
523
524fn activation_from_expiration(expiration_ns: UnixNanos) -> UnixNanos {
525    expiration_ns.checked_sub(NINETY_DAYS).unwrap_or_default()
526}
527
528fn parse_contract_size_rules(
529    details: &ibapi::contracts::ContractDetails,
530    default_increment: f64,
531) -> (u8, Quantity, Option<Quantity>) {
532    let size_increment = details
533        .size_increment
534        .or(details.min_size)
535        .unwrap_or(default_increment);
536    let size_precision = details.min_size.map_or_else(
537        || tick_size_to_precision(size_increment),
538        |min_size| tick_size_to_precision(min_size).max(tick_size_to_precision(size_increment)),
539    );
540    let min_quantity = details
541        .min_size
542        .map(|min_size| Quantity::new(min_size, size_precision));
543
544    (
545        size_precision,
546        Quantity::new(size_increment, size_precision),
547        min_quantity,
548    )
549}
550
551#[cfg(test)]
552#[allow(
553    clippy::items_after_test_module,
554    reason = "private parser tests remain beside the contract helpers they exercise"
555)]
556mod tests {
557    use ibapi::contracts::{
558        Contract, ContractDetails, Currency, Exchange, OptionRight, SecurityType, Symbol,
559    };
560    use nautilus_model::{
561        enums::AssetClass,
562        identifiers::{InstrumentId, Symbol as NautilusSymbol, Venue},
563        instruments::{Instrument, InstrumentAny},
564        types::{Price, Quantity},
565    };
566    use rstest::rstest;
567    use ustr::Ustr;
568
569    use super::{
570        expiry_timestring_to_unix_nanos, parse_contract_multiplier,
571        parse_ib_contract_to_instrument, parse_option_spread_instrument_id, split_last_trade_date,
572    };
573
574    fn es_future_details(expiry: &str) -> ContractDetails {
575        ContractDetails {
576            contract: Contract {
577                symbol: Symbol::from("ES"),
578                security_type: SecurityType::Future,
579                exchange: Exchange::from("CME"),
580                currency: Currency::from("USD"),
581                local_symbol: String::from("ESZ6"),
582                last_trade_date_or_contract_month: expiry.to_string(),
583                multiplier: "50".to_string(),
584                ..Default::default()
585            },
586            min_tick: 0.25,
587            under_symbol: String::from("ES"),
588            under_security_type: String::from("IND"),
589            time_zone_id: String::from("US/Central"),
590            ..Default::default()
591        }
592    }
593
594    #[rstest]
595    fn test_parse_crypto_contract_creates_spot_currency_pair() {
596        let details = ContractDetails {
597            contract: Contract {
598                symbol: Symbol::from("BTC"),
599                security_type: SecurityType::Crypto,
600                exchange: Exchange::from("PAXOS"),
601                currency: Currency::from("USD"),
602                local_symbol: String::from("BTC.USD"),
603                ..Default::default()
604            },
605            min_tick: 0.01,
606            min_size: Some(0.0001),
607            size_increment: Some(0.0001),
608            ..Default::default()
609        };
610
611        let instrument_id = InstrumentId::from("BTC/USD.PAXOS");
612
613        let instrument = parse_ib_contract_to_instrument(&details, instrument_id).unwrap();
614
615        let InstrumentAny::CurrencyPair(pair) = instrument else {
616            panic!("expected spot currency pair");
617        };
618
619        assert_eq!(pair.base_currency.code.as_str(), "BTC");
620        assert_eq!(pair.quote_currency.code.as_str(), "USD");
621        assert_eq!(pair.size_precision, 4);
622        assert_eq!(pair.size_increment, Quantity::from("0.0001"));
623    }
624
625    #[rstest]
626    fn test_expiry_session_end_uses_contract_timezone() {
627        let details = ContractDetails {
628            time_zone_id: String::from("America/New_York"),
629            trading_hours: vec![String::from("20260313:0930-20260313:1600")],
630            ..Default::default()
631        };
632
633        let expiry = expiry_timestring_to_unix_nanos("20260313", Some(&details)).unwrap();
634        let expected = "2026-03-13T20:00:00Z".parse::<jiff::Timestamp>().unwrap();
635
636        assert_eq!(
637            expiry.as_u64(),
638            u64::try_from(expected.as_nanosecond()).unwrap()
639        );
640    }
641
642    #[rstest]
643    #[case::listed_session_closes_later_than_expiry(
644        vec!["20260929:0930-20260929:1600", "20260930:0930-20260930:1600", "20261001:CLOSED"],
645        "2026-10-30T20:00:00Z"
646    )]
647    #[case::overnight_sessions(
648        vec!["20260928:1700-20260929:1600", "20260929:1700-20260930:1600"],
649        "2026-10-30T20:00:00Z"
650    )]
651    #[case::only_closed_sessions(vec!["20261001:CLOSED"], "2026-10-30T04:00:00Z")]
652    #[case::no_sessions(vec![], "2026-10-30T04:00:00Z")]
653    fn test_expiry_beyond_listed_sessions_uses_last_session_close(
654        #[case] trading_hours: Vec<&str>,
655        #[case] expected: &str,
656    ) {
657        let details = ContractDetails {
658            time_zone_id: String::from("America/New_York"),
659            trading_hours: trading_hours.into_iter().map(String::from).collect(),
660            ..Default::default()
661        };
662
663        let expiry = expiry_timestring_to_unix_nanos("20261030", Some(&details)).unwrap();
664        let expected = expected.parse::<jiff::Timestamp>().unwrap();
665
666        assert_eq!(
667            expiry.as_u64(),
668            u64::try_from(expected.as_nanosecond()).unwrap()
669        );
670    }
671
672    #[rstest]
673    fn test_expiry_date_takes_last_trade_time_over_session() {
674        let details = ContractDetails {
675            time_zone_id: String::from("US/Central"),
676            last_trade_time: String::from("08:30:00"),
677            trading_hours: vec![String::from("20261218:1700-20261219:1600")],
678            ..Default::default()
679        };
680
681        let expiry = expiry_timestring_to_unix_nanos("20261218", Some(&details)).unwrap();
682        let expected = "2026-12-18T14:30:00Z".parse::<jiff::Timestamp>().unwrap();
683
684        assert_eq!(
685            expiry.as_u64(),
686            u64::try_from(expected.as_nanosecond()).unwrap()
687        );
688    }
689
690    #[rstest]
691    #[case::no_contract_timezone("")]
692    #[case::same_contract_timezone("US/Central")]
693    #[case::other_contract_timezone("Asia/Tokyo")]
694    fn test_expiry_date_takes_last_trade_time_zone_over_contract_timezone(
695        #[case] time_zone_id: &str,
696    ) {
697        let details = ContractDetails {
698            time_zone_id: time_zone_id.to_string(),
699            last_trade_time: String::from("08:30:00 US/Central"),
700            ..Default::default()
701        };
702
703        let expiry = expiry_timestring_to_unix_nanos("20261218", Some(&details)).unwrap();
704        let expected = "2026-12-18T14:30:00Z".parse::<jiff::Timestamp>().unwrap();
705
706        assert_eq!(
707            expiry.as_u64(),
708            u64::try_from(expected.as_nanosecond()).unwrap()
709        );
710    }
711
712    #[rstest]
713    fn test_expiry_rejects_last_trade_time_with_extra_token() {
714        let details = ContractDetails {
715            last_trade_time: String::from("08:30:00 US/Central extra"),
716            ..Default::default()
717        };
718
719        let result = expiry_timestring_to_unix_nanos("20261218", Some(&details));
720
721        assert_eq!(
722            result.unwrap_err().to_string(),
723            "Invalid expiry format: 08:30:00 US/Central extra"
724        );
725    }
726
727    #[rstest]
728    fn test_split_last_trade_date_moves_time_and_zone_out_of_expiry() {
729        let mut details = es_future_details("20261218 08:30:00 US/Central");
730
731        split_last_trade_date(&mut details);
732
733        assert_eq!(
734            details.contract.last_trade_date_or_contract_month,
735            "20261218"
736        );
737        assert_eq!(details.last_trade_time, "08:30:00 US/Central");
738    }
739
740    #[rstest]
741    #[case::date("20261218")]
742    #[case::contract_month("202612")]
743    #[case::empty("")]
744    fn test_split_last_trade_date_keeps_expiry_without_time(#[case] expiry: &str) {
745        let mut details = es_future_details(expiry);
746
747        split_last_trade_date(&mut details);
748
749        assert_eq!(details.contract.last_trade_date_or_contract_month, expiry);
750        assert!(details.last_trade_time.is_empty());
751    }
752
753    #[rstest]
754    fn test_split_last_trade_date_keeps_bond_expiry() {
755        let mut details = ContractDetails {
756            contract: Contract {
757                security_type: SecurityType::Bond,
758                last_trade_date_or_contract_month: String::from("20301115 16:00:00 US/Eastern"),
759                ..Default::default()
760            },
761            ..Default::default()
762        };
763
764        split_last_trade_date(&mut details);
765
766        assert_eq!(
767            details.contract.last_trade_date_or_contract_month,
768            "20301115 16:00:00 US/Eastern"
769        );
770        assert!(details.last_trade_time.is_empty());
771    }
772
773    #[rstest]
774    #[case::same_contract_timezone("US/Central", "")]
775    #[case::no_contract_timezone("", "")]
776    #[case::other_contract_timezone("America/New_York", "")]
777    #[case::other_last_trade_time("America/New_York", "10:00:00")]
778    fn test_parse_future_after_split_keeps_expiry_and_stores_date(
779        #[case] time_zone_id: &str,
780        #[case] last_trade_time: &str,
781    ) {
782        let instrument_id = InstrumentId::from("ESZ6.CME");
783        let mut details = es_future_details("20261218 08:30:00 US/Central");
784        details.time_zone_id = time_zone_id.to_string();
785        details.last_trade_time = last_trade_time.to_string();
786        let unsplit = parse_ib_contract_to_instrument(&details, instrument_id).unwrap();
787
788        split_last_trade_date(&mut details);
789        let instrument = parse_ib_contract_to_instrument(&details, instrument_id).unwrap();
790
791        let expected = "2026-12-18T14:30:00Z".parse::<jiff::Timestamp>().unwrap();
792        assert_eq!(
793            instrument.expiration_ns().unwrap().as_u64(),
794            u64::try_from(expected.as_nanosecond()).unwrap()
795        );
796        assert_eq!(instrument.expiration_ns(), unsplit.expiration_ns());
797        let InstrumentAny::FuturesContract(future) = instrument else {
798            panic!("expected futures contract");
799        };
800        let info = future.info.unwrap();
801        assert_eq!(
802            info.get("contract")
803                .and_then(|contract| contract.get("lastTradeDateOrContractMonth")),
804            Some(&serde_json::Value::from("20261218"))
805        );
806    }
807
808    #[rstest]
809    fn test_parse_future_rejects_missing_expiry() {
810        let details = ContractDetails {
811            contract: Contract {
812                symbol: Symbol::from("ES"),
813                security_type: SecurityType::Future,
814                exchange: Exchange::from("CME"),
815                currency: Currency::from("USD"),
816                local_symbol: String::from("ESZ6"),
817                ..Default::default()
818            },
819            min_tick: 0.25,
820            ..Default::default()
821        };
822
823        let result = parse_ib_contract_to_instrument(&details, InstrumentId::from("ESZ6.CME"));
824
825        assert_eq!(
826            result.unwrap_err().to_string(),
827            "Failed to parse futures expiry ''"
828        );
829    }
830
831    #[rstest]
832    fn test_parse_option_contract_prefixes_index_underlying() {
833        let details = ContractDetails {
834            contract: Contract {
835                symbol: Symbol::from("SPXW"),
836                security_type: SecurityType::Option,
837                exchange: Exchange::from("SMART"),
838                currency: Currency::from("USD"),
839                local_symbol: "SPXW  260313P06630000".to_string(),
840                last_trade_date_or_contract_month: "20260313".to_string(),
841                right: Some(OptionRight::Put),
842                strike: 6630.0,
843                multiplier: "100".to_string(),
844                ..Default::default()
845            },
846            min_tick: 0.05,
847            under_symbol: "SPX".to_string(),
848            under_security_type: "IND".to_string(),
849            ..Default::default()
850        };
851
852        let instrument_id = InstrumentId::new(
853            NautilusSymbol::from("SPXW  260313P06630000"),
854            Venue::from("SMART"),
855        );
856
857        let instrument = parse_ib_contract_to_instrument(&details, instrument_id).unwrap();
858
859        let InstrumentAny::OptionContract(option) = instrument else {
860            panic!("expected option contract");
861        };
862
863        assert_eq!(option.asset_class(), AssetClass::Index);
864        assert_eq!(option.underlying(), Some(Ustr::from("^SPX")));
865    }
866
867    #[rstest]
868    fn test_parse_contract_preserves_price_magnifier_in_info() {
869        let details = ContractDetails {
870            contract: Contract {
871                symbol: Symbol::from("AAPL"),
872                security_type: SecurityType::Stock,
873                exchange: Exchange::from("SMART"),
874                primary_exchange: Exchange::from("NASDAQ"),
875                currency: Currency::from("USD"),
876                local_symbol: String::from("AAPL"),
877                ..Default::default()
878            },
879            min_tick: 0.01,
880            price_magnifier: 100,
881            ..Default::default()
882        };
883
884        let instrument_id = InstrumentId::new(NautilusSymbol::from("AAPL"), Venue::from("XNAS"));
885
886        let instrument = parse_ib_contract_to_instrument(&details, instrument_id).unwrap();
887
888        let InstrumentAny::Equity(equity) = instrument else {
889            panic!("expected equity");
890        };
891
892        assert_eq!(
893            equity.info.unwrap().get("priceMagnifier"),
894            Some(&serde_json::Value::from(100))
895        );
896    }
897
898    #[rstest]
899    #[case("100", 100.0)]
900    #[case("", 1.0)]
901    #[case("not-a-number", 1.0)]
902    fn test_parse_contract_multiplier_uses_quantity_parser(
903        #[case] multiplier: &str,
904        #[case] expected: f64,
905    ) {
906        assert_eq!(
907            parse_contract_multiplier(multiplier, 1.0),
908            Quantity::new(expected, 0)
909        );
910    }
911
912    #[rstest]
913    fn test_parse_continuous_future_contract_uses_symbol_as_raw_symbol() {
914        let details = ContractDetails {
915            contract: Contract {
916                symbol: Symbol::from("ES"),
917                security_type: SecurityType::ContinuousFuture,
918                exchange: Exchange::from("CME"),
919                currency: Currency::from("USD"),
920                local_symbol: String::new(),
921                multiplier: "50".to_string(),
922                ..Default::default()
923            },
924            min_tick: 0.25,
925            under_symbol: "ES".to_string(),
926            under_security_type: "IND".to_string(),
927            ..Default::default()
928        };
929
930        let instrument_id = InstrumentId::new(NautilusSymbol::from("ES"), Venue::from("CME"));
931
932        let instrument = parse_ib_contract_to_instrument(&details, instrument_id).unwrap();
933
934        let InstrumentAny::FuturesContract(future) = instrument else {
935            panic!("expected futures contract");
936        };
937
938        assert_eq!(future.raw_symbol().as_str(), "ES");
939    }
940
941    #[rstest]
942    fn test_parse_option_spread_uses_minimum_leg_tick() {
943        let leg1 = ContractDetails {
944            contract: Contract {
945                symbol: Symbol::from("SPY"),
946                security_type: SecurityType::Option,
947                exchange: Exchange::from("SMART"),
948                currency: Currency::from("USD"),
949                local_symbol: "SPY   260120C00400000".to_string(),
950                multiplier: "100".to_string(),
951                ..Default::default()
952            },
953            min_tick: 0.05,
954            under_symbol: "SPY".to_string(),
955            ..Default::default()
956        };
957
958        let leg2 = ContractDetails {
959            contract: Contract {
960                symbol: Symbol::from("SPY"),
961                security_type: SecurityType::Option,
962                exchange: Exchange::from("SMART"),
963                currency: Currency::from("USD"),
964                local_symbol: "SPY   260120C00410000".to_string(),
965                multiplier: "100".to_string(),
966                ..Default::default()
967            },
968            min_tick: 0.01,
969            under_symbol: "SPY".to_string(),
970            ..Default::default()
971        };
972
973        let instrument_id =
974            InstrumentId::from("(1)SPY   260120C00400000_((-1))SPY   260120C00410000.SMART");
975
976        let spread = parse_option_spread_instrument_id(
977            instrument_id,
978            &[(&leg1, 1), (&leg2, -1)],
979            None,
980            None,
981        )
982        .unwrap();
983
984        assert_eq!(spread.price_precision(), 2);
985        assert_eq!(spread.price_increment(), Price::from("0.01"));
986    }
987
988    #[rstest]
989    fn test_parse_futures_option_contract_divides_magnified_strike() {
990        let details = ContractDetails {
991            contract: Contract {
992                symbol: Symbol::from("ZC"),
993                security_type: SecurityType::FuturesOption,
994                exchange: Exchange::from("CBOT"),
995                currency: Currency::from("USD"),
996                local_symbol: "OZCX6 C4630".to_string(),
997                last_trade_date_or_contract_month: "20261023".to_string(),
998                right: Some(OptionRight::Call),
999                strike: 463.0,
1000                multiplier: "5000".to_string(),
1001                ..Default::default()
1002            },
1003            min_tick: 0.00125,
1004            price_magnifier: 100,
1005            under_symbol: "ZCZ6".to_string(),
1006            under_security_type: "FUT".to_string(),
1007            ..Default::default()
1008        };
1009
1010        let instrument_id =
1011            InstrumentId::new(NautilusSymbol::from("OZCX6 C4630"), Venue::from("CBOT"));
1012
1013        let instrument = parse_ib_contract_to_instrument(&details, instrument_id).unwrap();
1014
1015        let InstrumentAny::OptionContract(option) = instrument else {
1016            panic!("expected option contract");
1017        };
1018
1019        assert_eq!(option.strike_price, Price::from("4.63000"));
1020        assert_eq!(option.price_increment, Price::from("0.00125"));
1021        assert_eq!(option.price_precision, 5);
1022    }
1023
1024    #[rstest]
1025    fn test_parse_future_contract_keeps_min_tick_with_price_magnifier() {
1026        let details = ContractDetails {
1027            contract: Contract {
1028                symbol: Symbol::from("ZC"),
1029                security_type: SecurityType::Future,
1030                exchange: Exchange::from("CBOT"),
1031                currency: Currency::from("USD"),
1032                local_symbol: "ZCZ6".to_string(),
1033                last_trade_date_or_contract_month: "20261214".to_string(),
1034                multiplier: "5000".to_string(),
1035                ..Default::default()
1036            },
1037            min_tick: 0.0025,
1038            price_magnifier: 100,
1039            under_symbol: "ZC".to_string(),
1040            ..Default::default()
1041        };
1042
1043        let instrument_id = InstrumentId::new(NautilusSymbol::from("ZCZ6"), Venue::from("CBOT"));
1044
1045        let instrument = parse_ib_contract_to_instrument(&details, instrument_id).unwrap();
1046
1047        let InstrumentAny::FuturesContract(future) = instrument else {
1048            panic!("expected futures contract");
1049        };
1050
1051        assert_eq!(future.price_increment, Price::from("0.0025"));
1052        assert_eq!(future.price_precision, 4);
1053        assert_eq!(future.multiplier, Quantity::from(5000));
1054    }
1055
1056    #[rstest]
1057    #[case("EW1F26 P5000.XCME", "ESZ6", "20251231", "ESZ26")]
1058    #[case("EW1F30 P5000.XCME", "ESH0", "20291231", "ESH30")]
1059    #[case("EW1F6 P5000.XCME", "ESZ6", "20251231", "ESZ6")]
1060    fn test_futures_option_uses_actual_underlying(
1061        #[case] instrument_id: InstrumentId,
1062        #[case] underlying: &str,
1063        #[case] expiry: &str,
1064        #[case] expected: &str,
1065    ) {
1066        let details = ContractDetails {
1067            contract: Contract {
1068                symbol: Symbol::from("ES"),
1069                security_type: SecurityType::FuturesOption,
1070                currency: Currency::from("USD"),
1071                local_symbol: "EW1F6 P5000".to_string(),
1072                last_trade_date_or_contract_month: expiry.to_string(),
1073                right: Some(OptionRight::Put),
1074                strike: 5000.0,
1075                multiplier: "50".to_string(),
1076                ..Default::default()
1077            },
1078            min_tick: 0.25,
1079            under_symbol: underlying.to_string(),
1080            under_security_type: "FUT".to_string(),
1081            ..Default::default()
1082        };
1083
1084        let InstrumentAny::OptionContract(option) =
1085            parse_ib_contract_to_instrument(&details, instrument_id).unwrap()
1086        else {
1087            panic!("expected option contract");
1088        };
1089
1090        assert_eq!(option.underlying(), Some(Ustr::from(expected)));
1091        assert_eq!(option.id(), instrument_id);
1092        assert_eq!(option.raw_symbol(), NautilusSymbol::from("EW1F6 P5000"));
1093    }
1094}
1095
1096/// Parse index contract (IND).
1097///
1098/// Note: Indices are typically not directly tradable. This creates a CurrencyPair
1099/// representation as a placeholder until IndexInstrument type is available.
1100fn parse_index_contract(
1101    details: &ibapi::contracts::ContractDetails,
1102    instrument_id: InstrumentId,
1103) -> InstrumentAny {
1104    let price_precision = tick_size_to_precision(details.min_tick);
1105    let (size_precision, size_increment, _) = parse_contract_size_rules(details, 1.0);
1106    let timestamp = get_atomic_clock_realtime().get_time_ns();
1107
1108    let instrument = IndexInstrument::builder()
1109        .instrument_id(instrument_id)
1110        .raw_symbol(Symbol::from(details.contract.local_symbol.as_str()))
1111        .currency(Currency::from(details.contract.currency.to_string()))
1112        .price_precision(price_precision)
1113        .size_precision(size_precision)
1114        .price_increment(Price::new(details.min_tick, price_precision))
1115        .size_increment(size_increment)
1116        .info(ib_contract_info(details))
1117        .ts_event(timestamp)
1118        .ts_init(timestamp)
1119        .build()
1120        .unwrap();
1121
1122    InstrumentAny::from(instrument)
1123}
1124
1125/// Parse a spread instrument ID into an OptionSpread instrument.
1126///
1127/// This implements the same logic as Python's `parse_spread_instrument_id`.
1128/// Uses contract details from the first leg to determine spread properties.
1129///
1130/// # Errors
1131///
1132/// Returns an error if parsing fails.
1133pub fn parse_spread_instrument_id(
1134    instrument_id: InstrumentId,
1135    leg_contract_details: &[(&ibapi::contracts::ContractDetails, i32)],
1136    timestamp_ns: Option<UnixNanos>,
1137) -> anyhow::Result<OptionSpread> {
1138    if leg_contract_details.is_empty() {
1139        anyhow::bail!("leg_contract_details must be provided");
1140    }
1141
1142    // Use contract details from first leg
1143    let (first_details, _) = leg_contract_details[0];
1144    let first_contract = &first_details.contract;
1145
1146    // Extract properties from the first leg contract details
1147    let currency = Currency::from(first_contract.currency.to_string());
1148    let underlying = if first_details.under_symbol.is_empty() {
1149        Ustr::from(first_contract.symbol.as_str())
1150    } else {
1151        Ustr::from(first_details.under_symbol.as_str())
1152    };
1153
1154    // Parse multiplier
1155    let multiplier_str = first_contract.multiplier.clone();
1156    let multiplier =
1157        Quantity::from_str(&multiplier_str).unwrap_or_else(|_| Quantity::new(100.0, 0)); // Default to 100 for options
1158
1159    // Determine asset class based on security type
1160    let asset_class = match first_contract.security_type {
1161        ibapi::contracts::SecurityType::FuturesOption => AssetClass::Index, // Futures options
1162        _ => AssetClass::Equity,                                            // Equity options
1163    };
1164
1165    // Calculate price precision and increment from the finest leg tick.
1166    let min_tick = leg_contract_details
1167        .iter()
1168        .map(|(details, _)| details.min_tick)
1169        .fold(first_details.min_tick, f64::min);
1170    let price_precision = tick_size_to_precision(min_tick);
1171    let price_increment = Price::new(min_tick, price_precision);
1172
1173    // Use provided timestamp or current time
1174    let timestamp = timestamp_ns.unwrap_or_else(|| get_atomic_clock_realtime().get_time_ns());
1175
1176    // For options spreads, lot size equals multiplier (same as individual option contracts)
1177    let lot_size = multiplier;
1178
1179    // Create the spread instrument
1180    let spread = OptionSpread::builder()
1181        .instrument_id(instrument_id)
1182        .raw_symbol(Symbol::from(instrument_id.symbol.as_str()))
1183        .asset_class(asset_class)
1184        .underlying(underlying)
1185        .strategy_type(Ustr::from("SPREAD"))
1186        // activation_ns (spreads don't have single activation dates)
1187        .activation_ns(UnixNanos::new(0))
1188        // expiration_ns (spreads don't have single expiration dates)
1189        .expiration_ns(UnixNanos::new(0))
1190        .currency(currency)
1191        .price_precision(price_precision)
1192        .price_increment(price_increment)
1193        .multiplier(multiplier)
1194        .lot_size(lot_size)
1195        .margin_init(Decimal::ZERO)
1196        .margin_maint(Decimal::ZERO)
1197        .ts_event(timestamp)
1198        .ts_init(timestamp)
1199        .build()?;
1200
1201    Ok(spread)
1202}
1203
1204pub fn parse_option_spread_instrument_id(
1205    instrument_id: InstrumentId,
1206    leg_contract_details: &[(&ibapi::contracts::ContractDetails, i32)],
1207    bag_contract: Option<&ibapi::contracts::Contract>,
1208    timestamp_ns: Option<UnixNanos>,
1209) -> anyhow::Result<OptionSpread> {
1210    let mut spread = parse_spread_instrument_id(instrument_id, leg_contract_details, timestamp_ns)?;
1211    spread.info = bag_contract
1212        .map(ib_contract_info_for_contract)
1213        .map(nautilus_core::Params::new);
1214    Ok(spread)
1215}
1216
1217pub fn parse_futures_spread_instrument_id(
1218    instrument_id: InstrumentId,
1219    leg_contract_details: &[(&ibapi::contracts::ContractDetails, i32)],
1220    bag_contract: Option<&ibapi::contracts::Contract>,
1221    timestamp_ns: Option<UnixNanos>,
1222) -> anyhow::Result<FuturesSpread> {
1223    if leg_contract_details.is_empty() {
1224        anyhow::bail!("leg_contract_details must be provided");
1225    }
1226
1227    let (first_details, _) = leg_contract_details[0];
1228    let first_contract = &first_details.contract;
1229    let currency = Currency::from(first_contract.currency.to_string());
1230    let underlying = if first_details.under_symbol.is_empty() {
1231        Ustr::from(first_contract.symbol.as_str())
1232    } else {
1233        Ustr::from(first_details.under_symbol.as_str())
1234    };
1235
1236    let multiplier =
1237        Quantity::from_str(&first_contract.multiplier).unwrap_or_else(|_| Quantity::new(1.0, 0));
1238    let min_tick = leg_contract_details
1239        .iter()
1240        .map(|(details, _)| details.min_tick)
1241        .fold(first_details.min_tick, f64::min);
1242    let price_precision = tick_size_to_precision(min_tick);
1243    let price_increment = Price::new(min_tick, price_precision);
1244    let timestamp = timestamp_ns.unwrap_or_else(|| get_atomic_clock_realtime().get_time_ns());
1245
1246    Ok(FuturesSpread::builder()
1247        .instrument_id(instrument_id)
1248        .raw_symbol(Symbol::from(instrument_id.symbol.as_str()))
1249        .asset_class(AssetClass::Index)
1250        .underlying(underlying)
1251        .strategy_type(Ustr::from("SPREAD"))
1252        .activation_ns(UnixNanos::new(0))
1253        .expiration_ns(UnixNanos::new(0))
1254        .currency(currency)
1255        .price_precision(price_precision)
1256        .price_increment(price_increment)
1257        .multiplier(multiplier)
1258        .lot_size(Quantity::new(1.0, 0))
1259        .margin_init(Decimal::ZERO)
1260        .margin_maint(Decimal::ZERO)
1261        .maybe_info(
1262            bag_contract
1263                .map(ib_contract_info_for_contract)
1264                .map(nautilus_core::Params::new),
1265        )
1266        .ts_event(timestamp)
1267        .ts_init(timestamp)
1268        .build()?)
1269}
1270
1271pub fn parse_spread_instrument_any(
1272    instrument_id: InstrumentId,
1273    leg_contract_details: &[(&ibapi::contracts::ContractDetails, i32)],
1274    bag_contract: Option<&ibapi::contracts::Contract>,
1275    timestamp_ns: Option<UnixNanos>,
1276) -> anyhow::Result<InstrumentAny> {
1277    let has_future = leg_contract_details.iter().any(|(details, _)| {
1278        matches!(
1279            details.contract.security_type,
1280            SecurityType::Future | SecurityType::ContinuousFuture
1281        )
1282    });
1283
1284    if has_future {
1285        Ok(InstrumentAny::from(parse_futures_spread_instrument_id(
1286            instrument_id,
1287            leg_contract_details,
1288            bag_contract,
1289            timestamp_ns,
1290        )?))
1291    } else {
1292        Ok(InstrumentAny::from(parse_option_spread_instrument_id(
1293            instrument_id,
1294            leg_contract_details,
1295            bag_contract,
1296            timestamp_ns,
1297        )?))
1298    }
1299}
1300
1301/// Parse CFD contract (CFD).
1302fn parse_cfd_contract(
1303    details: &ibapi::contracts::ContractDetails,
1304    instrument_id: InstrumentId,
1305) -> InstrumentAny {
1306    let price_precision = tick_size_to_precision(details.min_tick);
1307    let (size_precision, size_increment, min_quantity) = parse_contract_size_rules(details, 1.0);
1308    let timestamp = get_atomic_clock_realtime().get_time_ns();
1309
1310    let base_currency = details
1311        .contract
1312        .local_symbol
1313        .contains('.')
1314        .then(|| Currency::from(details.contract.symbol.to_string()));
1315
1316    let instrument = Cfd::builder()
1317        .instrument_id(instrument_id)
1318        .raw_symbol(Symbol::from(details.contract.local_symbol.as_str()))
1319        .asset_class(sec_type_to_asset_class(
1320            details.under_security_type.as_str(),
1321        ))
1322        .maybe_base_currency(base_currency)
1323        .quote_currency(Currency::from(details.contract.currency.to_string()))
1324        .price_precision(price_precision)
1325        .size_precision(size_precision)
1326        .price_increment(Price::new(details.min_tick, price_precision))
1327        .size_increment(size_increment)
1328        .maybe_min_quantity(min_quantity)
1329        .info(ib_contract_info(details))
1330        .ts_event(timestamp)
1331        .ts_init(timestamp)
1332        .build()
1333        .unwrap();
1334
1335    InstrumentAny::from(instrument)
1336}
1337
1338/// Parse commodity contract (CMDTY).
1339fn parse_commodity_contract(
1340    details: &ibapi::contracts::ContractDetails,
1341    instrument_id: InstrumentId,
1342) -> InstrumentAny {
1343    let price_precision = tick_size_to_precision(details.min_tick);
1344    let (size_precision, size_increment, min_quantity) = parse_contract_size_rules(details, 1.0);
1345    let timestamp = get_atomic_clock_realtime().get_time_ns();
1346
1347    let instrument = Commodity::builder()
1348        .instrument_id(instrument_id)
1349        .raw_symbol(Symbol::from(details.contract.local_symbol.as_str()))
1350        .asset_class(AssetClass::Commodity)
1351        .quote_currency(Currency::from(details.contract.currency.to_string()))
1352        .price_precision(price_precision)
1353        .size_precision(size_precision)
1354        .price_increment(Price::new(details.min_tick, price_precision))
1355        .size_increment(size_increment)
1356        .maybe_min_quantity(min_quantity)
1357        .info(ib_contract_info(details))
1358        .ts_event(timestamp)
1359        .ts_init(timestamp)
1360        .build()
1361        .unwrap();
1362
1363    InstrumentAny::from(instrument)
1364}
1365
1366/// Parse bond contract (BOND).
1367fn parse_bond_contract(
1368    details: &ibapi::contracts::ContractDetails,
1369    instrument_id: InstrumentId,
1370) -> InstrumentAny {
1371    // Use Equity as a placeholder until Bond type is available in Rust model
1372    // Note: This is a limitation of the current Nautilus Rust model, not the IB adapter
1373    let price_precision = tick_size_to_precision(details.min_tick);
1374    let timestamp = get_atomic_clock_realtime().get_time_ns();
1375
1376    // ISIN could be extracted from `security_id` if needed
1377    let instrument = Equity::builder()
1378        .instrument_id(instrument_id)
1379        .raw_symbol(Symbol::from(details.contract.local_symbol.as_str()))
1380        .currency(Currency::from(details.contract.currency.to_string()))
1381        .price_precision(price_precision)
1382        .price_increment(Price::new(details.min_tick, price_precision))
1383        // Standard lot size for bonds
1384        .lot_size(Quantity::new(1.0, 0))
1385        .info(ib_contract_info(details))
1386        .ts_event(timestamp)
1387        .ts_init(timestamp)
1388        .build()
1389        .unwrap();
1390
1391    InstrumentAny::from(instrument)
1392}