1use std::hash::{Hash, Hasher};
17
18use nautilus_core::{
19 Params, UnixNanos,
20 correctness::{CorrectnessResult, check_equal_u8},
21};
22use rust_decimal::Decimal;
23use serde::{Deserialize, Serialize};
24use ustr::Ustr;
25
26use super::{Instrument, any::InstrumentAny, tick_scheme::check_tick_scheme};
27use crate::{
28 enums::{AssetClass, ExerciseStyle, InstrumentClass, OptionKind, SettlementType},
29 identifiers::{InstrumentId, Symbol},
30 types::{
31 currency::Currency,
32 money::Money,
33 price::{Price, check_positive_price},
34 quantity::{Quantity, check_positive_quantity},
35 },
36};
37
38#[repr(C)]
40#[derive(Clone, Debug, Serialize, Deserialize)]
41#[cfg_attr(
42 feature = "python",
43 pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
44)]
45#[cfg_attr(
46 feature = "python",
47 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
48)]
49pub struct CryptoOption {
50 pub id: InstrumentId,
52 pub raw_symbol: Symbol,
54 pub underlying: Currency,
56 pub quote_currency: Currency,
58 pub settlement_currency: Currency,
60 pub is_inverse: bool,
62 pub option_kind: OptionKind,
64 pub strike_price: Price,
66 pub activation_ns: UnixNanos,
68 pub expiration_ns: UnixNanos,
70 pub price_precision: u8,
72 pub size_precision: u8,
74 pub price_increment: Price,
76 pub size_increment: Quantity,
78 pub multiplier: Quantity,
80 pub lot_size: Quantity,
82 pub margin_init: Decimal,
84 pub margin_maint: Decimal,
86 pub max_quantity: Option<Quantity>,
88 pub min_quantity: Option<Quantity>,
90 pub max_notional: Option<Money>,
92 pub min_notional: Option<Money>,
94 pub max_price: Option<Price>,
96 pub min_price: Option<Price>,
98 pub tick_scheme: Option<Ustr>,
100 pub info: Option<Params>,
102 pub ts_event: UnixNanos,
104 pub ts_init: UnixNanos,
106 #[serde(default)]
108 pub underlying_instrument_id: Option<InstrumentId>,
109 #[serde(default)]
111 pub exercise_style: Option<ExerciseStyle>,
112 #[serde(default)]
114 pub settlement_type: Option<SettlementType>,
115}
116
117#[bon::bon]
118impl CryptoOption {
119 #[expect(clippy::too_many_arguments)]
120 fn new_checked(
121 instrument_id: InstrumentId,
122 raw_symbol: Symbol,
123 underlying: Currency,
124 quote_currency: Currency,
125 settlement_currency: Currency,
126 is_inverse: bool,
127 option_kind: OptionKind,
128 strike_price: Price,
129 activation_ns: UnixNanos,
130 expiration_ns: UnixNanos,
131 price_precision: u8,
132 size_precision: u8,
133 price_increment: Price,
134 size_increment: Quantity,
135 multiplier: Option<Quantity>,
136 lot_size: Option<Quantity>,
137 max_quantity: Option<Quantity>,
138 min_quantity: Option<Quantity>,
139 max_notional: Option<Money>,
140 min_notional: Option<Money>,
141 max_price: Option<Price>,
142 min_price: Option<Price>,
143 margin_init: Option<Decimal>,
144 margin_maint: Option<Decimal>,
145 tick_scheme: Option<Ustr>,
146 info: Option<Params>,
147 ts_event: UnixNanos,
148 ts_init: UnixNanos,
149 underlying_instrument_id: Option<InstrumentId>,
150 exercise_style: Option<ExerciseStyle>,
151 settlement_type: Option<SettlementType>,
152 ) -> CorrectnessResult<Self> {
153 check_equal_u8(
154 price_precision,
155 price_increment.precision,
156 stringify!(price_precision),
157 stringify!(price_increment.precision),
158 )?;
159 check_equal_u8(
160 size_precision,
161 size_increment.precision,
162 stringify!(size_precision),
163 stringify!(size_increment.precision),
164 )?;
165 check_positive_price(price_increment, stringify!(price_increment))?;
166 check_positive_price(strike_price, stringify!(strike_price))?;
167 check_positive_quantity(size_increment, stringify!(size_increment))?;
168 check_tick_scheme(tick_scheme)?;
169
170 if let Some(multiplier) = multiplier {
171 check_positive_quantity(multiplier, stringify!(multiplier))?;
172 }
173
174 if let Some(lot_size) = lot_size {
175 check_positive_quantity(lot_size, stringify!(lot_size))?;
176 }
177
178 Ok(Self {
179 id: instrument_id,
180 raw_symbol,
181 underlying,
182 quote_currency,
183 settlement_currency,
184 is_inverse,
185 option_kind,
186 strike_price,
187 activation_ns,
188 expiration_ns,
189 price_precision,
190 size_precision,
191 price_increment,
192 size_increment,
193 multiplier: multiplier.unwrap_or(Quantity::from(1)),
194 lot_size: lot_size.unwrap_or(Quantity::from(1)),
195 margin_init: margin_init.unwrap_or_default(),
196 margin_maint: margin_maint.unwrap_or_default(),
197 max_notional,
198 min_notional,
199 max_quantity,
200 min_quantity,
201 max_price,
202 min_price,
203 tick_scheme,
204 info,
205 ts_event,
206 ts_init,
207 underlying_instrument_id,
208 exercise_style,
209 settlement_type,
210 })
211 }
212
213 #[builder(start_fn = builder, finish_fn = build)]
222 pub fn build_checked(
223 instrument_id: InstrumentId,
224 raw_symbol: Symbol,
225 underlying: Currency,
226 quote_currency: Currency,
227 settlement_currency: Currency,
228 is_inverse: bool,
229 option_kind: OptionKind,
230 strike_price: Price,
231 activation_ns: UnixNanos,
232 expiration_ns: UnixNanos,
233 price_precision: u8,
234 size_precision: u8,
235 price_increment: Price,
236 size_increment: Quantity,
237 multiplier: Option<Quantity>,
238 lot_size: Option<Quantity>,
239 max_quantity: Option<Quantity>,
240 min_quantity: Option<Quantity>,
241 max_notional: Option<Money>,
242 min_notional: Option<Money>,
243 max_price: Option<Price>,
244 min_price: Option<Price>,
245 margin_init: Option<Decimal>,
246 margin_maint: Option<Decimal>,
247 tick_scheme: Option<Ustr>,
248 info: Option<Params>,
249 ts_event: UnixNanos,
250 ts_init: UnixNanos,
251 underlying_instrument_id: Option<InstrumentId>,
252 exercise_style: Option<ExerciseStyle>,
253 settlement_type: Option<SettlementType>,
254 ) -> CorrectnessResult<Self> {
255 Self::new_checked(
256 instrument_id,
257 raw_symbol,
258 underlying,
259 quote_currency,
260 settlement_currency,
261 is_inverse,
262 option_kind,
263 strike_price,
264 activation_ns,
265 expiration_ns,
266 price_precision,
267 size_precision,
268 price_increment,
269 size_increment,
270 multiplier,
271 lot_size,
272 max_quantity,
273 min_quantity,
274 max_notional,
275 min_notional,
276 max_price,
277 min_price,
278 margin_init,
279 margin_maint,
280 tick_scheme,
281 info,
282 ts_event,
283 ts_init,
284 underlying_instrument_id,
285 exercise_style,
286 settlement_type,
287 )
288 }
289}
290
291impl PartialEq<Self> for CryptoOption {
292 fn eq(&self, other: &Self) -> bool {
293 self.id == other.id
294 }
295}
296
297impl Eq for CryptoOption {}
298
299impl Hash for CryptoOption {
300 fn hash<H: Hasher>(&self, state: &mut H) {
301 self.id.hash(state);
302 }
303}
304
305impl Instrument for CryptoOption {
306 fn into_any(self) -> InstrumentAny {
307 InstrumentAny::CryptoOption(self)
308 }
309
310 fn id(&self) -> InstrumentId {
311 self.id
312 }
313
314 fn raw_symbol(&self) -> Symbol {
315 self.raw_symbol
316 }
317
318 fn asset_class(&self) -> AssetClass {
319 AssetClass::Cryptocurrency
320 }
321
322 fn instrument_class(&self) -> InstrumentClass {
323 InstrumentClass::Option
324 }
325
326 fn underlying(&self) -> Option<Ustr> {
327 Some(self.underlying.code)
328 }
329
330 fn base_currency(&self) -> Option<Currency> {
331 Some(self.underlying)
332 }
333
334 fn quote_currency(&self) -> Currency {
335 self.quote_currency
336 }
337
338 fn settlement_currency(&self) -> Currency {
339 self.settlement_currency
340 }
341
342 fn is_inverse(&self) -> bool {
343 self.is_inverse
344 }
345
346 fn isin(&self) -> Option<Ustr> {
347 None }
349
350 fn option_kind(&self) -> Option<OptionKind> {
351 Some(self.option_kind)
352 }
353
354 fn strike_price(&self) -> Option<Price> {
355 Some(self.strike_price)
356 }
357
358 fn activation_ns(&self) -> Option<UnixNanos> {
359 Some(self.activation_ns)
360 }
361
362 fn expiration_ns(&self) -> Option<UnixNanos> {
363 Some(self.expiration_ns)
364 }
365
366 fn exchange(&self) -> Option<Ustr> {
367 None }
369
370 fn price_precision(&self) -> u8 {
371 self.price_precision
372 }
373
374 fn size_precision(&self) -> u8 {
375 self.size_precision
376 }
377
378 fn price_increment(&self) -> Price {
379 self.price_increment
380 }
381
382 fn size_increment(&self) -> Quantity {
383 self.size_increment
384 }
385
386 fn multiplier(&self) -> Quantity {
387 self.multiplier
388 }
389
390 fn lot_size(&self) -> Option<Quantity> {
391 Some(self.lot_size)
392 }
393
394 fn max_quantity(&self) -> Option<Quantity> {
395 self.max_quantity
396 }
397
398 fn min_quantity(&self) -> Option<Quantity> {
399 self.min_quantity
400 }
401
402 fn max_notional(&self) -> Option<Money> {
403 self.max_notional
404 }
405
406 fn min_notional(&self) -> Option<Money> {
407 self.min_notional
408 }
409
410 fn max_price(&self) -> Option<Price> {
411 self.max_price
412 }
413
414 fn min_price(&self) -> Option<Price> {
415 self.min_price
416 }
417
418 fn tick_scheme(&self) -> Option<Ustr> {
419 self.tick_scheme
420 }
421
422 fn info(&self) -> Option<&Params> {
423 self.info.as_ref()
424 }
425
426 fn ts_event(&self) -> UnixNanos {
427 self.ts_event
428 }
429
430 fn ts_init(&self) -> UnixNanos {
431 self.ts_init
432 }
433
434 fn margin_init(&self) -> Decimal {
435 self.margin_init
436 }
437
438 fn margin_maint(&self) -> Decimal {
439 self.margin_maint
440 }
441}
442
443#[cfg(test)]
444mod tests {
445 use rstest::rstest;
446 use rust_decimal_macros::dec;
447
448 use crate::{
449 enums::{AssetClass, ExerciseStyle, InstrumentClass, OptionKind, SettlementType},
450 identifiers::{InstrumentId, Symbol},
451 instruments::{CryptoOption, Instrument, stubs::*},
452 types::{Currency, Money, Price, Quantity},
453 };
454
455 #[rstest]
456 fn test_trait_accessors(crypto_option_btc_deribit: CryptoOption) {
457 assert_eq!(
458 crypto_option_btc_deribit.id(),
459 InstrumentId::from("BTC-13JAN23-16000-P.DERIBIT"),
460 );
461 assert_eq!(
462 crypto_option_btc_deribit.asset_class(),
463 AssetClass::Cryptocurrency
464 );
465 assert_eq!(
466 crypto_option_btc_deribit.instrument_class(),
467 InstrumentClass::Option
468 );
469 assert_eq!(
470 crypto_option_btc_deribit.option_kind(),
471 Some(OptionKind::Put)
472 );
473 assert_eq!(
474 crypto_option_btc_deribit.strike_price(),
475 Some(Price::from("16000.000"))
476 );
477 assert!(!crypto_option_btc_deribit.is_inverse());
478 assert_eq!(crypto_option_btc_deribit.price_precision(), 3);
479 assert_eq!(crypto_option_btc_deribit.size_precision(), 1);
480 assert_eq!(
481 crypto_option_btc_deribit.min_quantity(),
482 Some(Quantity::from("0.1"))
483 );
484 assert!(crypto_option_btc_deribit.activation_ns().is_some());
485 assert!(crypto_option_btc_deribit.expiration_ns().is_some());
486 }
487
488 #[rstest]
489 #[case::unspecified(None)]
490 #[case::fractional(Some(Quantity::from("0.01")))]
491 #[case::whole(Some(Quantity::from("2")))]
492 fn test_builder_preserves_minimum_quantity(#[case] min_quantity: Option<Quantity>) {
493 let instrument = CryptoOption::builder()
494 .instrument_id(InstrumentId::from("BTC-13JAN23-16000-P.DERIBIT"))
495 .raw_symbol(Symbol::from("BTC-13JAN23-16000-P"))
496 .underlying(Currency::BTC())
497 .quote_currency(Currency::USD())
498 .settlement_currency(Currency::BTC())
499 .is_inverse(false)
500 .option_kind(OptionKind::Put)
501 .strike_price(Price::from("16000"))
502 .activation_ns(1.into())
503 .expiration_ns(2.into())
504 .price_precision(1)
505 .size_precision(2)
506 .price_increment(Price::from("0.1"))
507 .size_increment(Quantity::from("0.01"))
508 .maybe_min_quantity(min_quantity)
509 .ts_event(3.into())
510 .ts_init(4.into())
511 .build()
512 .unwrap();
513
514 assert_eq!(instrument.min_quantity(), min_quantity);
515 }
516
517 #[rstest]
518 fn test_new_checked_price_precision_mismatch() {
519 let result = CryptoOption::new_checked(
520 InstrumentId::from("TEST.DERIBIT"),
521 Symbol::from("TEST"),
522 Currency::BTC(),
523 Currency::USD(),
524 Currency::BTC(),
525 false,
526 OptionKind::Call,
527 Price::from("50000.0"),
528 0.into(),
529 0.into(),
530 4, 1,
532 Price::from("0.001"),
533 Quantity::from("0.1"),
534 None,
535 None,
536 None,
537 None,
538 None,
539 None,
540 None,
541 None,
542 None,
543 None,
544 None,
545 None,
546 0.into(),
547 0.into(),
548 None,
549 None,
550 None,
551 );
552 assert!(result.is_err());
553 }
554
555 #[rstest]
556 fn test_new_checked_rejects_non_positive_lot_size() {
557 let result = CryptoOption::new_checked(
558 InstrumentId::from("TEST.DERIBIT"),
559 Symbol::from("TEST"),
560 Currency::BTC(),
561 Currency::USD(),
562 Currency::BTC(),
563 false,
564 OptionKind::Call,
565 Price::from("50000.0"),
566 0.into(),
567 0.into(),
568 1,
569 1,
570 Price::from("0.1"),
571 Quantity::from("0.1"),
572 None,
573 Some(Quantity::from("0")),
574 None,
575 None,
576 None,
577 None,
578 None,
579 None,
580 None,
581 None,
582 None,
583 None,
584 0.into(),
585 0.into(),
586 None,
587 None,
588 None,
589 );
590 assert!(result.is_err());
591 }
592
593 #[rstest]
594 #[case(Price::from("0"))]
595 #[case(Price::from("-1"))]
596 fn test_new_checked_rejects_non_positive_strike_price(#[case] strike_price: Price) {
597 let result = CryptoOption::new_checked(
598 InstrumentId::from("TEST.DERIBIT"),
599 Symbol::from("TEST"),
600 Currency::BTC(),
601 Currency::USD(),
602 Currency::BTC(),
603 false,
604 OptionKind::Call,
605 strike_price,
606 0.into(),
607 0.into(),
608 1,
609 1,
610 Price::from("0.1"),
611 Quantity::from("0.1"),
612 None,
613 None,
614 None,
615 None,
616 None,
617 None,
618 None,
619 None,
620 None,
621 None,
622 None,
623 None,
624 0.into(),
625 0.into(),
626 None,
627 None,
628 None,
629 );
630
631 assert!(
634 result
635 .unwrap_err()
636 .to_string()
637 .contains("'strike_price' not positive")
638 );
639 }
640
641 #[rstest]
642 fn test_serialization_roundtrip(crypto_option_btc_deribit: CryptoOption) {
643 let json = serde_json::to_string(&crypto_option_btc_deribit).unwrap();
644 let deserialized: CryptoOption = serde_json::from_str(&json).unwrap();
645 assert_eq!(json, serde_json::to_string(&deserialized).unwrap());
646 }
647
648 #[rstest]
649 fn test_builder_matches_new_checked() {
650 let positional = CryptoOption::new_checked(
651 InstrumentId::from("BTC-13JAN23-16000-P.DERIBIT"),
652 Symbol::from("BTC-13JAN23-16000-P"),
653 Currency::BTC(),
654 Currency::USDC(),
655 Currency::USDT(),
656 false,
657 OptionKind::Put,
658 Price::from("16000.000"),
659 1.into(),
660 2.into(),
661 3,
662 1,
663 Price::from("0.001"),
664 Quantity::from("0.1"),
665 Some(Quantity::from("10")),
666 Some(Quantity::from("5")),
667 Some(Quantity::from("1000.0")),
668 Some(Quantity::from("0.1")),
669 Some(Money::new(1_000_000.0, Currency::USDC())),
670 Some(Money::new(10.0, Currency::USDC())),
671 Some(Price::from("99999.999")),
672 Some(Price::from("0.001")),
673 Some(dec!(0.01)),
674 Some(dec!(0.02)),
675 None,
676 None,
677 1.into(),
678 2.into(),
679 Some(InstrumentId::from("BTCUSDT.BINANCE")),
680 Some(ExerciseStyle::European),
681 Some(SettlementType::Cash),
682 )
683 .unwrap();
684
685 let built = CryptoOption::builder()
686 .instrument_id(InstrumentId::from("BTC-13JAN23-16000-P.DERIBIT"))
687 .raw_symbol(Symbol::from("BTC-13JAN23-16000-P"))
688 .underlying(Currency::BTC())
689 .quote_currency(Currency::USDC())
690 .settlement_currency(Currency::USDT())
691 .is_inverse(false)
692 .option_kind(OptionKind::Put)
693 .strike_price(Price::from("16000.000"))
694 .activation_ns(1.into())
695 .expiration_ns(2.into())
696 .price_precision(3)
697 .size_precision(1)
698 .price_increment(Price::from("0.001"))
699 .size_increment(Quantity::from("0.1"))
700 .multiplier(Quantity::from("10"))
701 .lot_size(Quantity::from("5"))
702 .max_quantity(Quantity::from("1000.0"))
703 .min_quantity(Quantity::from("0.1"))
704 .max_notional(Money::new(1_000_000.0, Currency::USDC()))
705 .min_notional(Money::new(10.0, Currency::USDC()))
706 .max_price(Price::from("99999.999"))
707 .min_price(Price::from("0.001"))
708 .margin_init(dec!(0.01))
709 .margin_maint(dec!(0.02))
710 .ts_event(1.into())
711 .ts_init(2.into())
712 .underlying_instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
713 .exercise_style(ExerciseStyle::European)
714 .settlement_type(SettlementType::Cash)
715 .build()
716 .unwrap();
717
718 assert_eq!(
719 built.underlying_instrument_id,
720 Some(InstrumentId::from("BTCUSDT.BINANCE"))
721 );
722 assert_eq!(built.exercise_style, Some(ExerciseStyle::European));
723 assert_eq!(built.settlement_type, Some(SettlementType::Cash));
724 assert_eq!(
725 serde_json::to_value(&positional).unwrap(),
726 serde_json::to_value(&built).unwrap(),
727 );
728 }
729
730 #[rstest]
731 #[case(OptionKind::Call, ExerciseStyle::American, SettlementType::Cash)]
732 #[case(OptionKind::Put, ExerciseStyle::European, SettlementType::Physical)]
733 #[case(OptionKind::Call, ExerciseStyle::European, SettlementType::Physical)]
734 #[case(OptionKind::Put, ExerciseStyle::Bermudan, SettlementType::Cash)]
735 fn test_explicit_option_terms_round_trip(
736 #[from(crypto_option_btc_deribit)] mut option: CryptoOption,
737 #[case] kind: OptionKind,
738 #[case] style: ExerciseStyle,
739 #[case] settlement: SettlementType,
740 ) {
741 let legacy = option.clone();
742 let underlying_id = InstrumentId::from("BTCUSDT.BINANCE");
743 option.option_kind = kind;
744 option.underlying_instrument_id = Some(underlying_id);
745 option.exercise_style = Some(style);
746 option.settlement_type = Some(settlement);
747 let mut encoded = serde_json::to_value(&option).unwrap();
748 let restored: CryptoOption = serde_json::from_value(encoded.clone()).unwrap();
749 let mut old = encoded.clone();
750 old.as_object_mut()
751 .unwrap()
752 .remove("underlying_instrument_id");
753 old.as_object_mut().unwrap().remove("exercise_style");
754 old.as_object_mut().unwrap().remove("settlement_type");
755 let restored_legacy: CryptoOption = serde_json::from_value(old).unwrap();
756
757 assert_eq!(serde_json::to_value(&restored).unwrap(), encoded);
758 encoded["underlying_instrument_id"] = serde_json::Value::Null;
759 encoded["exercise_style"] = serde_json::Value::Null;
760 encoded["settlement_type"] = serde_json::Value::Null;
761 assert_eq!(serde_json::to_value(&restored_legacy).unwrap(), encoded);
762 assert_eq!(option, legacy);
763 }
764}