Skip to main content

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