Skip to main content

nautilus_model/instruments/
option_contract.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
16use std::hash::{Hash, Hasher};
17
18use nautilus_core::{
19    Params, UnixNanos,
20    correctness::{
21        CorrectnessResult, check_equal_u8, check_valid_string_ascii,
22        check_valid_string_ascii_optional,
23    },
24};
25use rust_decimal::Decimal;
26use serde::{Deserialize, Serialize};
27use ustr::Ustr;
28
29use super::{Instrument, any::InstrumentAny, tick_scheme::check_tick_scheme};
30use crate::{
31    enums::{AssetClass, ExerciseStyle, InstrumentClass, OptionKind, SettlementType},
32    identifiers::{InstrumentId, Symbol},
33    types::{
34        currency::Currency,
35        money::Money,
36        price::{Price, check_positive_price},
37        quantity::{Quantity, check_positive_quantity},
38    },
39};
40
41/// Represents a generic option contract instrument.
42#[repr(C)]
43#[derive(Clone, Debug, Serialize, Deserialize)]
44#[cfg_attr(
45    feature = "python",
46    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
47)]
48#[cfg_attr(
49    feature = "python",
50    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
51)]
52pub struct OptionContract {
53    /// The instrument ID.
54    pub id: InstrumentId,
55    /// The raw/local/native symbol for the instrument, assigned by the venue.
56    pub raw_symbol: Symbol,
57    /// The option contract asset class.
58    pub asset_class: AssetClass,
59    /// The exchange ISO 10383 Market Identifier Code (MIC) where the instrument trades.
60    pub exchange: Option<Ustr>,
61    /// The underlying asset.
62    pub underlying: Ustr,
63    /// The kind of option (PUT | CALL).
64    pub option_kind: OptionKind,
65    /// The option strike price.
66    pub strike_price: Price,
67    /// UNIX timestamp (nanoseconds) for contract activation.
68    pub activation_ns: UnixNanos,
69    /// UNIX timestamp (nanoseconds) for contract expiration.
70    pub expiration_ns: UnixNanos,
71    /// The option contract currency.
72    pub currency: Currency,
73    /// The price decimal precision.
74    pub price_precision: u8,
75    /// The minimum price increment (tick size).
76    pub price_increment: Price,
77    /// The minimum size increment.
78    pub size_increment: Quantity,
79    /// The trading size decimal precision.
80    pub size_precision: u8,
81    /// The option multiplier.
82    pub multiplier: Quantity,
83    /// The rounded lot unit size (standard/board).
84    pub lot_size: Quantity,
85    /// The initial (order) margin requirement in percentage of order value.
86    pub margin_init: Decimal,
87    /// The maintenance (position) margin in percentage of position value.
88    pub margin_maint: Decimal,
89    /// The maximum allowable order quantity.
90    pub max_quantity: Option<Quantity>,
91    /// The minimum allowable order quantity.
92    pub min_quantity: Option<Quantity>,
93    /// The maximum allowable quoted price.
94    pub max_price: Option<Price>,
95    /// The minimum allowable quoted price.
96    pub min_price: Option<Price>,
97    /// The registered variable tick scheme name.
98    pub tick_scheme: Option<Ustr>,
99    /// Additional instrument metadata as a JSON-serializable dictionary.
100    pub info: Option<Params>,
101    /// UNIX timestamp (nanoseconds) when the data event occurred.
102    pub ts_event: UnixNanos,
103    /// UNIX timestamp (nanoseconds) when the data object was initialized.
104    pub ts_init: UnixNanos,
105    /// The actual underlying instrument, which may trade on another venue; absent when unknown.
106    #[serde(default)]
107    pub underlying_instrument_id: Option<InstrumentId>,
108    /// The exercise style; absent when unknown.
109    #[serde(default)]
110    pub exercise_style: Option<ExerciseStyle>,
111    /// The contractual settlement type; absent when unknown or not represented by a single type.
112    #[serde(default)]
113    pub settlement_type: Option<SettlementType>,
114}
115
116#[bon::bon]
117impl OptionContract {
118    #[expect(clippy::too_many_arguments)]
119    fn new_checked(
120        instrument_id: InstrumentId,
121        raw_symbol: Symbol,
122        asset_class: AssetClass,
123        exchange: Option<Ustr>,
124        underlying: Ustr,
125        option_kind: OptionKind,
126        strike_price: Price,
127        currency: Currency,
128        activation_ns: UnixNanos,
129        expiration_ns: UnixNanos,
130        price_precision: u8,
131        price_increment: Price,
132        multiplier: Quantity,
133        lot_size: Quantity,
134        max_quantity: Option<Quantity>,
135        min_quantity: Option<Quantity>,
136        max_price: Option<Price>,
137        min_price: Option<Price>,
138        margin_init: Option<Decimal>,
139        margin_maint: Option<Decimal>,
140        tick_scheme: Option<Ustr>,
141        info: Option<Params>,
142        ts_event: UnixNanos,
143        ts_init: UnixNanos,
144        underlying_instrument_id: Option<InstrumentId>,
145        exercise_style: Option<ExerciseStyle>,
146        settlement_type: Option<SettlementType>,
147    ) -> CorrectnessResult<Self> {
148        check_valid_string_ascii_optional(exchange, stringify!(exchange))?;
149        check_valid_string_ascii(underlying, stringify!(underlying))?;
150        check_equal_u8(
151            price_precision,
152            price_increment.precision,
153            stringify!(price_precision),
154            stringify!(price_increment.precision),
155        )?;
156        check_positive_price(price_increment, stringify!(price_increment))?;
157        check_positive_price(strike_price, stringify!(strike_price))?;
158        check_tick_scheme(tick_scheme)?;
159        check_positive_quantity(multiplier, stringify!(multiplier))?;
160        check_positive_quantity(lot_size, stringify!(lot_size))?;
161
162        Ok(Self {
163            id: instrument_id,
164            raw_symbol,
165            asset_class,
166            exchange,
167            underlying,
168            option_kind,
169            activation_ns,
170            expiration_ns,
171            strike_price,
172            currency,
173            price_precision,
174            price_increment,
175            size_precision: 0,
176            size_increment: Quantity::from(1),
177            multiplier,
178            lot_size,
179            margin_init: margin_init.unwrap_or_default(),
180            margin_maint: margin_maint.unwrap_or_default(),
181            tick_scheme,
182            info,
183            max_quantity,
184            min_quantity: Some(min_quantity.unwrap_or(1.into())),
185            max_price,
186            min_price,
187            ts_event,
188            ts_init,
189            underlying_instrument_id,
190            exercise_style,
191            settlement_type,
192        })
193    }
194
195    /// Returns a fluent builder for a [`OptionContract`] instance.
196    ///
197    /// Required fields are enforced at compile time; optional fields can be omitted and use the
198    /// same defaults as checked construction. The same correctness checks run on `build`.
199    ///
200    /// # Errors
201    ///
202    /// Returns an error if any input validation fails.
203    #[builder(start_fn = builder, finish_fn = build)]
204    pub fn build_checked(
205        instrument_id: InstrumentId,
206        raw_symbol: Symbol,
207        asset_class: AssetClass,
208        exchange: Option<Ustr>,
209        underlying: Ustr,
210        option_kind: OptionKind,
211        strike_price: Price,
212        currency: Currency,
213        activation_ns: UnixNanos,
214        expiration_ns: UnixNanos,
215        price_precision: u8,
216        price_increment: Price,
217        multiplier: Quantity,
218        lot_size: Quantity,
219        max_quantity: Option<Quantity>,
220        min_quantity: Option<Quantity>,
221        max_price: Option<Price>,
222        min_price: Option<Price>,
223        margin_init: Option<Decimal>,
224        margin_maint: Option<Decimal>,
225        tick_scheme: Option<Ustr>,
226        info: Option<Params>,
227        ts_event: UnixNanos,
228        ts_init: UnixNanos,
229        underlying_instrument_id: Option<InstrumentId>,
230        exercise_style: Option<ExerciseStyle>,
231        settlement_type: Option<SettlementType>,
232    ) -> CorrectnessResult<Self> {
233        Self::new_checked(
234            instrument_id,
235            raw_symbol,
236            asset_class,
237            exchange,
238            underlying,
239            option_kind,
240            strike_price,
241            currency,
242            activation_ns,
243            expiration_ns,
244            price_precision,
245            price_increment,
246            multiplier,
247            lot_size,
248            max_quantity,
249            min_quantity,
250            max_price,
251            min_price,
252            margin_init,
253            margin_maint,
254            tick_scheme,
255            info,
256            ts_event,
257            ts_init,
258            underlying_instrument_id,
259            exercise_style,
260            settlement_type,
261        )
262    }
263}
264
265impl PartialEq<Self> for OptionContract {
266    fn eq(&self, other: &Self) -> bool {
267        self.id == other.id
268    }
269}
270
271impl Eq for OptionContract {}
272
273impl Hash for OptionContract {
274    fn hash<H: Hasher>(&self, state: &mut H) {
275        self.id.hash(state);
276    }
277}
278
279impl Instrument for OptionContract {
280    fn into_any(self) -> InstrumentAny {
281        InstrumentAny::OptionContract(self)
282    }
283
284    fn id(&self) -> InstrumentId {
285        self.id
286    }
287
288    fn raw_symbol(&self) -> Symbol {
289        self.raw_symbol
290    }
291
292    fn asset_class(&self) -> AssetClass {
293        self.asset_class
294    }
295
296    fn instrument_class(&self) -> InstrumentClass {
297        InstrumentClass::Option
298    }
299    fn underlying(&self) -> Option<Ustr> {
300        Some(self.underlying)
301    }
302
303    fn base_currency(&self) -> Option<Currency> {
304        None
305    }
306
307    fn quote_currency(&self) -> Currency {
308        self.currency
309    }
310
311    fn settlement_currency(&self) -> Currency {
312        self.currency
313    }
314
315    fn isin(&self) -> Option<Ustr> {
316        None
317    }
318
319    fn option_kind(&self) -> Option<OptionKind> {
320        Some(self.option_kind)
321    }
322
323    fn exchange(&self) -> Option<Ustr> {
324        self.exchange
325    }
326
327    fn strike_price(&self) -> Option<Price> {
328        Some(self.strike_price)
329    }
330
331    fn activation_ns(&self) -> Option<UnixNanos> {
332        Some(self.activation_ns)
333    }
334
335    fn expiration_ns(&self) -> Option<UnixNanos> {
336        Some(self.expiration_ns)
337    }
338
339    fn is_inverse(&self) -> bool {
340        false
341    }
342
343    fn price_precision(&self) -> u8 {
344        self.price_precision
345    }
346
347    fn size_precision(&self) -> u8 {
348        0
349    }
350
351    fn price_increment(&self) -> Price {
352        self.price_increment
353    }
354
355    fn size_increment(&self) -> Quantity {
356        Quantity::from(1)
357    }
358
359    fn multiplier(&self) -> Quantity {
360        self.multiplier
361    }
362
363    fn lot_size(&self) -> Option<Quantity> {
364        Some(self.lot_size)
365    }
366
367    fn max_quantity(&self) -> Option<Quantity> {
368        self.max_quantity
369    }
370
371    fn min_quantity(&self) -> Option<Quantity> {
372        self.min_quantity
373    }
374
375    fn max_notional(&self) -> Option<Money> {
376        None
377    }
378
379    fn min_notional(&self) -> Option<Money> {
380        None
381    }
382
383    fn max_price(&self) -> Option<Price> {
384        self.max_price
385    }
386
387    fn min_price(&self) -> Option<Price> {
388        self.min_price
389    }
390
391    fn tick_scheme(&self) -> Option<Ustr> {
392        self.tick_scheme
393    }
394
395    fn info(&self) -> Option<&Params> {
396        self.info.as_ref()
397    }
398
399    fn ts_event(&self) -> UnixNanos {
400        self.ts_event
401    }
402
403    fn ts_init(&self) -> UnixNanos {
404        self.ts_init
405    }
406
407    fn margin_init(&self) -> Decimal {
408        self.margin_init
409    }
410
411    fn margin_maint(&self) -> Decimal {
412        self.margin_maint
413    }
414}
415
416#[cfg(test)]
417mod tests {
418    use rstest::rstest;
419    use rust_decimal_macros::dec;
420    use ustr::Ustr;
421
422    use crate::{
423        enums::{AssetClass, ExerciseStyle, InstrumentClass, OptionKind, SettlementType},
424        identifiers::{InstrumentId, Symbol},
425        instruments::{Instrument, OptionContract, stubs::*},
426        types::{Currency, Price, Quantity},
427    };
428
429    #[rstest]
430    fn test_trait_accessors(option_contract_appl: OptionContract) {
431        assert_eq!(
432            option_contract_appl.id(),
433            InstrumentId::from("AAPL211217C00150000.OPRA"),
434        );
435        assert_eq!(option_contract_appl.asset_class(), AssetClass::Equity);
436        assert_eq!(
437            option_contract_appl.instrument_class(),
438            InstrumentClass::Option
439        );
440        assert_eq!(option_contract_appl.quote_currency(), Currency::USD());
441        assert!(!option_contract_appl.is_inverse());
442        assert_eq!(option_contract_appl.option_kind(), Some(OptionKind::Call));
443        assert_eq!(
444            option_contract_appl.strike_price(),
445            Some(Price::from("149.0"))
446        );
447        assert_eq!(option_contract_appl.underlying(), Some(Ustr::from("AAPL")));
448        assert_eq!(option_contract_appl.exchange(), Some(Ustr::from("GMNI")));
449        assert!(option_contract_appl.activation_ns().is_some());
450        assert!(option_contract_appl.expiration_ns().is_some());
451        assert_eq!(option_contract_appl.size_precision(), 0);
452        assert_eq!(option_contract_appl.size_increment(), Quantity::from("1"));
453        assert_eq!(
454            option_contract_appl.min_quantity(),
455            Some(Quantity::from("1"))
456        );
457    }
458
459    #[rstest]
460    fn test_new_checked_price_precision_mismatch() {
461        let result = OptionContract::new_checked(
462            InstrumentId::from("TEST.OPRA"),
463            Symbol::from("TEST"),
464            AssetClass::Equity,
465            Some(Ustr::from("GMNI")),
466            Ustr::from("AAPL"),
467            OptionKind::Call,
468            Price::from("150.0"),
469            Currency::USD(),
470            0.into(),
471            0.into(),
472            4, // mismatch
473            Price::from("0.01"),
474            Quantity::from(1),
475            Quantity::from(1),
476            None,
477            None,
478            None,
479            None,
480            None,
481            None,
482            None,
483            None,
484            0.into(),
485            0.into(),
486            None,
487            None,
488            None,
489        );
490        assert!(result.is_err());
491    }
492
493    #[rstest]
494    fn test_new_checked_zero_multiplier() {
495        let result = OptionContract::new_checked(
496            InstrumentId::from("TEST.OPRA"),
497            Symbol::from("TEST"),
498            AssetClass::Equity,
499            Some(Ustr::from("GMNI")),
500            Ustr::from("AAPL"),
501            OptionKind::Call,
502            Price::from("150.0"),
503            Currency::USD(),
504            0.into(),
505            0.into(),
506            2,
507            Price::from("0.01"),
508            Quantity::from("0"), // zero multiplier
509            Quantity::from(1),
510            None,
511            None,
512            None,
513            None,
514            None,
515            None,
516            None,
517            None,
518            0.into(),
519            0.into(),
520            None,
521            None,
522            None,
523        );
524        assert!(result.is_err());
525    }
526
527    #[rstest]
528    #[case(Price::from("0"))]
529    #[case(Price::from("-1"))]
530    fn test_new_checked_rejects_non_positive_strike_price(#[case] strike_price: Price) {
531        let result = OptionContract::new_checked(
532            InstrumentId::from("TEST.OPRA"),
533            Symbol::from("TEST"),
534            AssetClass::Equity,
535            Some(Ustr::from("GMNI")),
536            Ustr::from("AAPL"),
537            OptionKind::Call,
538            strike_price,
539            Currency::USD(),
540            0.into(),
541            0.into(),
542            2,
543            Price::from("0.01"),
544            Quantity::from(1),
545            Quantity::from(1),
546            None,
547            None,
548            None,
549            None,
550            None,
551            None,
552            None,
553            None,
554            0.into(),
555            0.into(),
556            None,
557            None,
558            None,
559        );
560
561        // Assert on the parameter name, not merely `is_err`: this constructor validates a
562        // dozen other fields, and a bare error check would pass if an unrelated one fired.
563        assert!(
564            result
565                .unwrap_err()
566                .to_string()
567                .contains("'strike_price' not positive")
568        );
569    }
570
571    #[rstest]
572    fn test_serialization_roundtrip(option_contract_appl: OptionContract) {
573        let json = serde_json::to_string(&option_contract_appl).unwrap();
574        let deserialized: OptionContract = serde_json::from_str(&json).unwrap();
575        assert_eq!(json, serde_json::to_string(&deserialized).unwrap());
576    }
577
578    #[rstest]
579    fn test_builder_matches_new_checked() {
580        let positional = OptionContract::new_checked(
581            InstrumentId::from("AAPL211217C00150000.OPRA"),
582            Symbol::from("AAPL211217C00150000"),
583            AssetClass::Equity,
584            Some(Ustr::from("GMNI")),
585            Ustr::from("AAPL"),
586            OptionKind::Call,
587            Price::from("149.0"),
588            Currency::USD(),
589            1.into(),
590            2.into(),
591            2,
592            Price::from("0.01"),
593            Quantity::from(10),
594            Quantity::from(5),
595            Some(Quantity::from("100")),
596            Some(Quantity::from("1")),
597            Some(Price::from("999.0")),
598            Some(Price::from("1.0")),
599            Some(dec!(0.01)),
600            Some(dec!(0.02)),
601            None,
602            None,
603            3.into(),
604            4.into(),
605            Some(InstrumentId::from("AAPL.NASDAQ")),
606            Some(ExerciseStyle::American),
607            Some(SettlementType::Physical),
608        )
609        .unwrap();
610
611        let built = OptionContract::builder()
612            .instrument_id(InstrumentId::from("AAPL211217C00150000.OPRA"))
613            .raw_symbol(Symbol::from("AAPL211217C00150000"))
614            .asset_class(AssetClass::Equity)
615            .exchange(Ustr::from("GMNI"))
616            .underlying(Ustr::from("AAPL"))
617            .option_kind(OptionKind::Call)
618            .strike_price(Price::from("149.0"))
619            .currency(Currency::USD())
620            .activation_ns(1.into())
621            .expiration_ns(2.into())
622            .price_precision(2)
623            .price_increment(Price::from("0.01"))
624            .multiplier(Quantity::from(10))
625            .lot_size(Quantity::from(5))
626            .max_quantity(Quantity::from("100"))
627            .min_quantity(Quantity::from("1"))
628            .max_price(Price::from("999.0"))
629            .min_price(Price::from("1.0"))
630            .margin_init(dec!(0.01))
631            .margin_maint(dec!(0.02))
632            .ts_event(3.into())
633            .ts_init(4.into())
634            .underlying_instrument_id(InstrumentId::from("AAPL.NASDAQ"))
635            .exercise_style(ExerciseStyle::American)
636            .settlement_type(SettlementType::Physical)
637            .build()
638            .unwrap();
639
640        assert_eq!(
641            built.underlying_instrument_id,
642            Some(InstrumentId::from("AAPL.NASDAQ"))
643        );
644        assert_eq!(built.exercise_style, Some(ExerciseStyle::American));
645        assert_eq!(built.settlement_type, Some(SettlementType::Physical));
646        assert_eq!(
647            serde_json::to_value(&positional).unwrap(),
648            serde_json::to_value(&built).unwrap(),
649        );
650    }
651
652    #[rstest]
653    #[case(OptionKind::Call, ExerciseStyle::American, SettlementType::Cash)]
654    #[case(OptionKind::Put, ExerciseStyle::European, SettlementType::Physical)]
655    #[case(OptionKind::Call, ExerciseStyle::European, SettlementType::Physical)]
656    #[case(OptionKind::Put, ExerciseStyle::Bermudan, SettlementType::Cash)]
657    fn test_explicit_option_terms_round_trip(
658        #[from(option_contract_appl)] mut option: OptionContract,
659        #[case] kind: OptionKind,
660        #[case] style: ExerciseStyle,
661        #[case] settlement: SettlementType,
662    ) {
663        let legacy = option.clone();
664        let underlying_id = InstrumentId::from("AAPL.NASDAQ");
665        option.option_kind = kind;
666        option.underlying_instrument_id = Some(underlying_id);
667        option.exercise_style = Some(style);
668        option.settlement_type = Some(settlement);
669        let mut encoded = serde_json::to_value(&option).unwrap();
670        let restored: OptionContract = serde_json::from_value(encoded.clone()).unwrap();
671        let mut old = encoded.clone();
672        old.as_object_mut()
673            .unwrap()
674            .remove("underlying_instrument_id");
675        old.as_object_mut().unwrap().remove("exercise_style");
676        old.as_object_mut().unwrap().remove("settlement_type");
677        let restored_legacy: OptionContract = serde_json::from_value(old).unwrap();
678
679        assert_eq!(serde_json::to_value(&restored).unwrap(), encoded);
680        encoded["underlying_instrument_id"] = serde_json::Value::Null;
681        encoded["exercise_style"] = serde_json::Value::Null;
682        encoded["settlement_type"] = serde_json::Value::Null;
683        assert_eq!(serde_json::to_value(&restored_legacy).unwrap(), encoded);
684        assert_eq!(option, legacy);
685    }
686}