1use 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
43pub(crate) const DEFAULT_DELTA_FALLBACK_STRIKES: usize = 5;
46
47#[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 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 #[must_use]
104 pub fn increments(&self) -> &[Decimal] {
105 &self.increments
106 }
107
108 #[must_use]
110 pub const fn origin(&self) -> Decimal {
111 self.origin
112 }
113
114 #[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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
167#[non_exhaustive]
168pub enum StrikeRange {
169 Fixed(Vec<Price>),
171 AtmRelative {
173 strikes_above: usize,
174 strikes_below: usize,
175 },
176 AtmPercent { pct: f64 },
178 Delta { target: f64, tolerance: f64 },
185}
186
187impl StrikeRange {
188 pub fn atm_percent(pct: f64) -> CorrectnessResult<Self> {
194 check_non_negative_f64(pct, "pct")?;
195 Ok(Self::AtmPercent { pct })
196 }
197
198 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 #[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![]; };
249 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 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![]; };
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#[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 pub instrument_id: InstrumentId,
318 pub convention: GreeksConvention,
320 pub greeks: OptionGreekValues,
322 pub mark_iv: Option<f64>,
324 pub bid_iv: Option<f64>,
326 pub ask_iv: Option<f64>,
328 pub underlying_price: Option<f64>,
330 pub open_interest: Option<f64>,
332 pub ts_event: UnixNanos,
334 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#[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 pub quote: QuoteTick,
405 pub greeks: Option<OptionGreeks>,
407}
408
409#[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 pub series_id: OptionSeriesId,
422 pub atm_strike: Option<Price>,
424 pub calls: BTreeMap<Price, OptionStrikeData>,
426 pub puts: BTreeMap<Price, OptionStrikeData>,
428 pub ts_event: UnixNanos,
430 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 #[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 #[must_use]
469 pub fn call_count(&self) -> usize {
470 self.calls.len()
471 }
472
473 #[must_use]
475 pub fn put_count(&self) -> usize {
476 self.puts.len()
477 }
478
479 #[must_use]
481 pub fn get_call(&self, strike: &Price) -> Option<&OptionStrikeData> {
482 self.calls.get(strike)
483 }
484
485 #[must_use]
487 pub fn get_put(&self, strike: &Price) -> Option<&OptionStrikeData> {
488 self.puts.get(strike)
489 }
490
491 #[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 #[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 #[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 #[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 #[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 #[must_use]
526 pub fn strike_count(&self) -> usize {
527 self.strikes().len()
528 }
529
530 #[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 #[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 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 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 assert!(result.is_empty());
907 }
908
909 #[rstest]
910 fn test_strike_range_resolve_atm_percent() {
911 let range = StrikeRange::AtmPercent { pct: 0.1 }; 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 assert_eq!(result.len(), 5); 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 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")); 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 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}