Skip to main content

nautilus_model/instruments/
futures_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, InstrumentClass, OptionKind},
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 deliverable futures 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 FuturesContract {
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 futures 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    /// UNIX timestamp (nanoseconds) for contract activation.
64    pub activation_ns: UnixNanos,
65    /// UNIX timestamp (nanoseconds) for contract expiration.
66    pub expiration_ns: UnixNanos,
67    /// The futures contract currency.
68    pub currency: Currency,
69    /// The price decimal precision.
70    pub price_precision: u8,
71    /// The minimum price increment (tick size).
72    pub price_increment: Price,
73    /// The minimum size increment.
74    pub size_increment: Quantity,
75    /// The trading size decimal precision.
76    pub size_precision: u8,
77    /// The contract multiplier.
78    pub multiplier: Quantity,
79    /// The rounded lot unit size (standard/board).
80    pub lot_size: Quantity,
81    /// The initial (order) margin requirement in percentage of order value.
82    pub margin_init: Decimal,
83    /// The maintenance (position) margin in percentage of position value.
84    pub margin_maint: Decimal,
85    /// The fee rate for liquidity makers as a percentage of order value.
86    pub maker_fee: Decimal,
87    /// The fee rate for liquidity takers as a percentage of order value.
88    pub taker_fee: 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}
106
107#[bon::bon]
108impl FuturesContract {
109    #[expect(clippy::too_many_arguments)]
110    fn new_checked(
111        instrument_id: InstrumentId,
112        raw_symbol: Symbol,
113        asset_class: AssetClass,
114        exchange: Option<Ustr>,
115        underlying: Ustr,
116        activation_ns: UnixNanos,
117        expiration_ns: UnixNanos,
118        currency: Currency,
119        price_precision: u8,
120        price_increment: Price,
121        multiplier: Quantity,
122        lot_size: Quantity,
123        max_quantity: Option<Quantity>,
124        min_quantity: Option<Quantity>,
125        max_price: Option<Price>,
126        min_price: Option<Price>,
127        margin_init: Option<Decimal>,
128        margin_maint: Option<Decimal>,
129        maker_fee: Option<Decimal>,
130        taker_fee: Option<Decimal>,
131        tick_scheme: Option<Ustr>,
132        info: Option<Params>,
133        ts_event: UnixNanos,
134        ts_init: UnixNanos,
135    ) -> CorrectnessResult<Self> {
136        check_valid_string_ascii_optional(exchange.map(|u| u.as_str()), stringify!(exchange))?;
137        check_valid_string_ascii(underlying.as_str(), stringify!(underlying))?;
138        check_equal_u8(
139            price_precision,
140            price_increment.precision,
141            stringify!(price_precision),
142            stringify!(price_increment.precision),
143        )?;
144        check_positive_price(price_increment, stringify!(price_increment))?;
145        check_tick_scheme(tick_scheme)?;
146        check_positive_quantity(multiplier, stringify!(multiplier))?;
147        check_positive_quantity(lot_size, stringify!(lot_size))?;
148
149        Ok(Self {
150            id: instrument_id,
151            raw_symbol,
152            asset_class,
153            exchange,
154            underlying,
155            activation_ns,
156            expiration_ns,
157            currency,
158            price_precision,
159            price_increment,
160            size_precision: 0,
161            size_increment: Quantity::from(1),
162            multiplier,
163            lot_size,
164            max_quantity,
165            min_quantity: Some(min_quantity.unwrap_or(1.into())),
166            max_price,
167            min_price,
168            margin_init: margin_init.unwrap_or_default(),
169            margin_maint: margin_maint.unwrap_or_default(),
170            maker_fee: maker_fee.unwrap_or_default(),
171            taker_fee: taker_fee.unwrap_or_default(),
172            tick_scheme,
173            info,
174            ts_event,
175            ts_init,
176        })
177    }
178
179    /// Returns a fluent builder for a [`FuturesContract`] instance.
180    ///
181    /// Required fields are enforced at compile time; optional fields can be omitted and use the
182    /// same defaults as checked construction. The same correctness checks run on `build`.
183    ///
184    /// # Errors
185    ///
186    /// Returns an error if any input validation fails.
187    #[builder(start_fn = builder, finish_fn = build)]
188    pub fn build_checked(
189        instrument_id: InstrumentId,
190        raw_symbol: Symbol,
191        asset_class: AssetClass,
192        exchange: Option<Ustr>,
193        underlying: Ustr,
194        activation_ns: UnixNanos,
195        expiration_ns: UnixNanos,
196        currency: Currency,
197        price_precision: u8,
198        price_increment: Price,
199        multiplier: Quantity,
200        lot_size: Quantity,
201        max_quantity: Option<Quantity>,
202        min_quantity: Option<Quantity>,
203        max_price: Option<Price>,
204        min_price: Option<Price>,
205        margin_init: Option<Decimal>,
206        margin_maint: Option<Decimal>,
207        maker_fee: Option<Decimal>,
208        taker_fee: Option<Decimal>,
209        tick_scheme: Option<Ustr>,
210        info: Option<Params>,
211        ts_event: UnixNanos,
212        ts_init: UnixNanos,
213    ) -> CorrectnessResult<Self> {
214        Self::new_checked(
215            instrument_id,
216            raw_symbol,
217            asset_class,
218            exchange,
219            underlying,
220            activation_ns,
221            expiration_ns,
222            currency,
223            price_precision,
224            price_increment,
225            multiplier,
226            lot_size,
227            max_quantity,
228            min_quantity,
229            max_price,
230            min_price,
231            margin_init,
232            margin_maint,
233            maker_fee,
234            taker_fee,
235            tick_scheme,
236            info,
237            ts_event,
238            ts_init,
239        )
240    }
241}
242
243impl PartialEq<Self> for FuturesContract {
244    fn eq(&self, other: &Self) -> bool {
245        self.id == other.id
246    }
247}
248
249impl Eq for FuturesContract {}
250
251impl Hash for FuturesContract {
252    fn hash<H: Hasher>(&self, state: &mut H) {
253        self.id.hash(state);
254    }
255}
256
257impl Instrument for FuturesContract {
258    fn tick_scheme(&self) -> Option<Ustr> {
259        self.tick_scheme
260    }
261    fn into_any(self) -> InstrumentAny {
262        InstrumentAny::FuturesContract(self)
263    }
264
265    fn id(&self) -> InstrumentId {
266        self.id
267    }
268
269    fn raw_symbol(&self) -> Symbol {
270        self.raw_symbol
271    }
272
273    fn asset_class(&self) -> AssetClass {
274        self.asset_class
275    }
276
277    fn instrument_class(&self) -> InstrumentClass {
278        InstrumentClass::Future
279    }
280    fn underlying(&self) -> Option<Ustr> {
281        Some(self.underlying)
282    }
283
284    fn base_currency(&self) -> Option<Currency> {
285        None
286    }
287
288    fn quote_currency(&self) -> Currency {
289        self.currency
290    }
291
292    fn settlement_currency(&self) -> Currency {
293        self.currency
294    }
295
296    fn isin(&self) -> Option<Ustr> {
297        None
298    }
299
300    fn option_kind(&self) -> Option<OptionKind> {
301        None
302    }
303
304    fn exchange(&self) -> Option<Ustr> {
305        self.exchange
306    }
307
308    fn strike_price(&self) -> Option<Price> {
309        None
310    }
311
312    fn activation_ns(&self) -> Option<UnixNanos> {
313        Some(self.activation_ns)
314    }
315
316    fn expiration_ns(&self) -> Option<UnixNanos> {
317        Some(self.expiration_ns)
318    }
319
320    fn is_inverse(&self) -> bool {
321        false
322    }
323
324    fn price_precision(&self) -> u8 {
325        self.price_precision
326    }
327
328    fn size_precision(&self) -> u8 {
329        0
330    }
331
332    fn price_increment(&self) -> Price {
333        self.price_increment
334    }
335
336    fn size_increment(&self) -> Quantity {
337        Quantity::from(1)
338    }
339
340    fn multiplier(&self) -> Quantity {
341        self.multiplier
342    }
343
344    fn lot_size(&self) -> Option<Quantity> {
345        Some(self.lot_size)
346    }
347
348    fn max_quantity(&self) -> Option<Quantity> {
349        self.max_quantity
350    }
351
352    fn min_quantity(&self) -> Option<Quantity> {
353        self.min_quantity
354    }
355
356    fn max_notional(&self) -> Option<Money> {
357        None
358    }
359
360    fn min_notional(&self) -> Option<Money> {
361        None
362    }
363
364    fn max_price(&self) -> Option<Price> {
365        self.max_price
366    }
367
368    fn min_price(&self) -> Option<Price> {
369        self.min_price
370    }
371
372    fn ts_event(&self) -> UnixNanos {
373        self.ts_event
374    }
375
376    fn ts_init(&self) -> UnixNanos {
377        self.ts_init
378    }
379
380    fn margin_init(&self) -> Decimal {
381        self.margin_init
382    }
383
384    fn margin_maint(&self) -> Decimal {
385        self.margin_maint
386    }
387
388    fn maker_fee(&self) -> Decimal {
389        self.maker_fee
390    }
391
392    fn taker_fee(&self) -> Decimal {
393        self.taker_fee
394    }
395}
396
397#[cfg(test)]
398mod tests {
399    use rstest::rstest;
400    use rust_decimal_macros::dec;
401    use ustr::Ustr;
402
403    use crate::{
404        enums::{AssetClass, InstrumentClass},
405        identifiers::{InstrumentId, Symbol},
406        instruments::{FuturesContract, Instrument, stubs::*},
407        types::{Currency, Price, Quantity},
408    };
409
410    #[rstest]
411    fn test_trait_accessors() {
412        let inst = futures_contract_es(None, None);
413        assert_eq!(inst.id(), InstrumentId::from("ESZ21.GLBX"));
414        assert_eq!(inst.raw_symbol(), Symbol::from("ESZ21"));
415        assert_eq!(inst.asset_class(), AssetClass::Index);
416        assert_eq!(inst.instrument_class(), InstrumentClass::Future);
417        assert_eq!(inst.quote_currency(), Currency::USD());
418        assert!(!inst.is_inverse());
419        assert_eq!(inst.price_precision(), 2);
420        assert_eq!(inst.size_precision(), 0);
421        assert_eq!(inst.price_increment(), Price::from("0.01"));
422        assert_eq!(inst.size_increment(), Quantity::from("1"));
423        assert_eq!(inst.multiplier(), Quantity::from("1"));
424        assert_eq!(inst.lot_size(), Some(Quantity::from("1")));
425        assert_eq!(inst.underlying(), Some(Ustr::from("ES")));
426        assert_eq!(inst.exchange(), Some(Ustr::from("XCME")));
427        assert!(inst.activation_ns().is_some());
428        assert!(inst.expiration_ns().is_some());
429        assert_eq!(inst.min_quantity(), Some(Quantity::from("1")));
430    }
431
432    #[rstest]
433    fn test_new_checked_price_precision_mismatch() {
434        let result = FuturesContract::new_checked(
435            InstrumentId::from("ESZ21.GLBX"),
436            Symbol::from("ESZ21"),
437            AssetClass::Index,
438            Some(Ustr::from("XCME")),
439            Ustr::from("ES"),
440            0.into(),
441            0.into(),
442            Currency::USD(),
443            4, // mismatch
444            Price::from("0.01"),
445            Quantity::from(1),
446            Quantity::from(1),
447            None,
448            None,
449            None,
450            None,
451            None,
452            None,
453            None,
454            None,
455            None,
456            None,
457            0.into(),
458            0.into(),
459        );
460        assert!(result.is_err());
461    }
462
463    #[rstest]
464    fn test_new_checked_zero_multiplier() {
465        let result = FuturesContract::new_checked(
466            InstrumentId::from("ESZ21.GLBX"),
467            Symbol::from("ESZ21"),
468            AssetClass::Index,
469            Some(Ustr::from("XCME")),
470            Ustr::from("ES"),
471            0.into(),
472            0.into(),
473            Currency::USD(),
474            2,
475            Price::from("0.01"),
476            Quantity::from("0"), // zero multiplier
477            Quantity::from(1),
478            None,
479            None,
480            None,
481            None,
482            None,
483            None,
484            None,
485            None,
486            None,
487            None,
488            0.into(),
489            0.into(),
490        );
491        assert!(result.is_err());
492    }
493
494    #[rstest]
495    fn test_new_checked_zero_lot_size() {
496        let result = FuturesContract::new_checked(
497            InstrumentId::from("ESZ21.GLBX"),
498            Symbol::from("ESZ21"),
499            AssetClass::Index,
500            Some(Ustr::from("XCME")),
501            Ustr::from("ES"),
502            0.into(),
503            0.into(),
504            Currency::USD(),
505            2,
506            Price::from("0.01"),
507            Quantity::from(1),
508            Quantity::from("0"), // zero lot_size
509            None,
510            None,
511            None,
512            None,
513            None,
514            None,
515            None,
516            None,
517            None,
518            None,
519            0.into(),
520            0.into(),
521        );
522        assert!(result.is_err());
523    }
524
525    #[rstest]
526    fn test_serialization_roundtrip() {
527        let inst = futures_contract_es(None, None);
528        let json = serde_json::to_string(&inst).unwrap();
529        let deserialized: FuturesContract = serde_json::from_str(&json).unwrap();
530        assert_eq!(json, serde_json::to_string(&deserialized).unwrap());
531    }
532
533    #[rstest]
534    fn test_builder_matches_new_checked() {
535        let positional = FuturesContract::new_checked(
536            InstrumentId::from("ESZ21.GLBX"),
537            Symbol::from("ESZ21"),
538            AssetClass::Index,
539            Some(Ustr::from("XCME")),
540            Ustr::from("ES"),
541            1_000.into(),
542            2_000.into(),
543            Currency::USD(),
544            2,
545            Price::from("0.01"),
546            Quantity::from(50),
547            Quantity::from(10),
548            Some(Quantity::from("10000")),
549            Some(Quantity::from("5")),
550            Some(Price::from("9999.99")),
551            Some(Price::from("0.01")),
552            Some(dec!(0.01)),
553            Some(dec!(0.02)),
554            Some(dec!(0.0002)),
555            Some(dec!(0.0004)),
556            None,
557            None,
558            1.into(),
559            2.into(),
560        )
561        .unwrap();
562
563        let built = FuturesContract::builder()
564            .instrument_id(InstrumentId::from("ESZ21.GLBX"))
565            .raw_symbol(Symbol::from("ESZ21"))
566            .asset_class(AssetClass::Index)
567            .exchange(Ustr::from("XCME"))
568            .underlying(Ustr::from("ES"))
569            .activation_ns(1_000.into())
570            .expiration_ns(2_000.into())
571            .currency(Currency::USD())
572            .price_precision(2)
573            .price_increment(Price::from("0.01"))
574            .multiplier(Quantity::from(50))
575            .lot_size(Quantity::from(10))
576            .max_quantity(Quantity::from("10000"))
577            .min_quantity(Quantity::from("5"))
578            .max_price(Price::from("9999.99"))
579            .min_price(Price::from("0.01"))
580            .margin_init(dec!(0.01))
581            .margin_maint(dec!(0.02))
582            .maker_fee(dec!(0.0002))
583            .taker_fee(dec!(0.0004))
584            .ts_event(1.into())
585            .ts_init(2.into())
586            .build()
587            .unwrap();
588
589        assert_eq!(
590            serde_json::to_value(&positional).unwrap(),
591            serde_json::to_value(&built).unwrap(),
592        );
593    }
594}