Skip to main content

nautilus_model/identifiers/
option_instrument_id.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//! Computes candidate option identifiers under an explicit symbology scheme.
17//!
18//! CME inference follows nominal weekday expiry schedules. Exchange holidays and instrument
19//! listings require definition validation by the caller. Standard quarterly equity options
20//! take precedence when the futures month matches the quarterly expiry month; otherwise
21//! weekly or EOM roots apply.
22
23use std::str::FromStr;
24
25use jiff::{civil::Date, tz::TimeZone};
26use nautilus_core::UnixNanos;
27use thiserror::Error;
28
29use crate::{
30    enums::OptionKind,
31    identifiers::{
32        InstrumentId, Symbol, Venue,
33        futures::{futures_month, futures_month_code, parse_futures_symbol},
34    },
35    types::{
36        Price,
37        fixed::{check_fixed_precision, raw_scale},
38    },
39};
40
41/// The contract inputs used to compute a candidate option identifier.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct OptionContractSpec {
44    /// The option's actual underlying, independent of its series reference-price instrument.
45    pub underlying_instrument_id: InstrumentId,
46    /// The exact strike price.
47    pub strike: Price,
48    /// UNIX expiration timestamp in nanoseconds.
49    pub expiration_ns: UnixNanos,
50    /// The option kind.
51    pub option_kind: OptionKind,
52}
53
54/// A scheme for computing raw option symbols.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum OptionSymbologyScheme {
57    /// CME Globex symbols, with an optional SOFR midcurve tenor code.
58    CmeGlobex {
59        /// `0` denotes one year; `2`, `3`, `4`, and `5` denote those year tenors.
60        mid_curve: Option<u8>,
61    },
62    /// Padded 21-character OSI symbols.
63    Osi {
64        /// An option-root override, such as `SPXW`; otherwise uses the underlying symbol.
65        root: Option<String>,
66    },
67}
68
69/// A contract component cannot be represented by the selected scheme.
70#[derive(Debug, Clone, Error, PartialEq, Eq)]
71pub enum OptionInstrumentIdError {
72    /// The underlying futures code is invalid.
73    #[error("invalid future code '{value}': {reason}")]
74    InvalidFutureCode {
75        /// The invalid code.
76        value: String,
77        /// The validation failure.
78        reason: String,
79    },
80    /// The expiry is unsupported or ambiguous.
81    #[error("invalid expiration '{value}': {reason}")]
82    InvalidExpiration {
83        /// The invalid expiry.
84        value: String,
85        /// The validation failure.
86        reason: String,
87    },
88    /// The strike cannot be represented exactly.
89    #[error("invalid strike '{value}': {reason}")]
90    InvalidStrike {
91        /// The invalid strike.
92        value: String,
93        /// The validation failure.
94        reason: String,
95    },
96    /// The option root is invalid or unsupported.
97    #[error("invalid option root '{value}': {reason}")]
98    InvalidRoot {
99        /// The invalid root.
100        value: String,
101        /// The validation failure.
102        reason: String,
103    },
104}
105
106impl OptionContractSpec {
107    /// Creates a contract specification.
108    #[must_use]
109    pub const fn new(
110        underlying_instrument_id: InstrumentId,
111        strike: Price,
112        expiration_ns: UnixNanos,
113        option_kind: OptionKind,
114    ) -> Self {
115        Self {
116            underlying_instrument_id,
117            strike,
118            expiration_ns,
119            option_kind,
120        }
121    }
122
123    /// Creates a specification from a UTC expiry date or timestamp string.
124    ///
125    /// # Errors
126    ///
127    /// Returns an error if the expiry cannot be parsed.
128    pub fn from_expiry(
129        underlying_instrument_id: InstrumentId,
130        strike: Price,
131        expiry: &str,
132        option_kind: OptionKind,
133    ) -> Result<Self, OptionInstrumentIdError> {
134        let expiration_ns = UnixNanos::from_str(expiry).map_err(|e| {
135            OptionInstrumentIdError::InvalidExpiration {
136                value: expiry.to_string(),
137                reason: e.to_string(),
138            }
139        })?;
140
141        Ok(Self::new(
142            underlying_instrument_id,
143            strike,
144            expiration_ns,
145            option_kind,
146        ))
147    }
148
149    /// Returns the UTC calendar date of expiration.
150    #[must_use]
151    pub fn expiry_date(&self) -> Date {
152        TimeZone::UTC
153            .to_datetime(self.expiration_ns.to_datetime_utc())
154            .date()
155    }
156}
157
158/// Computes a candidate option ID at the option venue.
159///
160/// The computed symbol does not prove that a matching contract is listed.
161/// CME reads the underlying symbol as a futures code such as `ESH6`, rather than `ES`.
162/// OSI uses that symbol as the option root unless the scheme supplies an override.
163///
164/// # Errors
165///
166/// Returns an error if a contract component is invalid, unsupported, or ambiguous.
167pub fn compute_option_instrument_id(
168    spec: &OptionContractSpec,
169    scheme: &OptionSymbologyScheme,
170    venue: Venue,
171) -> Result<InstrumentId, OptionInstrumentIdError> {
172    let symbol = match scheme {
173        OptionSymbologyScheme::CmeGlobex { mid_curve } => cme_globex_option_symbol(
174            spec.underlying_instrument_id.symbol.as_str(),
175            spec.strike,
176            spec.option_kind,
177            spec.expiry_date(),
178            *mid_curve,
179        )?,
180        OptionSymbologyScheme::Osi { root } => osi_option_symbol(
181            root.as_deref()
182                .unwrap_or(spec.underlying_instrument_id.symbol.as_str()),
183            spec.expiry_date(),
184            spec.option_kind,
185            spec.strike,
186        )?,
187    };
188
189    let checked =
190        Symbol::new_checked(&symbol).map_err(|e| OptionInstrumentIdError::InvalidRoot {
191            value: symbol,
192            reason: e.to_string(),
193        })?;
194
195    Ok(InstrumentId::new(checked, venue))
196}
197
198/// Computes a CME Globex option symbol from a nominal UTC expiry date.
199///
200/// Uses the expiry year with the underlying's one- or two-digit year convention.
201/// Supports ES, NQ, RTY, MES, MNQ, SR3 SOFR contracts, and CL WTI weeklies.
202/// Other roots return typed errors. Physically settled Micro E-mini contracts are supported
203/// before June 29, 2026; subsequent physical and financial families are ambiguous.
204/// SOFR and WTI strike digits use hundredths; equity-index strike digits use whole index points.
205/// Holiday-adjusted expiries require validation against instrument definitions.
206///
207/// # Errors
208///
209/// Returns an error if:
210/// - The futures code, root, or midcurve tenor is unsupported.
211/// - The expiry is on a weekend, a nominal WTI monthly date, or an ambiguous micro date.
212/// - The strike is non-positive or cannot fit the supported integral symbol scale.
213#[expect(
214    clippy::missing_panics_doc,
215    reason = "the futures parser validates the month code before conversion"
216)]
217pub fn cme_globex_option_symbol(
218    future_code: &str,
219    strike: Price,
220    option_kind: OptionKind,
221    expiry: Date,
222    mid_curve: Option<u8>,
223) -> Result<String, OptionInstrumentIdError> {
224    let parsed = parse_futures_symbol(future_code)
225        .filter(|parsed| {
226            matches!(parsed.year_digits.len(), 1 | 2)
227                && future_code
228                    .bytes()
229                    .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
230        })
231        .ok_or_else(|| OptionInstrumentIdError::InvalidFutureCode {
232            value: future_code.to_string(),
233            reason: "expected a root, month code, and one- or two-digit year".to_string(),
234        })?;
235
236    let root = parsed.root;
237    let future_month = u32::from(futures_month(parsed.month_code).expect("parsed futures month"));
238    let future_year = parsed.year_digits;
239    let day = expiry.weekday().to_monday_one_offset();
240    if day > 5 {
241        return Err(invalid_expiry(
242            expiry,
243            "CME nominal expiry must be a weekday",
244        ));
245    }
246
247    if mid_curve.is_some() && root != "SR3" {
248        return Err(OptionInstrumentIdError::InvalidRoot {
249            value: root.to_string(),
250            reason: "midcurve tenors apply only to SR3".to_string(),
251        });
252    }
253
254    let week = (expiry.day() - 1) / 7 + 1;
255    let month = expiry.month();
256
257    let option_root = match root {
258        "ES" | "NQ" | "RTY" | "MES" | "MNQ" => equity_root(root, future_month, expiry, day, week)?,
259        "SR3" => sofr_root(expiry, mid_curve, day, week)?,
260        "CL" => crude_root(expiry, day, week)?,
261        _ => {
262            return Err(OptionInstrumentIdError::InvalidRoot {
263                value: root.to_string(),
264                reason: "unsupported CME option root".to_string(),
265            });
266        }
267    };
268
269    let month_code = futures_month_code(month as u8).expect("expiry month is valid");
270    let side = option_letter(option_kind);
271    let year_width = future_year.len();
272    let year_modulus = if year_width == 1 { 10 } else { 100 };
273    let year = expiry.year().rem_euclid(year_modulus);
274    let strike = cme_strike(root, strike)?;
275    Ok(format!(
276        "{option_root}{month_code}{year:0year_width$} {side}{strike}"
277    ))
278}
279
280/// Computes a padded OSI option symbol with an exact thousandths strike.
281///
282/// # Errors
283///
284/// Returns an error if:
285/// - The root is outside one to six ASCII alphanumeric characters.
286/// - The expiry year is outside `[2000, 2099]`.
287/// - The strike cannot fit eight digits of exact non-negative thousandths.
288pub fn osi_option_symbol(
289    root: &str,
290    expiry: Date,
291    option_kind: OptionKind,
292    strike: Price,
293) -> Result<String, OptionInstrumentIdError> {
294    if root.is_empty() || root.len() > 6 || !root.bytes().all(|c| c.is_ascii_alphanumeric()) {
295        return Err(OptionInstrumentIdError::InvalidRoot {
296            value: root.to_string(),
297            reason: "OSI root must be one to six ASCII alphanumeric characters".to_string(),
298        });
299    }
300
301    if !(2000..=2099).contains(&expiry.year()) {
302        return Err(invalid_expiry(
303            expiry,
304            "OSI expiry year must be in [2000, 2099]",
305        ));
306    }
307
308    let reason = "OSI strike must fit eight digits of exact non-negative thousandths";
309    let scaled = strike_digits(strike, 3, reason)?;
310    if scaled > 99_999_999 {
311        return Err(OptionInstrumentIdError::InvalidStrike {
312            value: strike.to_string(),
313            reason: reason.to_string(),
314        });
315    }
316
317    let year = expiry.year() % 100;
318    let month = expiry.month();
319    let day = expiry.day();
320    let side = option_letter(option_kind);
321    Ok(format!(
322        "{root:<6}{year:02}{month:02}{day:02}{side}{scaled:08}"
323    ))
324}
325
326fn equity_root(
327    root: &str,
328    future_month: u32,
329    expiry: Date,
330    day: i8,
331    week: i8,
332) -> Result<String, OptionInstrumentIdError> {
333    if matches!(root, "MES" | "MNQ")
334        && expiry >= Date::new(2026, 6, 29).expect("valid transition date")
335    {
336        return Err(invalid_expiry(
337            expiry,
338            "physical and financial micro option families are ambiguous",
339        ));
340    }
341
342    let (daily, friday, eom, quarterly) = match root {
343        "ES" => ("E", "EW", "EW", "ES"),
344        "NQ" => ("Q", "QN", "QNE", "NQ"),
345        "RTY" => ("R", "R", "RTM", "RTO"),
346        "MES" => ("X", "EX", "EX", "MES"),
347        "MNQ" => ("D", "MQ", "MQE", "MNQ"),
348        _ => unreachable!("equity root dispatched by caller"),
349    };
350
351    if business_days_remaining(expiry) == 0 {
352        return Ok(eom.to_string());
353    }
354
355    if day == 5 && week == 3 && expiry.month() % 3 == 0 && future_month == expiry.month() as u32 {
356        return Ok(quarterly.to_string());
357    }
358
359    if day == 5 {
360        let suffix = if root == "RTY" { "E" } else { "" };
361        return Ok(format!("{friday}{week}{suffix}"));
362    }
363
364    let day_code = match (root, day) {
365        ("RTY", 2) => 'U',
366        (_, 1) => 'A',
367        (_, 2) => 'B',
368        (_, 3) => 'C',
369        _ => 'D',
370    };
371
372    Ok(format!("{daily}{week}{day_code}"))
373}
374
375fn sofr_root(
376    expiry: Date,
377    mid_curve: Option<u8>,
378    day: i8,
379    week: i8,
380) -> Result<String, OptionInstrumentIdError> {
381    let day_fifteen = Date::new(expiry.year(), expiry.month(), 15).expect("valid fifteenth day");
382    let third_wednesday = 15 + (3 - day_fifteen.weekday().to_monday_one_offset()).rem_euclid(7);
383    let monthly = day == 5 && expiry.day() == third_wednesday - 5;
384
385    let base = match mid_curve {
386        None => "SR3".to_string(),
387        Some(tenor @ (0 | 2 | 3 | 4 | 5)) => format!("S{tenor}"),
388        _ => {
389            return Err(OptionInstrumentIdError::InvalidRoot {
390                value: format!("SR3 midcurve {mid_curve:?}"),
391                reason: "unsupported SOFR midcurve tenor".to_string(),
392            });
393        }
394    };
395
396    if monthly {
397        return Ok(base);
398    }
399
400    if day != 5 || !matches!(mid_curve, Some(0 | 2 | 3)) {
401        return Err(invalid_expiry(
402            expiry,
403            "unsupported SOFR weekly expiry or tenor",
404        ));
405    }
406
407    Ok(format!("{base}{week}"))
408}
409
410fn crude_root(expiry: Date, day: i8, week: i8) -> Result<String, OptionInstrumentIdError> {
411    let anchor = Date::new(expiry.year(), expiry.month(), 25).expect("valid twenty-fifth day");
412    let monthly = previous_weekdays(previous_weekdays(anchor, 0)?, 6)?;
413    if expiry == monthly {
414        return Err(invalid_expiry(
415            expiry,
416            "monthly and weekly WTI expiries require a verified definition",
417        ));
418    }
419
420    let prefix = match day {
421        1 => "ML",
422        2 => "NL",
423        3 => "WL",
424        4 => "XL",
425        _ => "LO",
426    };
427
428    Ok(format!("{prefix}{week}"))
429}
430
431fn cme_strike(root: &str, strike: Price) -> Result<u128, OptionInstrumentIdError> {
432    let precision = match root {
433        "SR3" | "CL" => 2,
434        _ => 0,
435    };
436
437    let scaled = strike_digits(
438        strike,
439        precision,
440        "strike cannot be represented as integral CME symbol digits",
441    )?;
442
443    if scaled == 0 {
444        return Err(OptionInstrumentIdError::InvalidStrike {
445            value: strike.to_string(),
446            reason: "strike must be positive".to_string(),
447        });
448    }
449
450    Ok(scaled)
451}
452
453fn strike_digits(
454    strike: Price,
455    precision: u8,
456    reason: &str,
457) -> Result<u128, OptionInstrumentIdError> {
458    if strike.is_undefined()
459        || strike.is_error()
460        || check_fixed_precision(strike.precision).is_err()
461    {
462        return Err(OptionInstrumentIdError::InvalidStrike {
463            value: format!("raw={}, precision={}", strike.raw(), strike.precision),
464            reason: "strike must be a numeric price with valid precision".to_string(),
465        });
466    }
467
468    let divisor = raw_scale(strike.precision) / 10_u128.pow(u32::from(precision));
469    #[allow(
470        clippy::useless_conversion,
471        reason = "raw magnitude is u64 in standard precision and u128 in high precision"
472    )]
473    let raw = u128::from(strike.raw().unsigned_abs());
474    if strike.is_negative() || raw % divisor != 0 {
475        return Err(OptionInstrumentIdError::InvalidStrike {
476            value: strike.to_string(),
477            reason: reason.to_string(),
478        });
479    }
480
481    Ok(raw / divisor)
482}
483
484fn previous_weekdays(mut date: Date, mut count: u8) -> Result<Date, OptionInstrumentIdError> {
485    while date.weekday().to_monday_one_offset() > 5 || count > 0 {
486        date = date
487            .yesterday()
488            .map_err(|e| invalid_expiry(date, &e.to_string()))?;
489
490        if date.weekday().to_monday_one_offset() <= 5 && count > 0 {
491            count -= 1;
492        }
493    }
494
495    Ok(date)
496}
497
498fn business_days_remaining(expiry: Date) -> u8 {
499    let mut days = 0;
500    let mut date = expiry;
501    while let Ok(next) = date.tomorrow() {
502        if next.month() != expiry.month() {
503            break;
504        }
505
506        if next.weekday().to_monday_one_offset() <= 5 {
507            days += 1;
508        }
509
510        date = next;
511    }
512
513    days
514}
515
516fn option_letter(kind: OptionKind) -> char {
517    match kind {
518        OptionKind::Call => 'C',
519        OptionKind::Put => 'P',
520    }
521}
522
523fn invalid_expiry(expiry: Date, reason: &str) -> OptionInstrumentIdError {
524    OptionInstrumentIdError::InvalidExpiration {
525        value: expiry.to_string(),
526        reason: reason.to_string(),
527    }
528}
529
530#[cfg(test)]
531mod tests {
532    use rstest::*;
533
534    use super::*;
535    use crate::types::{
536        ERROR_PRICE, PRICE_ERROR, PRICE_UNDEF, fixed::FIXED_PRECISION, price::PriceRaw,
537    };
538
539    #[rstest]
540    #[case(0)]
541    #[case(FIXED_PRECISION)]
542    fn test_option_builders_reject_raw_strike_remainders(#[case] precision: u8) {
543        let scale = PriceRaw::try_from(crate::types::fixed::raw_scale(precision)).unwrap();
544
545        let strike = Price {
546            raw: 150 * scale + 1,
547            precision,
548        };
549
550        let cme =
551            cme_globex_option_symbol("ESH6", strike, OptionKind::Call, date(2026, 1, 9), None);
552        let osi = osi_option_symbol("AAPL", date(2026, 1, 9), OptionKind::Call, strike);
553
554        assert!(matches!(
555            cme,
556            Err(OptionInstrumentIdError::InvalidStrike { .. })
557        ));
558        assert!(matches!(
559            osi,
560            Err(OptionInstrumentIdError::InvalidStrike { .. })
561        ));
562    }
563
564    #[rstest]
565    #[case(0)]
566    #[case(FIXED_PRECISION)]
567    fn test_option_builders_preserve_raw_strike(#[case] precision: u8) {
568        let scale = PriceRaw::try_from(crate::types::fixed::raw_scale(precision)).unwrap();
569
570        let strike = Price {
571            raw: 75 * scale + scale / 4,
572            precision,
573        };
574
575        let cme =
576            cme_globex_option_symbol("CLH6", strike, OptionKind::Call, date(2026, 1, 9), None)
577                .unwrap();
578        let osi = osi_option_symbol("AAPL", date(2026, 1, 9), OptionKind::Call, strike).unwrap();
579
580        assert_eq!(cme, "LO2F6 C7525");
581        assert_eq!(osi, "AAPL  260109C00075250");
582    }
583
584    #[rstest]
585    #[case(ERROR_PRICE)]
586    #[case(Price::from_raw(PRICE_ERROR, 0))]
587    #[case(Price::from_raw(PRICE_UNDEF, 0))]
588    fn test_option_builders_reject_strike_sentinels(#[case] strike: Price) {
589        let cme =
590            cme_globex_option_symbol("ESH6", strike, OptionKind::Call, date(2026, 1, 9), None);
591        let osi = osi_option_symbol("AAPL", date(2026, 1, 9), OptionKind::Call, strike);
592
593        assert!(matches!(
594            cme,
595            Err(OptionInstrumentIdError::InvalidStrike { .. })
596        ));
597        assert!(matches!(
598            osi,
599            Err(OptionInstrumentIdError::InvalidStrike { .. })
600        ));
601    }
602
603    #[cfg(feature = "high-precision")]
604    #[rstest]
605    fn test_option_builders_reject_strike_beyond_decimal_mantissa() {
606        let scale = PriceRaw::try_from(crate::types::fixed::raw_scale(FIXED_PRECISION)).unwrap();
607        let strike = Price::from_raw(10_000_000_000_000 * scale + 1, FIXED_PRECISION);
608        let cme =
609            cme_globex_option_symbol("ESH6", strike, OptionKind::Call, date(2026, 1, 9), None);
610        let osi = osi_option_symbol("AAPL", date(2026, 1, 9), OptionKind::Call, strike);
611
612        assert!(matches!(
613            cme,
614            Err(OptionInstrumentIdError::InvalidStrike { .. })
615        ));
616        assert!(matches!(
617            osi,
618            Err(OptionInstrumentIdError::InvalidStrike { .. })
619        ));
620    }
621
622    #[rstest]
623    #[case("ESH6", "7250", "2026-01-27", OptionKind::Call, "E4BF6 C7250")]
624    #[case("ESH6", "7100", "2026-01-08", OptionKind::Put, "E2DF6 P7100")]
625    #[case("ESH26", "7000", "2026-01-09", OptionKind::Call, "EW2F26 C7000")]
626    #[case("ESH6", "5300", "2026-01-16", OptionKind::Call, "EW3F6 C5300")]
627    #[case("ESH6", "7250", "2026-01-30", OptionKind::Call, "EWF6 C7250")]
628    #[case("ESH6", "7250", "2026-01-30", OptionKind::Put, "EWF6 P7250")]
629    #[case("ESH6", "7000", "2026-03-20", OptionKind::Put, "ESH6 P7000")]
630    #[case("ESU6", "9600", "2026-09-18", OptionKind::Call, "ESU6 C9600")]
631    #[case("ESU6", "6575", "2026-09-18", OptionKind::Put, "ESU6 P6575")]
632    #[case("ESM4", "3550", "2024-06-21", OptionKind::Call, "ESM4 C3550")]
633    #[case("SR3Z3", "95.75", "2023-12-15", OptionKind::Put, "SR3Z3 P9575")]
634    #[case("ESH6", "6000.00", "2025-12-31", OptionKind::Call, "EWZ5 C6000")]
635    #[case("NQH6", "18000", "2026-01-13", OptionKind::Put, "Q2BF6 P18000")]
636    #[case("NQH6", "18000", "2026-01-09", OptionKind::Call, "QN2F6 C18000")]
637    #[case("NQH6", "18000", "2026-01-30", OptionKind::Put, "QNEF6 P18000")]
638    #[case("RTYH6", "2500", "2026-01-13", OptionKind::Call, "R2UF6 C2500")]
639    #[case("RTYH6", "2500", "2026-01-09", OptionKind::Put, "R2EF6 P2500")]
640    #[case("RTYH6", "2500", "2026-01-30", OptionKind::Call, "RTMF6 C2500")]
641    #[case("RTYH6", "2500", "2026-03-20", OptionKind::Call, "RTOH6 C2500")]
642    #[case("MESH6", "5300", "2026-01-13", OptionKind::Call, "X2BF6 C5300")]
643    #[case("MNQH6", "18000", "2026-01-08", OptionKind::Put, "D2DF6 P18000")]
644    #[case("CLZ5", "75", "2025-11-14", OptionKind::Put, "LO2X5 P7500")]
645    #[case("CLZ5", "75", "2025-11-10", OptionKind::Call, "ML2X5 C7500")]
646    #[case("CLZ5", "75", "2025-11-11", OptionKind::Put, "NL2X5 P7500")]
647    #[case("CLZ5", "75", "2025-11-12", OptionKind::Call, "WL2X5 C7500")]
648    #[case("CLZ5", "75", "2025-11-13", OptionKind::Put, "XL2X5 P7500")]
649    fn test_compute_cme_fixtures(
650        #[case] underlying: &str,
651        #[case] strike: &str,
652        #[case] expiry: &str,
653        #[case] kind: OptionKind,
654        #[case] expected: &str,
655    ) {
656        let underlying_id = InstrumentId::from_str(&format!("{underlying}.XCME")).unwrap();
657        let spec =
658            OptionContractSpec::from_expiry(underlying_id, Price::from(strike), expiry, kind)
659                .unwrap();
660        let id = compute_option_instrument_id(
661            &spec,
662            &OptionSymbologyScheme::CmeGlobex { mid_curve: None },
663            Venue::from("GLBX"),
664        )
665        .unwrap();
666        assert_eq!(id.symbol.as_str(), expected);
667        assert_eq!(id.venue, Venue::from("GLBX"));
668        assert_eq!(spec.underlying_instrument_id, underlying_id);
669        assert_eq!(spec.strike, Price::from(strike));
670        assert_eq!(spec.option_kind, kind);
671        assert_eq!(spec.expiration_ns, UnixNanos::from_str(expiry).unwrap());
672    }
673
674    #[rstest]
675    #[case("2026-03-13", Some(0), "S0H6 C9800")]
676    #[case("2026-03-20", Some(0), "S03H6 C9800")]
677    #[case("2026-03-13", Some(2), "S2H6 C9800")]
678    #[case("2026-03-13", Some(4), "S4H6 C9800")]
679    #[case("2026-03-13", None, "SR3H6 C9800")]
680    fn test_sofr_midcurve_fixtures(
681        #[case] expiry: &str,
682        #[case] tenor: Option<u8>,
683        #[case] expected: &str,
684    ) {
685        let spec = OptionContractSpec::from_expiry(
686            InstrumentId::from("SR3H7.XCME"),
687            Price::from("98"),
688            expiry,
689            OptionKind::Call,
690        )
691        .unwrap();
692        let id = compute_option_instrument_id(
693            &spec,
694            &OptionSymbologyScheme::CmeGlobex { mid_curve: tenor },
695            Venue::from("XCME"),
696        )
697        .unwrap();
698        assert_eq!(id.to_string(), format!("{expected}.XCME"));
699    }
700
701    #[rstest]
702    #[case("esh6")]
703    #[case("H6")]
704    #[case("ES6")]
705    #[case("ESH")]
706    #[case("ES H6")]
707    #[case("")]
708    #[case("123")]
709    #[case("ESH12345")]
710    #[case("ESH123")]
711    #[case("ESH2026")]
712    #[case("ÉSH6")]
713    fn test_invalid_future_code(#[case] code: &str) {
714        let error = cme_globex_option_symbol(
715            code,
716            Price::from("100"),
717            OptionKind::Call,
718            date(2026, 1, 9),
719            None,
720        )
721        .unwrap_err();
722        assert!(
723            matches!(error, OptionInstrumentIdError::InvalidFutureCode { value, .. } if value == code)
724        );
725    }
726
727    #[rstest]
728    #[case("6EH6", None)]
729    #[case("ZNH6", None)]
730    #[case("ZFH6", None)]
731    #[case("ZTH6", None)]
732    #[case("ZBH6", None)]
733    #[case("TNH6", None)]
734    #[case("UBH6", None)]
735    #[case("GCG6", None)]
736    #[case("SIH6", None)]
737    #[case("NGZ5", None)]
738    #[case("ESH6", Some(0))]
739    #[case("SR3H7", Some(1))]
740    #[case("SR3H7", Some(6))]
741    fn test_unsupported_cme_root(#[case] code: &str, #[case] tenor: Option<u8>) {
742        let error = cme_globex_option_symbol(
743            code,
744            Price::from("100"),
745            OptionKind::Call,
746            date(2026, 1, 9),
747            tenor,
748        )
749        .unwrap_err();
750        assert!(matches!(error, OptionInstrumentIdError::InvalidRoot { .. }));
751    }
752
753    #[rstest]
754    #[case("ESH6", date(2026, 1, 31), None)]
755    #[case("MESH6", date(2026, 7, 2), None)]
756    #[case("CLZ5", date(2025, 11, 17), None)]
757    #[case("SR3H7", date(2026, 3, 20), None)]
758    #[case("SR3H7", date(2026, 3, 20), Some(4))]
759    fn test_unrepresentable_cme_expiry(
760        #[case] code: &str,
761        #[case] expiry: Date,
762        #[case] tenor: Option<u8>,
763    ) {
764        let error =
765            cme_globex_option_symbol(code, Price::from("100"), OptionKind::Call, expiry, tenor)
766                .unwrap_err();
767        assert!(
768            matches!(error, OptionInstrumentIdError::InvalidExpiration { value, .. } if value == expiry.to_string())
769        );
770    }
771
772    #[rstest]
773    #[case("0")]
774    #[case("-1")]
775    fn test_cme_nonpositive_strike(#[case] strike: &str) {
776        let error = cme_globex_option_symbol(
777            "ESH6",
778            Price::from(strike),
779            OptionKind::Call,
780            date(2026, 1, 9),
781            None,
782        )
783        .unwrap_err();
784        assert!(
785            matches!(error, OptionInstrumentIdError::InvalidStrike { value, .. } if value == strike)
786        );
787    }
788
789    #[rstest]
790    #[case("ESH6", "7000.5")]
791    #[case("SR3H7", "95.751")]
792    #[case("CLZ5", "75.001")]
793    fn test_cme_unrepresentable_strike(#[case] code: &str, #[case] strike: &str) {
794        let error = cme_globex_option_symbol(
795            code,
796            Price::from(strike),
797            OptionKind::Call,
798            date(2026, 1, 9),
799            code.starts_with("SR3").then_some(0),
800        )
801        .unwrap_err();
802        assert_eq!(
803            error,
804            OptionInstrumentIdError::InvalidStrike {
805                value: strike.to_string(),
806                reason: "strike cannot be represented as integral CME symbol digits".to_string(),
807            }
808        );
809    }
810
811    #[rstest]
812    #[case(None, "AAPL  231215C00150000.OPRA")]
813    #[case(Some("SPXW"), "SPXW  231215C00150000.OPRA")]
814    fn test_compute_osi_root_and_venue(#[case] root: Option<&str>, #[case] expected: &str) {
815        let spec = OptionContractSpec::from_expiry(
816            InstrumentId::from("AAPL.XNAS"),
817            Price::from("150"),
818            "2023-12-15",
819            OptionKind::Call,
820        )
821        .unwrap();
822
823        let id = compute_option_instrument_id(
824            &spec,
825            &OptionSymbologyScheme::Osi {
826                root: root.map(str::to_string),
827            },
828            Venue::from("OPRA"),
829        )
830        .unwrap();
831
832        assert_eq!(id.to_string(), expected);
833    }
834
835    #[rstest]
836    fn test_invalid_spec_expiry() {
837        let error = OptionContractSpec::from_expiry(
838            InstrumentId::from("ESH6.XCME"),
839            Price::from("7250"),
840            "not-a-date",
841            OptionKind::Call,
842        )
843        .unwrap_err();
844        assert!(
845            matches!(error, OptionInstrumentIdError::InvalidExpiration { value, .. } if value == "not-a-date")
846        );
847    }
848
849    #[rstest]
850    #[case(
851        "AAPL",
852        date(2023, 12, 15),
853        OptionKind::Call,
854        "150",
855        "AAPL  231215C00150000"
856    )]
857    #[case(
858        "SPY",
859        date(2024, 1, 19),
860        OptionKind::Put,
861        "340",
862        "SPY   240119P00340000"
863    )]
864    #[case(
865        "SPXW",
866        date(2026, 1, 20),
867        OptionKind::Put,
868        "6835",
869        "SPXW  260120P06835000"
870    )]
871    #[case(
872        "F",
873        date(2024, 6, 21),
874        OptionKind::Call,
875        "12.5",
876        "F     240621C00012500"
877    )]
878    #[case(
879        "BRKB",
880        date(2024, 6, 21),
881        OptionKind::Call,
882        "412.375",
883        "BRKB  240621C00412375"
884    )]
885    fn test_osi_option_symbol(
886        #[case] root: &str,
887        #[case] expiry: Date,
888        #[case] kind: OptionKind,
889        #[case] strike: &str,
890        #[case] expected: &str,
891    ) {
892        let symbol = osi_option_symbol(root, expiry, kind, Price::from(strike)).unwrap();
893        assert_eq!(symbol, expected);
894        assert_eq!(symbol.len(), 21);
895    }
896
897    #[rstest]
898    fn test_osi_rejects_long_root() {
899        let result = osi_option_symbol(
900            "TOOLONG",
901            date(2024, 6, 21),
902            OptionKind::Call,
903            Price::from("100"),
904        );
905        assert!(matches!(
906            result,
907            Err(OptionInstrumentIdError::InvalidRoot { .. })
908        ));
909    }
910
911    #[rstest]
912    fn test_osi_rejects_non_ascii_root() {
913        let result = osi_option_symbol(
914            "SPÉ",
915            date(2024, 6, 21),
916            OptionKind::Call,
917            Price::from("100"),
918        );
919        assert!(matches!(
920            result,
921            Err(OptionInstrumentIdError::InvalidRoot { .. })
922        ));
923    }
924
925    #[rstest]
926    fn test_osi_rejects_sub_thousandth_strike() {
927        let result = osi_option_symbol(
928            "AAPL",
929            date(2024, 6, 21),
930            OptionKind::Call,
931            Price::from("150.1234"),
932        );
933        assert!(matches!(
934            result,
935            Err(OptionInstrumentIdError::InvalidStrike { .. })
936        ));
937    }
938
939    #[rstest]
940    fn test_osi_rejects_strike_over_eight_digits() {
941        let result = osi_option_symbol(
942            "AAPL",
943            date(2024, 6, 21),
944            OptionKind::Call,
945            Price::from("100000"),
946        );
947        assert!(matches!(
948            result,
949            Err(OptionInstrumentIdError::InvalidStrike { .. })
950        ));
951    }
952
953    #[rstest]
954    fn test_osi_rejects_pre_2000_expiration() {
955        let result = osi_option_symbol(
956            "AAPL",
957            date(1999, 12, 17),
958            OptionKind::Call,
959            Price::from("100"),
960        );
961        assert!(matches!(
962            result,
963            Err(OptionInstrumentIdError::InvalidExpiration { .. })
964        ));
965    }
966
967    #[rstest]
968    #[case("0", "AAPL  991231C00000000")]
969    #[case("99999.999", "AAPL  991231C99999999")]
970    fn test_osi_strike_boundaries(#[case] strike: &str, #[case] expected: &str) {
971        let symbol = osi_option_symbol(
972            "AAPL",
973            date(2099, 12, 31),
974            OptionKind::Call,
975            Price::from(strike),
976        )
977        .unwrap();
978        assert_eq!(symbol, expected);
979    }
980
981    #[rstest]
982    fn test_osi_negative_strike_returns_typed_error() {
983        let error = osi_option_symbol(
984            "AAPL",
985            date(2024, 6, 21),
986            OptionKind::Put,
987            Price::from("-1"),
988        )
989        .unwrap_err();
990        assert_eq!(
991            error,
992            OptionInstrumentIdError::InvalidStrike {
993                value: "-1".to_string(),
994                reason: "OSI strike must fit eight digits of exact non-negative thousandths"
995                    .to_string(),
996            }
997        );
998    }
999
1000    fn date(year: i16, month: i8, day: i8) -> Date {
1001        Date::new(year, month, day).unwrap()
1002    }
1003}