Skip to main content

nautilus_model/data/
option_chain.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//! Option chain data types for aggregated option series snapshots.
17
18use std::{
19    collections::{BTreeMap, HashSet},
20    fmt::Display,
21    ops::Deref,
22};
23
24use nautilus_core::{
25    UnixNanos,
26    correctness::{CorrectnessResult, check_non_negative_f64, check_predicate_true},
27    serialization::Serializable,
28};
29use rust_decimal::{Decimal, prelude::ToPrimitive};
30use serde::{Deserialize, Serialize};
31
32use super::HasTsInit;
33use crate::{
34    data::{
35        QuoteTick,
36        greeks::{HasGreeks, OptionGreekValues},
37    },
38    enums::GreeksConvention,
39    identifiers::{InstrumentId, OptionSeriesId},
40    types::Price,
41};
42
43/// Number of strikes either side of ATM that [`StrikeRange::Delta`] selects as a
44/// fallback when Greeks are not yet available for delta resolution.
45pub(crate) const DEFAULT_DELTA_FALLBACK_STRIKES: usize = 5;
46
47/// An ordered set of strike grids and a bound on definition candidates per slot.
48///
49/// Increments express discovery preference. They do not prove that a strike is listed.
50#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
51pub struct StrikeSearchProfile {
52    increments: Vec<Decimal>,
53    origin: Decimal,
54    max_candidates_per_slot: usize,
55}
56
57impl StrikeSearchProfile {
58    /// Creates a checked strike-search profile.
59    ///
60    /// # Errors
61    ///
62    /// Returns an error if:
63    /// - The increments are empty, non-positive, or duplicated.
64    /// - The origin is negative.
65    /// - The candidate bound is zero.
66    pub fn new(
67        increments: Vec<Decimal>,
68        origin: Decimal,
69        max_candidates_per_slot: usize,
70    ) -> anyhow::Result<Self> {
71        anyhow::ensure!(
72            !increments.is_empty(),
73            "strike search profile requires at least one increment"
74        );
75        anyhow::ensure!(
76            increments.iter().all(|value| *value > Decimal::ZERO),
77            "strike search profile increments must be positive"
78        );
79        let mut seen = HashSet::with_capacity(increments.len());
80        for increment in &increments {
81            anyhow::ensure!(
82                seen.insert(increment.normalize()),
83                "strike search profile increments must be unique (duplicate {increment})"
84            );
85        }
86
87        anyhow::ensure!(
88            origin >= Decimal::ZERO,
89            "strike search profile origin must be non-negative"
90        );
91        anyhow::ensure!(
92            max_candidates_per_slot > 0,
93            "strike search profile requires a positive candidate bound"
94        );
95        Ok(Self {
96            increments,
97            origin,
98            max_candidates_per_slot,
99        })
100    }
101
102    /// Returns strike increments in discovery preference order.
103    #[must_use]
104    pub fn increments(&self) -> &[Decimal] {
105        &self.increments
106    }
107
108    /// Returns the origin shared by the strike grids.
109    #[must_use]
110    pub const fn origin(&self) -> Decimal {
111        self.origin
112    }
113
114    /// Returns the maximum number of candidates probed per strike slot.
115    #[must_use]
116    pub const fn max_candidates_per_slot(&self) -> usize {
117        self.max_candidates_per_slot
118    }
119}
120
121impl<'de> Deserialize<'de> for StrikeSearchProfile {
122    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
123    where
124        D: serde::Deserializer<'de>,
125    {
126        #[derive(Deserialize)]
127        struct Fields {
128            increments: Vec<Decimal>,
129            origin: Decimal,
130            max_candidates_per_slot: usize,
131        }
132        let fields = Fields::deserialize(deserializer)?;
133        Self::new(
134            fields.increments,
135            fields.origin,
136            fields.max_candidates_per_slot,
137        )
138        .map_err(serde::de::Error::custom)
139    }
140}
141
142/// Defines which strikes to include in an option chain subscription.
143///
144/// [`Self::atm_percent`] and [`Self::delta`] validate numeric inputs at construction.
145/// Direct variants and deserialization leave input validity to the caller.
146///
147/// Existing variants support direct construction. Downstream matches require a
148/// wildcard arm so new selection modes can be added without changing those matches.
149/// Use [`Self::resolve`] for model-level selection, or reject unsupported modes
150/// explicitly when implementing a custom selector.
151///
152/// An exhaustive match outside this crate does not compile:
153///
154/// ```compile_fail,E0004
155/// use nautilus_model::data::StrikeRange;
156///
157/// fn is_fixed(range: &StrikeRange) -> bool {
158///     match range {
159///         StrikeRange::Fixed(_) => true,
160///         StrikeRange::AtmRelative { .. } => false,
161///         StrikeRange::AtmPercent { .. } => false,
162///         StrikeRange::Delta { .. } => false,
163///     }
164/// }
165/// ```
166#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
167#[non_exhaustive]
168pub enum StrikeRange {
169    /// Subscribe to a fixed set of strike prices.
170    Fixed(Vec<Price>),
171    /// Subscribe to strikes relative to ATM: N strikes above and N below.
172    AtmRelative {
173        strikes_above: usize,
174        strikes_below: usize,
175    },
176    /// Subscribe to strikes within a percentage band around ATM price.
177    AtmPercent { pct: f64 },
178    /// Subscribe to strikes whose absolute option delta is near `target`.
179    ///
180    /// Delta resolution needs Greeks, so the option chain aggregator performs it.
181    /// The model-level [`StrikeRange::resolve`] has no Greeks and falls back to an
182    /// ATM-relative window of `DEFAULT_DELTA_FALLBACK_STRIKES` strikes either side
183    /// of ATM until Greeks are available.
184    Delta { target: f64, tolerance: f64 },
185}
186
187impl StrikeRange {
188    /// Creates an ATM-percentage strike range.
189    ///
190    /// # Errors
191    ///
192    /// Returns an error if `pct` is non-finite or negative.
193    pub fn atm_percent(pct: f64) -> CorrectnessResult<Self> {
194        check_non_negative_f64(pct, "pct")?;
195        Ok(Self::AtmPercent { pct })
196    }
197
198    /// Creates an absolute-delta strike range.
199    ///
200    /// # Errors
201    ///
202    /// Returns an error if `target` or `tolerance` is non-finite or outside [0, 1].
203    pub fn delta(target: f64, tolerance: f64) -> CorrectnessResult<Self> {
204        let bounds = 0.0..=1.0;
205        check_predicate_true(
206            bounds.contains(&target),
207            "target must be finite and in [0, 1]",
208        )?;
209        check_predicate_true(
210            bounds.contains(&tolerance),
211            "tolerance must be finite and in [0, 1]",
212        )?;
213        Ok(Self::Delta { target, tolerance })
214    }
215
216    /// Resolves the filtered set of strikes from all available strikes.
217    ///
218    /// - `Fixed`: returns the fixed strikes directly (intersected with available).
219    /// - `AtmRelative`: finds the closest strike to ATM, takes N above and N below.
220    /// - `AtmPercent`: filters strikes within a percentage band around ATM.
221    /// - `Delta`: has no Greeks at this level, so it falls back to an ATM-relative
222    ///   window of `DEFAULT_DELTA_FALLBACK_STRIKES` strikes either side of ATM. The
223    ///   option chain aggregator resolves `Delta` from Greeks instead.
224    ///
225    /// If `atm_price` is `None` for ATM-based variants, returns an empty vec
226    /// (subscriptions are deferred until ATM is known).
227    #[must_use]
228    pub fn resolve(&self, atm_price: Option<Price>, all_strikes: &[Price]) -> Vec<Price> {
229        match self {
230            Self::Fixed(strikes) => {
231                if all_strikes.is_empty() {
232                    strikes.clone()
233                } else {
234                    let available: HashSet<Price> = all_strikes.iter().copied().collect();
235                    strikes
236                        .iter()
237                        .filter(|s| available.contains(s))
238                        .copied()
239                        .collect()
240                }
241            }
242            Self::AtmRelative {
243                strikes_above,
244                strikes_below,
245            } => {
246                let Some(atm) = atm_price else {
247                    return vec![]; // Defer until ATM is known
248                };
249                // Find index of closest strike to ATM
250                let atm_idx = match all_strikes.binary_search(&atm) {
251                    Ok(idx) => idx,
252                    Err(idx) => {
253                        if idx == 0 {
254                            0
255                        } else if idx >= all_strikes.len() {
256                            all_strikes.len() - 1
257                        } else {
258                            // Pick the closer of the two neighbors
259                            let diff_below = all_strikes[idx - 1].raw().abs_diff(atm.raw());
260                            let diff_above = all_strikes[idx].raw().abs_diff(atm.raw());
261                            if diff_below <= diff_above {
262                                idx - 1
263                            } else {
264                                idx
265                            }
266                        }
267                    }
268                };
269                let start = atm_idx.saturating_sub(*strikes_below);
270                let end = atm_idx
271                    .saturating_add(*strikes_above)
272                    .saturating_add(1)
273                    .min(all_strikes.len());
274                all_strikes[start..end].to_vec()
275            }
276            Self::AtmPercent { pct } => {
277                let Some(atm) = atm_price else {
278                    return vec![]; // Defer until ATM is known
279                };
280                let atm_decimal = atm.as_decimal();
281                if atm_decimal.is_zero() {
282                    return all_strikes.to_vec();
283                }
284                all_strikes
285                    .iter()
286                    .filter(|s| {
287                        let distance = (s.as_decimal() - atm_decimal).abs();
288                        let pct_diff = distance / atm_decimal.abs();
289                        pct_diff.to_f64().is_some_and(|pct_diff| pct_diff <= *pct)
290                    })
291                    .copied()
292                    .collect()
293            }
294            Self::Delta { .. } => Self::AtmRelative {
295                strikes_above: DEFAULT_DELTA_FALLBACK_STRIKES,
296                strikes_below: DEFAULT_DELTA_FALLBACK_STRIKES,
297            }
298            .resolve(atm_price, all_strikes),
299        }
300    }
301}
302
303/// Exchange-provided option Greeks and implied volatility for a single instrument.
304#[repr(C)]
305#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
306#[serde(tag = "type")]
307#[cfg_attr(
308    feature = "python",
309    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
310)]
311#[cfg_attr(
312    feature = "python",
313    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
314)]
315pub struct OptionGreeks {
316    /// The instrument ID these Greeks apply to.
317    pub instrument_id: InstrumentId,
318    /// The numeraire convention these Greeks are expressed in.
319    pub convention: GreeksConvention,
320    /// Core Greek sensitivity values.
321    pub greeks: OptionGreekValues,
322    /// Mark implied volatility as a fraction (0.552 represents 55.2%).
323    pub mark_iv: Option<f64>,
324    /// Bid implied volatility as a fraction (0.552 represents 55.2%).
325    pub bid_iv: Option<f64>,
326    /// Ask implied volatility as a fraction (0.552 represents 55.2%).
327    pub ask_iv: Option<f64>,
328    /// Underlying price at time of Greeks calculation.
329    pub underlying_price: Option<f64>,
330    /// Open interest for the instrument.
331    pub open_interest: Option<f64>,
332    /// UNIX timestamp (nanoseconds) when the event occurred.
333    pub ts_event: UnixNanos,
334    /// UNIX timestamp (nanoseconds) when the instance was initialized.
335    pub ts_init: UnixNanos,
336}
337
338impl HasTsInit for OptionGreeks {
339    fn ts_init(&self) -> UnixNanos {
340        self.ts_init
341    }
342}
343
344impl Deref for OptionGreeks {
345    type Target = OptionGreekValues;
346    fn deref(&self) -> &Self::Target {
347        &self.greeks
348    }
349}
350
351impl HasGreeks for OptionGreeks {
352    fn greeks(&self) -> OptionGreekValues {
353        self.greeks
354    }
355}
356
357impl Default for OptionGreeks {
358    fn default() -> Self {
359        Self {
360            instrument_id: InstrumentId::from("NULL.NULL"),
361            convention: GreeksConvention::default(),
362            greeks: OptionGreekValues::default(),
363            mark_iv: None,
364            bid_iv: None,
365            ask_iv: None,
366            underlying_price: None,
367            open_interest: None,
368            ts_event: UnixNanos::default(),
369            ts_init: UnixNanos::default(),
370        }
371    }
372}
373
374impl Display for OptionGreeks {
375    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
376        write!(
377            f,
378            "OptionGreeks({}, {}, delta={:.4}, gamma={:.4}, vega={:.4}, theta={:.4}, mark_iv={:?})",
379            self.instrument_id,
380            self.convention,
381            self.delta,
382            self.gamma,
383            self.vega,
384            self.theta,
385            self.mark_iv
386        )
387    }
388}
389
390impl Serializable for OptionGreeks {}
391
392/// Combined quote and Greeks data for a single strike in an option chain.
393#[derive(Clone, Debug)]
394#[cfg_attr(
395    feature = "python",
396    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
397)]
398#[cfg_attr(
399    feature = "python",
400    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
401)]
402pub struct OptionStrikeData {
403    /// The latest quote for this strike.
404    pub quote: QuoteTick,
405    /// Exchange-provided Greeks (if available).
406    pub greeks: Option<OptionGreeks>,
407}
408
409/// A point-in-time snapshot of an option chain for a single series.
410#[derive(Clone, Debug)]
411#[cfg_attr(
412    feature = "python",
413    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
414)]
415#[cfg_attr(
416    feature = "python",
417    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
418)]
419pub struct OptionChainSlice {
420    /// The option series identifier.
421    pub series_id: OptionSeriesId,
422    /// The current ATM strike price (if determined).
423    pub atm_strike: Option<Price>,
424    /// Call option data keyed by strike price (sorted).
425    pub calls: BTreeMap<Price, OptionStrikeData>,
426    /// Put option data keyed by strike price (sorted).
427    pub puts: BTreeMap<Price, OptionStrikeData>,
428    /// UNIX timestamp (nanoseconds) when the snapshot event occurred.
429    pub ts_event: UnixNanos,
430    /// UNIX timestamp (nanoseconds) when the instance was initialized.
431    pub ts_init: UnixNanos,
432}
433
434impl HasTsInit for OptionChainSlice {
435    fn ts_init(&self) -> UnixNanos {
436        self.ts_init
437    }
438}
439
440impl Display for OptionChainSlice {
441    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
442        write!(
443            f,
444            "OptionChainSlice({}, atm={:?}, calls={}, puts={})",
445            self.series_id,
446            self.atm_strike,
447            self.calls.len(),
448            self.puts.len()
449        )
450    }
451}
452
453impl OptionChainSlice {
454    /// Creates a new empty [`OptionChainSlice`] for the given series.
455    #[must_use]
456    pub fn new(series_id: OptionSeriesId) -> Self {
457        Self {
458            series_id,
459            atm_strike: None,
460            calls: BTreeMap::new(),
461            puts: BTreeMap::new(),
462            ts_event: UnixNanos::default(),
463            ts_init: UnixNanos::default(),
464        }
465    }
466
467    /// Returns the number of call entries.
468    #[must_use]
469    pub fn call_count(&self) -> usize {
470        self.calls.len()
471    }
472
473    /// Returns the number of put entries.
474    #[must_use]
475    pub fn put_count(&self) -> usize {
476        self.puts.len()
477    }
478
479    /// Returns the call data for a given strike price.
480    #[must_use]
481    pub fn get_call(&self, strike: &Price) -> Option<&OptionStrikeData> {
482        self.calls.get(strike)
483    }
484
485    /// Returns the put data for a given strike price.
486    #[must_use]
487    pub fn get_put(&self, strike: &Price) -> Option<&OptionStrikeData> {
488        self.puts.get(strike)
489    }
490
491    /// Returns the call quote for a given strike price.
492    #[must_use]
493    pub fn get_call_quote(&self, strike: &Price) -> Option<&QuoteTick> {
494        self.calls.get(strike).map(|d| &d.quote)
495    }
496
497    /// Returns the call Greeks for a given strike price.
498    #[must_use]
499    pub fn get_call_greeks(&self, strike: &Price) -> Option<&OptionGreeks> {
500        self.calls.get(strike).and_then(|d| d.greeks.as_ref())
501    }
502
503    /// Returns the put quote for a given strike price.
504    #[must_use]
505    pub fn get_put_quote(&self, strike: &Price) -> Option<&QuoteTick> {
506        self.puts.get(strike).map(|d| &d.quote)
507    }
508
509    /// Returns the put Greeks for a given strike price.
510    #[must_use]
511    pub fn get_put_greeks(&self, strike: &Price) -> Option<&OptionGreeks> {
512        self.puts.get(strike).and_then(|d| d.greeks.as_ref())
513    }
514
515    /// Returns all strike prices present in the chain (union of calls and puts).
516    #[must_use]
517    pub fn strikes(&self) -> Vec<Price> {
518        let mut strikes: Vec<Price> = self.calls.keys().chain(self.puts.keys()).copied().collect();
519        strikes.sort();
520        strikes.dedup();
521        strikes
522    }
523
524    /// Returns the total number of unique strikes.
525    #[must_use]
526    pub fn strike_count(&self) -> usize {
527        self.strikes().len()
528    }
529
530    /// Returns `true` if the chain has no data.
531    #[must_use]
532    pub fn is_empty(&self) -> bool {
533        self.calls.is_empty() && self.puts.is_empty()
534    }
535}
536
537#[cfg(test)]
538mod tests {
539    use rstest::*;
540
541    use super::*;
542    use crate::{identifiers::Venue, types::Quantity};
543
544    fn make_quote(instrument_id: InstrumentId) -> QuoteTick {
545        QuoteTick::new(
546            instrument_id,
547            Price::from("100.00"),
548            Price::from("101.00"),
549            Quantity::from("1.0"),
550            Quantity::from("1.0"),
551            UnixNanos::from(1u64),
552            UnixNanos::from(1u64),
553        )
554    }
555
556    fn make_series_id() -> OptionSeriesId {
557        OptionSeriesId::new_derived(
558            Venue::new("DERIBIT"),
559            ustr::Ustr::from("BTC"),
560            ustr::Ustr::from("BTC"),
561            UnixNanos::from(1_700_000_000_000_000_000u64),
562        )
563    }
564
565    #[rstest]
566    fn test_strike_range_fixed() {
567        let range = StrikeRange::Fixed(vec![Price::from("50000"), Price::from("55000")]);
568        assert_eq!(
569            range,
570            StrikeRange::Fixed(vec![Price::from("50000"), Price::from("55000")])
571        );
572    }
573
574    #[rstest]
575    fn test_strike_range_atm_relative() {
576        let range = StrikeRange::AtmRelative {
577            strikes_above: 5,
578            strikes_below: 5,
579        };
580
581        if let StrikeRange::AtmRelative {
582            strikes_above,
583            strikes_below,
584        } = range
585        {
586            assert_eq!(strikes_above, 5);
587            assert_eq!(strikes_below, 5);
588        } else {
589            panic!("Expected AtmRelative variant");
590        }
591    }
592
593    #[rstest]
594    fn test_strike_range_atm_percent() {
595        let range = StrikeRange::AtmPercent { pct: 0.1 };
596        if let StrikeRange::AtmPercent { pct } = range {
597            assert!((pct - 0.1).abs() < f64::EPSILON);
598        } else {
599            panic!("Expected AtmPercent variant");
600        }
601    }
602
603    #[rstest]
604    fn test_option_greeks_default_fields() {
605        let greeks = OptionGreeks {
606            instrument_id: InstrumentId::from("BTC-20240101-50000-C.DERIBIT"),
607            convention: GreeksConvention::BlackScholes,
608            greeks: OptionGreekValues::default(),
609            mark_iv: None,
610            bid_iv: None,
611            ask_iv: None,
612            underlying_price: None,
613            open_interest: None,
614            ts_event: UnixNanos::default(),
615            ts_init: UnixNanos::default(),
616        };
617        assert_eq!(greeks.delta, 0.0);
618        assert_eq!(greeks.gamma, 0.0);
619        assert_eq!(greeks.vega, 0.0);
620        assert_eq!(greeks.theta, 0.0);
621        assert!(greeks.mark_iv.is_none());
622        assert_eq!(greeks.convention, GreeksConvention::BlackScholes);
623    }
624
625    #[rstest]
626    fn test_option_greeks_default_is_black_scholes() {
627        let greeks = OptionGreeks::default();
628        assert_eq!(greeks.convention, GreeksConvention::BlackScholes);
629    }
630
631    #[rstest]
632    fn test_option_greeks_display() {
633        let greeks = OptionGreeks {
634            instrument_id: InstrumentId::from("BTC-20240101-50000-C.DERIBIT"),
635            convention: GreeksConvention::PriceAdjusted,
636            greeks: OptionGreekValues {
637                delta: 0.55,
638                gamma: 0.001,
639                vega: 10.0,
640                theta: -5.0,
641                rho: 0.0,
642            },
643            mark_iv: Some(0.65),
644            bid_iv: None,
645            ask_iv: None,
646            underlying_price: None,
647            open_interest: None,
648            ts_event: UnixNanos::default(),
649            ts_init: UnixNanos::default(),
650        };
651        let display = format!("{greeks}");
652        assert!(display.contains("OptionGreeks"));
653        assert!(display.contains("PRICE_ADJUSTED"));
654        assert!(display.contains("0.55"));
655    }
656
657    #[rstest]
658    fn test_option_greeks_data_serde_round_trip() {
659        let greeks = OptionGreeks {
660            instrument_id: InstrumentId::from("BTC-20240101-50000-C.DERIBIT"),
661            convention: GreeksConvention::PriceAdjusted,
662            greeks: OptionGreekValues {
663                delta: 0.55,
664                gamma: 0.001,
665                vega: 10.0,
666                theta: -5.0,
667                rho: 0.2,
668            },
669            mark_iv: Some(0.65),
670            bid_iv: None,
671            ask_iv: Some(0.66),
672            underlying_price: Some(50_000.0),
673            open_interest: None,
674            ts_event: UnixNanos::from(1u64),
675            ts_init: UnixNanos::from(2u64),
676        };
677        let data = crate::data::Data::OptionGreeks(greeks);
678
679        let json = serde_json::to_string(&data).unwrap();
680        let roundtripped: crate::data::Data = serde_json::from_str(&json).unwrap();
681
682        assert_eq!(roundtripped, data);
683    }
684
685    #[rstest]
686    fn test_option_chain_slice_empty() {
687        let slice = OptionChainSlice {
688            series_id: make_series_id(),
689            atm_strike: None,
690            calls: BTreeMap::new(),
691            puts: BTreeMap::new(),
692            ts_event: UnixNanos::from(1u64),
693            ts_init: UnixNanos::from(1u64),
694        };
695
696        assert!(slice.is_empty());
697        assert_eq!(slice.strike_count(), 0);
698        assert!(slice.strikes().is_empty());
699    }
700
701    #[rstest]
702    fn test_option_chain_slice_with_data() {
703        let call_id = InstrumentId::from("BTC-20240101-50000-C.DERIBIT");
704        let put_id = InstrumentId::from("BTC-20240101-50000-P.DERIBIT");
705        let strike = Price::from("50000");
706
707        let mut calls = BTreeMap::new();
708        calls.insert(
709            strike,
710            OptionStrikeData {
711                quote: make_quote(call_id),
712                greeks: Some(OptionGreeks {
713                    instrument_id: call_id,
714                    greeks: OptionGreekValues {
715                        delta: 0.55,
716                        ..Default::default()
717                    },
718                    ..Default::default()
719                }),
720            },
721        );
722
723        let mut puts = BTreeMap::new();
724        puts.insert(
725            strike,
726            OptionStrikeData {
727                quote: make_quote(put_id),
728                greeks: None,
729            },
730        );
731
732        let slice = OptionChainSlice {
733            series_id: make_series_id(),
734            atm_strike: Some(strike),
735            calls,
736            puts,
737            ts_event: UnixNanos::from(1u64),
738            ts_init: UnixNanos::from(1u64),
739        };
740
741        assert!(!slice.is_empty());
742        assert_eq!(slice.strike_count(), 1);
743        assert_eq!(slice.strikes(), vec![strike]);
744        assert!(slice.get_call(&strike).is_some());
745        assert!(slice.get_put(&strike).is_some());
746        assert!(slice.get_call_greeks(&strike).is_some());
747        assert!(slice.get_put_greeks(&strike).is_none());
748        assert_eq!(slice.get_call_greeks(&strike).unwrap().delta, 0.55);
749    }
750
751    #[rstest]
752    fn test_option_chain_slice_display() {
753        let slice = OptionChainSlice {
754            series_id: make_series_id(),
755            atm_strike: None,
756            calls: BTreeMap::new(),
757            puts: BTreeMap::new(),
758            ts_event: UnixNanos::from(1u64),
759            ts_init: UnixNanos::from(1u64),
760        };
761
762        let display = format!("{slice}");
763        assert!(display.contains("OptionChainSlice"));
764        assert!(display.contains("DERIBIT"));
765    }
766
767    #[rstest]
768    fn test_option_chain_slice_ts_init() {
769        let slice = OptionChainSlice {
770            series_id: make_series_id(),
771            atm_strike: None,
772            calls: BTreeMap::new(),
773            puts: BTreeMap::new(),
774            ts_event: UnixNanos::from(1u64),
775            ts_init: UnixNanos::from(42u64),
776        };
777
778        assert_eq!(slice.ts_init(), UnixNanos::from(42u64));
779    }
780
781    // -- StrikeRange::resolve tests --
782
783    #[rstest]
784    fn test_strike_range_preserves_subprecision_atm() {
785        let mut atm = Price::from("100.75");
786        atm.precision = 0;
787        let strikes = [Price::from("100"), Price::from("101")];
788
789        let range = StrikeRange::AtmRelative {
790            strikes_above: 0,
791            strikes_below: 0,
792        };
793
794        assert_eq!(range.resolve(Some(atm), &strikes), vec![strikes[1]]);
795    }
796
797    #[rstest]
798    fn test_strike_range_resolve_fixed() {
799        let range = StrikeRange::Fixed(vec![Price::from("50000"), Price::from("55000")]);
800        let result = range.resolve(None, &[]);
801        assert_eq!(result, vec![Price::from("50000"), Price::from("55000")]);
802    }
803
804    #[rstest]
805    fn test_strike_range_resolve_fixed_intersects_available_strikes() {
806        let range = StrikeRange::Fixed(vec![
807            Price::from("50000"),
808            Price::from("55000"),
809            Price::from("60000"),
810        ]);
811        let available = [
812            Price::from("45000"),
813            Price::from("50000"),
814            Price::from("60000"),
815        ];
816
817        let result = range.resolve(None, &available);
818
819        assert_eq!(result, vec![Price::from("50000"), Price::from("60000")]);
820    }
821
822    #[rstest]
823    fn test_strike_range_resolve_atm_relative() {
824        let range = StrikeRange::AtmRelative {
825            strikes_above: 2,
826            strikes_below: 2,
827        };
828        let strikes: Vec<Price> = [45000, 47000, 50000, 53000, 55000, 57000]
829            .iter()
830            .map(|s| Price::from(&s.to_string()))
831            .collect();
832        let atm = Some(Price::from("50000"));
833        let result = range.resolve(atm, &strikes);
834        // ATM at index 2, below=2 → start=0, above=2 → end=5
835        assert_eq!(result.len(), 5);
836        assert_eq!(result[0], Price::from("45000"));
837        assert_eq!(result[4], Price::from("55000"));
838    }
839
840    #[rstest]
841    #[case("49750", "50000")]
842    #[case("50250", "50000")]
843    #[case("51750", "52000")]
844    fn test_strike_range_resolve_atm_relative_selects_nearest_strike(
845        #[case] atm: &str,
846        #[case] expected: &str,
847    ) {
848        let range = StrikeRange::AtmRelative {
849            strikes_above: 0,
850            strikes_below: 0,
851        };
852        let strikes = [
853            Price::from("48000"),
854            Price::from("50000"),
855            Price::from("52000"),
856        ];
857
858        let result = range.resolve(Some(Price::from(atm)), &strikes);
859
860        assert_eq!(result, vec![Price::from(expected)]);
861    }
862
863    #[rstest]
864    fn test_strike_range_resolve_atm_relative_exact_high_value() {
865        let range = StrikeRange::AtmRelative {
866            strikes_above: 0,
867            strikes_below: 0,
868        };
869        let atm = Price::from("9007199253.999000000");
870        let collapsed = Price::from("9007199253.999000001");
871        let strikes = [atm, collapsed];
872        assert_eq!(collapsed.as_f64(), atm.as_f64());
873
874        let result = range.resolve(Some(atm), &strikes);
875
876        assert_eq!(result, vec![atm]);
877    }
878
879    #[rstest]
880    fn test_strike_range_resolve_atm_relative_saturates_extreme_window() {
881        // An extreme window must clamp to the available strikes without overflowing
882        let range = StrikeRange::AtmRelative {
883            strikes_above: usize::MAX,
884            strikes_below: usize::MAX,
885        };
886        let strikes: Vec<Price> = [45000, 50000, 55000]
887            .iter()
888            .map(|s| Price::from(&s.to_string()))
889            .collect();
890        let atm = Some(Price::from("50000"));
891
892        let result = range.resolve(atm, &strikes);
893
894        assert_eq!(result, strikes);
895    }
896
897    #[rstest]
898    fn test_strike_range_resolve_atm_relative_no_atm() {
899        let range = StrikeRange::AtmRelative {
900            strikes_above: 2,
901            strikes_below: 2,
902        };
903        let strikes = vec![Price::from("50000"), Price::from("55000")];
904        let result = range.resolve(None, &strikes);
905        // No ATM → return empty (deferred until ATM known)
906        assert!(result.is_empty());
907    }
908
909    #[rstest]
910    fn test_strike_range_resolve_atm_percent() {
911        let range = StrikeRange::AtmPercent { pct: 0.1 }; // 10%
912        let strikes: Vec<Price> = [45000, 48000, 50000, 52000, 55000, 60000]
913            .iter()
914            .map(|s| Price::from(&s.to_string()))
915            .collect();
916        let atm = Some(Price::from("50000"));
917        let result = range.resolve(atm, &strikes);
918        // 10% of 50000 = 5000, so [45000..55000] inclusive (<=)
919        assert_eq!(result.len(), 5); // 45000, 48000, 50000, 52000, 55000
920        assert!(result.contains(&Price::from("45000")));
921        assert!(result.contains(&Price::from("48000")));
922        assert!(result.contains(&Price::from("50000")));
923        assert!(result.contains(&Price::from("52000")));
924        assert!(result.contains(&Price::from("55000")));
925    }
926
927    #[rstest]
928    fn test_strike_range_resolve_atm_percent_zero_exact_high_value() {
929        let range = StrikeRange::AtmPercent { pct: 0.0 };
930        let atm = Price::from("9007199253.999000000");
931        let collapsed = Price::from("9007199253.999000001");
932        let strikes = [atm, collapsed];
933        assert_eq!(atm.as_f64(), collapsed.as_f64());
934
935        let result = range.resolve(Some(atm), &strikes);
936
937        assert_eq!(result, vec![atm]);
938    }
939
940    #[rstest]
941    fn test_option_chain_slice_new_empty() {
942        let slice = OptionChainSlice::new(make_series_id());
943        assert!(slice.is_empty());
944        assert_eq!(slice.call_count(), 0);
945        assert_eq!(slice.put_count(), 0);
946        assert!(slice.atm_strike.is_none());
947    }
948
949    #[rstest]
950    fn test_strike_range_resolve_delta_falls_back_to_atm_relative() {
951        // The model-level resolve has no Greeks, so Delta delegates to an
952        // AtmRelative window of DEFAULT_DELTA_FALLBACK_STRIKES either side of ATM.
953        let strikes: Vec<Price> = (0..=20)
954            .map(|i| Price::from(&(40000 + i * 1000).to_string()))
955            .collect();
956        let atm = Some(Price::from("50000")); // index 10
957        let delta = StrikeRange::Delta {
958            target: 0.25,
959            tolerance: 0.05,
960        };
961        let expected = StrikeRange::AtmRelative {
962            strikes_above: DEFAULT_DELTA_FALLBACK_STRIKES,
963            strikes_below: DEFAULT_DELTA_FALLBACK_STRIKES,
964        }
965        .resolve(atm, &strikes);
966
967        let result = delta.resolve(atm, &strikes);
968        assert_eq!(result, expected);
969        assert_eq!(result.len(), 2 * DEFAULT_DELTA_FALLBACK_STRIKES + 1);
970        assert!(result.contains(&Price::from("50000")));
971        assert!(!result.contains(&Price::from("40000")));
972        assert!(!result.contains(&Price::from("60000")));
973    }
974
975    #[rstest]
976    fn test_strike_range_resolve_delta_empty_without_atm() {
977        let delta = StrikeRange::Delta {
978            target: 0.25,
979            tolerance: 0.05,
980        };
981        let strikes = vec![Price::from("50000"), Price::from("55000")];
982        // No ATM -> deferred (empty), matching ATM-relative behavior.
983        assert!(delta.resolve(None, &strikes).is_empty());
984    }
985
986    #[rstest]
987    fn test_strike_search_profile_roundtrip() {
988        let profile = StrikeSearchProfile::new(
989            vec![Decimal::from(5), Decimal::from(25)],
990            Decimal::from(2),
991            7,
992        )
993        .unwrap();
994        let encoded = serde_json::to_value(&profile).unwrap();
995        let restored: StrikeSearchProfile = serde_json::from_value(encoded.clone()).unwrap();
996        assert_eq!(restored, profile);
997        assert_eq!(profile.increments(), &[Decimal::from(5), Decimal::from(25)]);
998        assert_eq!(profile.origin(), Decimal::from(2));
999        assert_eq!(profile.max_candidates_per_slot(), 7);
1000        assert_eq!(encoded["max_candidates_per_slot"], serde_json::json!(7));
1001    }
1002
1003    #[rstest]
1004    #[case(vec![], Decimal::ZERO, 7, "at least one increment")]
1005    #[case(vec![Decimal::ZERO], Decimal::ZERO, 7, "increments must be positive")]
1006    #[case(vec![Decimal::from(-1)], Decimal::ZERO, 7, "increments must be positive")]
1007    #[case(vec![Decimal::from(5), Decimal::new(50, 1)], Decimal::ZERO, 7, "increments must be unique")]
1008    #[case(vec![Decimal::from(5)], Decimal::from(-1), 7, "origin must be non-negative")]
1009    #[case(vec![Decimal::from(5)], Decimal::ZERO, 0, "positive candidate bound")]
1010    fn test_strike_search_profile_invalid(
1011        #[case] increments: Vec<Decimal>,
1012        #[case] origin: Decimal,
1013        #[case] candidates: usize,
1014        #[case] expected: &str,
1015    ) {
1016        let encoded = serde_json::json!({"increments": increments, "origin": origin, "max_candidates_per_slot": candidates});
1017        let error = StrikeSearchProfile::new(increments, origin, candidates).unwrap_err();
1018        let decoded_error = serde_json::from_value::<StrikeSearchProfile>(encoded).unwrap_err();
1019        assert!(error.to_string().contains(expected));
1020        assert!(decoded_error.to_string().contains(expected));
1021    }
1022}