Skip to main content

nautilus_model/
enums.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
16//! Enumerations for the trading domain model.
17
18use std::{borrow::Cow, fmt::Display, marker::PhantomData, str::FromStr};
19
20use serde::{Deserialize, Deserializer, Serializer};
21use strum::{AsRefStr, Display, EnumIter, EnumString, FromRepr};
22
23use crate::enum_strum_serde;
24
25/// Provides conversion from a `u8` value to an enum type.
26pub trait FromU8 {
27    /// Converts a `u8` value to the implementing type.
28    ///
29    /// Returns `None` if the value is not a valid representation.
30    fn from_u8(value: u8) -> Option<Self>
31    where
32        Self: Sized;
33}
34
35/// Provides conversion from a `u16` value to an enum type.
36pub trait FromU16 {
37    /// Converts a `u16` value to the implementing type.
38    ///
39    /// Returns `None` if the value is not a valid representation.
40    fn from_u16(value: u16) -> Option<Self>
41    where
42        Self: Sized;
43}
44
45/// An account type provided by a trading venue or execution provider.
46#[repr(C)]
47#[derive(
48    Copy,
49    Clone,
50    Debug,
51    Display,
52    Hash,
53    PartialEq,
54    Eq,
55    PartialOrd,
56    Ord,
57    AsRefStr,
58    FromRepr,
59    EnumIter,
60    EnumString,
61)]
62#[strum(ascii_case_insensitive)]
63#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
64#[cfg_attr(
65    feature = "python",
66    pyo3::pyclass(
67        frozen,
68        eq,
69        eq_int,
70        module = "nautilus_trader.model",
71        from_py_object,
72        rename_all = "SCREAMING_SNAKE_CASE",
73    )
74)]
75#[cfg_attr(
76    feature = "python",
77    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
78)]
79pub enum AccountType {
80    /// An account with unleveraged cash assets only.
81    Cash = 1,
82    /// An account which facilitates trading on margin, using account assets as collateral.
83    Margin = 2,
84    /// An account specific to betting markets.
85    Betting = 3,
86    /// An account which represents a blockchain wallet,
87    Wallet = 4,
88}
89
90/// An aggregation source for derived data.
91#[repr(C)]
92#[derive(
93    Copy,
94    Clone,
95    Debug,
96    Display,
97    Hash,
98    PartialEq,
99    Eq,
100    PartialOrd,
101    Ord,
102    AsRefStr,
103    FromRepr,
104    EnumIter,
105    EnumString,
106)]
107#[strum(ascii_case_insensitive)]
108#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
109#[cfg_attr(
110    feature = "python",
111    pyo3::pyclass(
112        frozen,
113        eq,
114        eq_int,
115        module = "nautilus_trader.model",
116        from_py_object,
117        rename_all = "SCREAMING_SNAKE_CASE",
118    )
119)]
120#[cfg_attr(
121    feature = "python",
122    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
123)]
124pub enum AggregationSource {
125    /// The data is externally aggregated (outside the Nautilus system boundary).
126    External = 1,
127    /// The data is internally aggregated (inside the Nautilus system boundary).
128    Internal = 2,
129}
130
131/// The side for the aggressing order of a trade in a market.
132#[repr(C)]
133#[derive(
134    Copy,
135    Clone,
136    Debug,
137    Default,
138    Display,
139    Hash,
140    PartialEq,
141    Eq,
142    PartialOrd,
143    Ord,
144    AsRefStr,
145    FromRepr,
146    EnumIter,
147    EnumString,
148)]
149#[strum(ascii_case_insensitive)]
150#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
151#[cfg_attr(
152    feature = "python",
153    pyo3::pyclass(
154        frozen,
155        eq,
156        eq_int,
157        module = "nautilus_trader.model",
158        from_py_object,
159        rename_all = "SCREAMING_SNAKE_CASE",
160    )
161)]
162#[cfg_attr(
163    feature = "python",
164    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
165)]
166pub enum AggressorSide {
167    /// There was no specific aggressor for the trade.
168    #[default]
169    NoAggressor = 0,
170    /// The BUY order was the aggressor for the trade.
171    ///
172    /// The deprecated `BUYER` serialization value is still accepted when parsing.
173    #[strum(serialize = "BUYER", to_string = "BUY")]
174    Buy = 1,
175    /// The SELL order was the aggressor for the trade.
176    ///
177    /// The deprecated `SELLER` serialization value is still accepted when parsing.
178    #[strum(serialize = "SELLER", to_string = "SELL")]
179    Sell = 2,
180}
181
182impl FromU8 for AggressorSide {
183    fn from_u8(value: u8) -> Option<Self> {
184        Self::from_repr(usize::from(value))
185    }
186}
187
188/// A broad financial market asset class.
189#[repr(C)]
190#[derive(
191    Copy,
192    Clone,
193    Debug,
194    Display,
195    Hash,
196    PartialEq,
197    Eq,
198    PartialOrd,
199    Ord,
200    AsRefStr,
201    FromRepr,
202    EnumIter,
203    EnumString,
204)]
205#[strum(ascii_case_insensitive)]
206#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
207#[cfg_attr(
208    feature = "python",
209    pyo3::pyclass(
210        frozen,
211        eq,
212        eq_int,
213        module = "nautilus_trader.model",
214        from_py_object,
215        rename_all = "SCREAMING_SNAKE_CASE",
216    )
217)]
218#[cfg_attr(
219    feature = "python",
220    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
221)]
222#[allow(non_camel_case_types)]
223pub enum AssetClass {
224    /// Foreign exchange (FOREX) assets.
225    FX = 1,
226    /// Equity / stock assets.
227    Equity = 2,
228    /// Commodity assets.
229    Commodity = 3,
230    /// Debt based assets.
231    Debt = 4,
232    /// Index based assets (baskets).
233    Index = 5,
234    /// Cryptocurrency or crypto token assets.
235    Cryptocurrency = 6,
236    /// Alternative assets.
237    Alternative = 7,
238}
239
240impl FromU8 for AssetClass {
241    fn from_u8(value: u8) -> Option<Self> {
242        Self::from_repr(usize::from(value))
243    }
244}
245
246/// How position reconciliation may use a venue-reported average entry price.
247#[repr(C)]
248#[derive(
249    Copy,
250    Clone,
251    Debug,
252    Default,
253    Display,
254    Hash,
255    PartialEq,
256    Eq,
257    PartialOrd,
258    Ord,
259    AsRefStr,
260    FromRepr,
261    EnumIter,
262    EnumString,
263)]
264#[strum(ascii_case_insensitive)]
265#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
266#[cfg_attr(
267    feature = "python",
268    pyo3::pyclass(
269        frozen,
270        eq,
271        eq_int,
272        module = "nautilus_trader.model",
273        from_py_object,
274        rename_all = "SCREAMING_SNAKE_CASE",
275    )
276)]
277#[cfg_attr(
278    feature = "python",
279    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
280)]
281pub enum AvgPxReconciliation {
282    /// The average must match the cached position average within tolerance, and prices
283    /// reconciliation fills.
284    #[default]
285    Match = 1,
286    /// The average prices only positions opened from flat, and is never compared.
287    ///
288    /// For venue averages computed by a different method, such as FIFO lots.
289    OpeningOnly = 2,
290}
291
292/// The aggregation method through which a bar is generated and closed.
293#[repr(C)]
294#[derive(
295    Copy,
296    Clone,
297    Debug,
298    Display,
299    Hash,
300    PartialEq,
301    Eq,
302    PartialOrd,
303    Ord,
304    AsRefStr,
305    FromRepr,
306    EnumIter,
307    EnumString,
308)]
309#[strum(ascii_case_insensitive)]
310#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
311#[cfg_attr(
312    feature = "python",
313    pyo3::pyclass(
314        frozen,
315        eq,
316        eq_int,
317        module = "nautilus_trader.model",
318        from_py_object,
319        rename_all = "SCREAMING_SNAKE_CASE",
320    )
321)]
322#[cfg_attr(
323    feature = "python",
324    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
325)]
326pub enum BarAggregation {
327    /// Based on a number of ticks.
328    Tick = 1,
329    /// Based on the buy/sell imbalance of ticks.
330    TickImbalance = 2,
331    /// Based on sequential buy/sell runs of ticks.
332    TickRuns = 3,
333    /// Based on traded volume.
334    Volume = 4,
335    /// Based on the buy/sell imbalance of traded volume.
336    VolumeImbalance = 5,
337    /// Based on sequential runs of buy/sell traded volume.
338    VolumeRuns = 6,
339    /// Based on the 'notional' value of the instrument.
340    Value = 7,
341    /// Based on the buy/sell imbalance of trading by notional value.
342    ValueImbalance = 8,
343    /// Based on sequential buy/sell runs of trading by notional value.
344    ValueRuns = 9,
345    /// Based on time intervals with millisecond granularity.
346    Millisecond = 10,
347    /// Based on time intervals with second granularity.
348    Second = 11,
349    /// Based on time intervals with minute granularity.
350    Minute = 12,
351    /// Based on time intervals with hour granularity.
352    Hour = 13,
353    /// Based on time intervals with day granularity.
354    Day = 14,
355    /// Based on time intervals with week granularity.
356    Week = 15,
357    /// Based on time intervals with month granularity.
358    Month = 16,
359    /// Based on time intervals with year granularity.
360    Year = 17,
361    /// Based on fixed price movements (brick size).
362    Renko = 18,
363}
364
365/// The interval type for bar aggregation.
366#[repr(C)]
367#[derive(
368    Copy,
369    Clone,
370    Debug,
371    Default,
372    Display,
373    Hash,
374    PartialEq,
375    Eq,
376    PartialOrd,
377    Ord,
378    AsRefStr,
379    FromRepr,
380    EnumIter,
381    EnumString,
382)]
383#[strum(ascii_case_insensitive)]
384#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
385#[cfg_attr(
386    feature = "python",
387    pyo3::pyclass(
388        frozen,
389        eq,
390        eq_int,
391        module = "nautilus_trader.model",
392        from_py_object,
393        rename_all = "SCREAMING_SNAKE_CASE",
394    )
395)]
396#[cfg_attr(
397    feature = "python",
398    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
399)]
400pub enum BarIntervalType {
401    /// Left-open interval `(start, end]`: start is exclusive, end is inclusive (default).
402    #[default]
403    LeftOpen = 1,
404    /// Right-open interval `[start, end)`: start is inclusive, end is exclusive.
405    RightOpen = 2,
406}
407
408/// Represents the side of a bet in a betting market.
409#[repr(C)]
410#[derive(
411    Copy,
412    Clone,
413    Debug,
414    Display,
415    Hash,
416    PartialEq,
417    Eq,
418    PartialOrd,
419    Ord,
420    AsRefStr,
421    FromRepr,
422    EnumIter,
423    EnumString,
424)]
425#[strum(ascii_case_insensitive)]
426#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
427#[cfg_attr(
428    feature = "python",
429    pyo3::pyclass(
430        frozen,
431        eq,
432        eq_int,
433        module = "nautilus_trader.model",
434        from_py_object,
435        rename_all = "SCREAMING_SNAKE_CASE",
436    )
437)]
438#[cfg_attr(
439    feature = "python",
440    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
441)]
442pub enum BetSide {
443    /// A "Back" bet signifies support for a specific outcome.
444    Back = 1,
445    /// A "Lay" bet signifies opposition to a specific outcome.
446    Lay = 2,
447}
448
449impl BetSide {
450    /// Returns the opposite betting side.
451    #[must_use]
452    pub fn opposite(&self) -> Self {
453        match self {
454            Self::Back => Self::Lay,
455            Self::Lay => Self::Back,
456        }
457    }
458}
459
460impl From<OrderSide> for BetSide {
461    fn from(side: OrderSide) -> Self {
462        match side {
463            OrderSide::Buy => Self::Back,
464            OrderSide::Sell => Self::Lay,
465        }
466    }
467}
468
469/// The type of order book action for an order book event.
470#[repr(C)]
471#[derive(
472    Copy,
473    Clone,
474    Debug,
475    Display,
476    Hash,
477    PartialEq,
478    Eq,
479    PartialOrd,
480    Ord,
481    AsRefStr,
482    FromRepr,
483    EnumIter,
484    EnumString,
485)]
486#[strum(ascii_case_insensitive)]
487#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
488#[cfg_attr(
489    feature = "python",
490    pyo3::pyclass(
491        frozen,
492        eq,
493        eq_int,
494        module = "nautilus_trader.model",
495        from_py_object,
496        rename_all = "SCREAMING_SNAKE_CASE",
497    )
498)]
499#[cfg_attr(
500    feature = "python",
501    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
502)]
503pub enum BookAction {
504    /// An order is added to the book.
505    Add = 1,
506    /// An existing order in the book is updated/modified.
507    Update = 2,
508    /// An existing order in the book is deleted/canceled.
509    Delete = 3,
510    /// The state of the order book is cleared.
511    Clear = 4,
512}
513
514impl FromU8 for BookAction {
515    fn from_u8(value: u8) -> Option<Self> {
516        Self::from_repr(usize::from(value))
517    }
518}
519
520/// The order book type, representing the type of levels granularity and delta updating heuristics.
521#[repr(C)]
522#[derive(
523    Copy,
524    Clone,
525    Debug,
526    Display,
527    Hash,
528    PartialEq,
529    Eq,
530    PartialOrd,
531    Ord,
532    AsRefStr,
533    FromRepr,
534    EnumIter,
535    EnumString,
536)]
537#[strum(ascii_case_insensitive)]
538#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
539#[cfg_attr(
540    feature = "python",
541    pyo3::pyclass(
542        frozen,
543        eq,
544        eq_int,
545        module = "nautilus_trader.model",
546        from_py_object,
547        rename_all = "SCREAMING_SNAKE_CASE",
548    )
549)]
550#[cfg_attr(
551    feature = "python",
552    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
553)]
554#[allow(non_camel_case_types)]
555pub enum BookType {
556    /// Top-of-book best bid/ask, one level per side.
557    L1_MBP = 1,
558    /// Market by price, one order per level (aggregated).
559    L2_MBP = 2,
560    /// Market by order, multiple orders per level (full granularity).
561    L3_MBO = 3,
562}
563
564impl FromU8 for BookType {
565    fn from_u8(value: u8) -> Option<Self> {
566        Self::from_repr(usize::from(value))
567    }
568}
569
570/// The order contingency type which specifies the behavior of linked orders.
571///
572/// [FIX 5.0 SP2 : ContingencyType <1385> field](https://www.onixs.biz/fix-dictionary/5.0.sp2/tagnum_1385.html).
573///
574/// Python retains `NO_CONTINGENCY` as a compatibility alias for `None`. The alias is not an enum
575/// variant and may be removed in a future version.
576#[repr(C)]
577#[derive(
578    Copy,
579    Clone,
580    Debug,
581    Display,
582    Hash,
583    PartialEq,
584    Eq,
585    PartialOrd,
586    Ord,
587    AsRefStr,
588    FromRepr,
589    EnumIter,
590    EnumString,
591)]
592#[strum(ascii_case_insensitive)]
593#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
594#[cfg_attr(
595    feature = "python",
596    pyo3::pyclass(
597        frozen,
598        eq,
599        eq_int,
600        module = "nautilus_trader.model",
601        from_py_object,
602        rename_all = "SCREAMING_SNAKE_CASE",
603    )
604)]
605#[cfg_attr(
606    feature = "python",
607    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
608)]
609pub enum ContingencyType {
610    /// One-Cancels-the-Other.
611    Oco = 1,
612    /// One-Triggers-the-Other.
613    Oto = 2,
614    /// One-Updates-the-Other (by proportional quantity).
615    Ouo = 3,
616}
617
618/// The price-adjustment scheme applied when stitching segment contracts into a
619/// continuous future series.
620///
621/// The direction (backward vs. forward) selects the anchor contract:
622/// - Backward modes anchor on the most recent contract; prices in older
623///   segments are shifted into the latest contract's frame.
624/// - Forward modes anchor on the first contract; prices in later segments
625///   are shifted into the first contract's frame.
626///
627/// The kind (spread vs. ratio) selects how each transition's offset is combined:
628/// - Spread modes accumulate additive offsets (`post_price - pre_price`).
629/// - Ratio modes accumulate multiplicative factors (`post_price / pre_price`)
630///   and require strictly positive prices.
631#[repr(C)]
632#[derive(
633    Copy,
634    Clone,
635    Debug,
636    Default,
637    Display,
638    Hash,
639    PartialEq,
640    Eq,
641    PartialOrd,
642    Ord,
643    AsRefStr,
644    FromRepr,
645    EnumIter,
646    EnumString,
647)]
648#[strum(ascii_case_insensitive)]
649#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
650#[cfg_attr(
651    feature = "python",
652    pyo3::pyclass(
653        frozen,
654        eq,
655        eq_int,
656        module = "nautilus_trader.model",
657        from_py_object,
658        rename_all = "SCREAMING_SNAKE_CASE",
659    )
660)]
661#[cfg_attr(
662    feature = "python",
663    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
664)]
665pub enum ContinuousFutureAdjustmentType {
666    /// Additive adjustment, anchored on the most recent contract.
667    #[default]
668    BackwardSpread = 1,
669    /// Additive adjustment, anchored on the first contract.
670    ForwardSpread = 2,
671    /// Multiplicative adjustment, anchored on the most recent contract.
672    BackwardRatio = 3,
673    /// Multiplicative adjustment, anchored on the first contract.
674    ForwardRatio = 4,
675}
676
677impl ContinuousFutureAdjustmentType {
678    /// Returns whether this mode accumulates multiplicative factors.
679    #[must_use]
680    pub const fn is_ratio(&self) -> bool {
681        matches!(self, Self::BackwardRatio | Self::ForwardRatio)
682    }
683
684    /// Returns whether this mode anchors on the most recent contract.
685    #[must_use]
686    pub const fn is_backward(&self) -> bool {
687        matches!(self, Self::BackwardSpread | Self::BackwardRatio)
688    }
689}
690
691/// The broad currency type.
692#[repr(C)]
693#[derive(
694    Copy,
695    Clone,
696    Debug,
697    Display,
698    Hash,
699    PartialEq,
700    Eq,
701    PartialOrd,
702    Ord,
703    AsRefStr,
704    FromRepr,
705    EnumIter,
706    EnumString,
707)]
708#[strum(ascii_case_insensitive)]
709#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
710#[cfg_attr(
711    feature = "python",
712    pyo3::pyclass(
713        frozen,
714        eq,
715        eq_int,
716        module = "nautilus_trader.model",
717        from_py_object,
718        rename_all = "SCREAMING_SNAKE_CASE",
719    )
720)]
721#[cfg_attr(
722    feature = "python",
723    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
724)]
725pub enum CurrencyType {
726    /// A type of cryptocurrency or crypto token.
727    Crypto = 1,
728    /// A type of currency issued by governments which is not backed by a commodity.
729    Fiat = 2,
730    /// A type of currency that is based on the value of an underlying commodity.
731    CommodityBacked = 3,
732}
733
734/// The exercise style of an option, independent of its kind and settlement type.
735#[repr(C)]
736#[derive(
737    Copy,
738    Clone,
739    Debug,
740    Display,
741    Hash,
742    PartialEq,
743    Eq,
744    PartialOrd,
745    Ord,
746    AsRefStr,
747    FromRepr,
748    EnumIter,
749    EnumString,
750)]
751#[strum(ascii_case_insensitive)]
752#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
753#[cfg_attr(
754    feature = "python",
755    pyo3::pyclass(
756        frozen,
757        eq,
758        eq_int,
759        module = "nautilus_trader.model",
760        from_py_object,
761        rename_all = "SCREAMING_SNAKE_CASE",
762    )
763)]
764#[cfg_attr(
765    feature = "python",
766    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
767)]
768pub enum ExerciseStyle {
769    /// Exercisable at any time up to expiration.
770    American = 1,
771    /// Exercisable only at expiration.
772    European = 2,
773    /// Exercisable only on specified dates up to expiration.
774    Bermudan = 3,
775}
776
777/// The instrument class.
778#[repr(C)]
779#[derive(
780    Copy,
781    Clone,
782    Debug,
783    Display,
784    Hash,
785    PartialEq,
786    Eq,
787    PartialOrd,
788    Ord,
789    AsRefStr,
790    FromRepr,
791    EnumIter,
792    EnumString,
793)]
794#[strum(ascii_case_insensitive)]
795#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
796#[cfg_attr(
797    feature = "python",
798    pyo3::pyclass(
799        frozen,
800        eq,
801        eq_int,
802        module = "nautilus_trader.model",
803        from_py_object,
804        rename_all = "SCREAMING_SNAKE_CASE",
805    )
806)]
807#[cfg_attr(
808    feature = "python",
809    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
810)]
811pub enum InstrumentClass {
812    /// A spot market instrument class. The current market price of an instrument that is bought or sold for immediate delivery and payment.
813    Spot = 1,
814    /// A swap instrument class. A derivative contract through which two parties exchange the cash flows or liabilities from two different financial instruments.
815    Swap = 2,
816    /// A futures contract instrument class. A legal agreement to buy or sell an asset at a predetermined price at a specified time in the future.
817    Future = 3,
818    /// A futures spread instrument class. A strategy involving the use of futures contracts to take advantage of price differentials between different contract months, underlying assets, or marketplaces.
819    FuturesSpread = 4,
820    /// A forward derivative instrument class. A customized contract between two parties to buy or sell an asset at a specified price on a future date.
821    Forward = 5,
822    /// A contract-for-difference (CFD) instrument class. A contract between an investor and a CFD provider to exchange the difference in the value of a financial product between the time the contract opens and closes.
823    Cfd = 6,
824    /// A bond instrument class. A type of debt investment where an investor loans money to an entity (typically corporate or governmental) which borrows the funds for a defined period of time at a variable or fixed interest rate.
825    Bond = 7,
826    /// An option contract instrument class. A type of derivative that gives the holder the right, but not the obligation, to buy or sell an underlying asset at a predetermined price before or at a certain future date.
827    Option = 8,
828    /// An option spread instrument class. A strategy involving the purchase and/or sale of multiple option contracts on the same underlying asset with different strike prices or expiration dates to hedge risk or speculate on price movements.
829    OptionSpread = 9,
830    /// A warrant instrument class. A derivative that gives the holder the right, but not the obligation, to buy or sell a security - most commonly an equity - at a certain price before expiration.
831    Warrant = 10,
832    /// A sports betting instrument class. A financialized derivative that allows wagering on the outcome of sports events using structured contracts or prediction markets.
833    SportsBetting = 11,
834    /// A binary option instrument class. A type of derivative where the payoff is either a fixed monetary amount or nothing, depending on whether the price of an underlying asset is above or below a predetermined level at expiration.
835    BinaryOption = 12,
836}
837
838impl InstrumentClass {
839    /// Returns whether this instrument class has an expiration.
840    #[must_use]
841    pub const fn has_expiration(&self) -> bool {
842        matches!(
843            self,
844            Self::Future | Self::FuturesSpread | Self::Option | Self::OptionSpread
845        )
846    }
847
848    /// Returns whether this instrument class allows negative prices.
849    ///
850    /// Futures allow negative prices, which occur as real settlement prices (e.g. WTI crude
851    /// oil in April 2020) and in back-adjusted continuous price series. Inverse instruments
852    /// whose notional divides by price still require a positive price.
853    #[must_use]
854    pub const fn allows_negative_price(&self) -> bool {
855        matches!(
856            self,
857            Self::Future | Self::Option | Self::FuturesSpread | Self::OptionSpread
858        )
859    }
860
861    /// Returns whether fills for this instrument class exchange the notional value as premium cash.
862    #[must_use]
863    pub const fn is_premium_based(&self) -> bool {
864        matches!(
865            self,
866            Self::Option | Self::OptionSpread | Self::BinaryOption | Self::Warrant
867        )
868    }
869
870    /// Returns whether inverse valuation for this class divides by price, which holds for inverse
871    /// instruments unless the class is premium based.
872    #[must_use]
873    pub const fn divides_notional_by_price(&self, is_inverse: bool) -> bool {
874        is_inverse && !self.is_premium_based()
875    }
876
877    /// Returns the [`InstrumentClass`] for the parent-symbol suffix, if recognized.
878    ///
879    /// Matches strict uppercase forms only. Both Databento-style abbreviations
880    /// (`FUT`, `OPT`) and long forms (`FUTURE`, `OPTION`) are accepted.
881    #[must_use]
882    pub fn try_from_parent_suffix(suffix: &str) -> Option<Self> {
883        match suffix {
884            "FUT" | "FUTURE" => Some(Self::Future),
885            "OPT" | "OPTION" => Some(Self::Option),
886            _ => None,
887        }
888    }
889
890    /// Returns the canonical parent-symbol suffix for this class, if one exists.
891    ///
892    /// Always emits the short form (`FUT`, `OPT`) so that adapters constructing
893    /// parent ids produce a single canonical string per class.
894    #[must_use]
895    pub const fn parent_suffix(self) -> Option<&'static str> {
896        match self {
897            Self::Future => Some("FUT"),
898            Self::Option => Some("OPT"),
899            _ => None,
900        }
901    }
902}
903
904/// The type of event for an instrument close.
905#[repr(C)]
906#[derive(
907    Copy,
908    Clone,
909    Debug,
910    Display,
911    Hash,
912    PartialEq,
913    Eq,
914    PartialOrd,
915    Ord,
916    AsRefStr,
917    FromRepr,
918    EnumIter,
919    EnumString,
920)]
921#[strum(ascii_case_insensitive)]
922#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
923#[cfg_attr(
924    feature = "python",
925    pyo3::pyclass(
926        frozen,
927        eq,
928        eq_int,
929        module = "nautilus_trader.model",
930        from_py_object,
931        rename_all = "SCREAMING_SNAKE_CASE",
932    )
933)]
934#[cfg_attr(
935    feature = "python",
936    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
937)]
938pub enum InstrumentCloseType {
939    /// When the market session ended.
940    EndOfSession = 1,
941    /// When the instrument expiration was reached.
942    ContractExpired = 2,
943}
944
945/// Convert the given `value` to an [`InstrumentCloseType`].
946impl FromU8 for InstrumentCloseType {
947    fn from_u8(value: u8) -> Option<Self> {
948        Self::from_repr(usize::from(value))
949    }
950}
951
952/// The liquidity side for a trade.
953#[repr(C)]
954#[derive(
955    Copy,
956    Clone,
957    Debug,
958    Display,
959    Hash,
960    PartialEq,
961    Eq,
962    PartialOrd,
963    Ord,
964    AsRefStr,
965    FromRepr,
966    EnumIter,
967    EnumString,
968)]
969#[strum(ascii_case_insensitive)]
970#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
971#[cfg_attr(
972    feature = "python",
973    pyo3::pyclass(
974        frozen,
975        eq,
976        eq_int,
977        module = "nautilus_trader.model",
978        from_py_object,
979        rename_all = "SCREAMING_SNAKE_CASE",
980    )
981)]
982#[cfg_attr(
983    feature = "python",
984    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
985)]
986pub enum LiquiditySide {
987    /// No liquidity side specified.
988    NoLiquiditySide = 0,
989    /// The order passively provided liquidity to the market to complete the trade (made a market).
990    Maker = 1,
991    /// The order aggressively took liquidity from the market to complete the trade.
992    Taker = 2,
993}
994
995/// The status of an individual market on a trading venue.
996#[repr(C)]
997#[derive(
998    Copy,
999    Clone,
1000    Debug,
1001    Display,
1002    Hash,
1003    PartialEq,
1004    Eq,
1005    PartialOrd,
1006    Ord,
1007    AsRefStr,
1008    FromRepr,
1009    EnumIter,
1010    EnumString,
1011)]
1012#[strum(ascii_case_insensitive)]
1013#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
1014#[cfg_attr(
1015    feature = "python",
1016    pyo3::pyclass(
1017        frozen,
1018        eq,
1019        eq_int,
1020        module = "nautilus_trader.model",
1021        from_py_object,
1022        rename_all = "SCREAMING_SNAKE_CASE",
1023    )
1024)]
1025#[cfg_attr(
1026    feature = "python",
1027    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
1028)]
1029pub enum MarketStatus {
1030    /// The instrument is trading.
1031    Open = 1,
1032    /// Trading in the instrument has closed.
1033    Closed = 2,
1034    /// Trading in the instrument has been paused.
1035    Paused = 3,
1036    /// Trading in the instrument has been halted.
1037    Halted = 4,
1038    /// Trading in the instrument has been suspended.
1039    Suspended = 5,
1040    /// Trading in the instrument is not available.
1041    NotAvailable = 6,
1042}
1043
1044/// An action affecting the status of an individual market on a trading venue.
1045#[repr(C)]
1046#[derive(
1047    Copy,
1048    Clone,
1049    Debug,
1050    Display,
1051    Hash,
1052    PartialEq,
1053    Eq,
1054    PartialOrd,
1055    Ord,
1056    AsRefStr,
1057    FromRepr,
1058    EnumIter,
1059    EnumString,
1060)]
1061#[strum(ascii_case_insensitive)]
1062#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
1063#[cfg_attr(
1064    feature = "python",
1065    pyo3::pyclass(
1066        frozen,
1067        eq,
1068        eq_int,
1069        module = "nautilus_trader.model",
1070        from_py_object,
1071        rename_all = "SCREAMING_SNAKE_CASE",
1072    )
1073)]
1074#[cfg_attr(
1075    feature = "python",
1076    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
1077)]
1078pub enum MarketStatusAction {
1079    /// No change.
1080    None = 0,
1081    /// The instrument is in a pre-open period.
1082    PreOpen = 1,
1083    /// The instrument is in a pre-cross period.
1084    PreCross = 2,
1085    /// The instrument is quoting but not trading.
1086    Quoting = 3,
1087    /// The instrument is in a cross/auction.
1088    Cross = 4,
1089    /// The instrument is being opened through a trading rotation.
1090    Rotation = 5,
1091    /// A new price indication is available for the instrument.
1092    NewPriceIndication = 6,
1093    /// The instrument is trading.
1094    Trading = 7,
1095    /// Trading in the instrument has been halted.
1096    Halt = 8,
1097    /// Trading in the instrument has been paused.
1098    Pause = 9,
1099    /// Trading in the instrument has been suspended.
1100    Suspend = 10,
1101    /// The instrument is in a pre-close period.
1102    PreClose = 11,
1103    /// Trading in the instrument has closed.
1104    Close = 12,
1105    /// The instrument is in a post-close period.
1106    PostClose = 13,
1107    /// A change in short-selling restrictions.
1108    ShortSellRestrictionChange = 14,
1109    /// The instrument is not available for trading, either trading has closed or been halted.
1110    NotAvailableForTrading = 15,
1111}
1112
1113/// Convert the given `value` to a [`MarketStatusAction`].
1114impl FromU16 for MarketStatusAction {
1115    fn from_u16(value: u16) -> Option<Self> {
1116        Self::from_repr(usize::from(value))
1117    }
1118}
1119
1120/// The order management system (OMS) type for a trading venue or trading strategy.
1121#[repr(C)]
1122#[derive(
1123    Copy,
1124    Clone,
1125    Debug,
1126    Default,
1127    Display,
1128    Hash,
1129    PartialEq,
1130    Eq,
1131    PartialOrd,
1132    Ord,
1133    AsRefStr,
1134    FromRepr,
1135    EnumIter,
1136    EnumString,
1137)]
1138#[strum(ascii_case_insensitive)]
1139#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
1140#[cfg_attr(
1141    feature = "python",
1142    pyo3::pyclass(
1143        frozen,
1144        eq,
1145        eq_int,
1146        module = "nautilus_trader.model",
1147        from_py_object,
1148        rename_all = "SCREAMING_SNAKE_CASE",
1149    )
1150)]
1151#[cfg_attr(
1152    feature = "python",
1153    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
1154)]
1155pub enum OmsType {
1156    /// There is no specific type of order management specified (will defer to the venue OMS).
1157    #[default]
1158    Unspecified = 0,
1159    /// The netting type where there is one position per instrument.
1160    Netting = 1,
1161    /// The hedging type where there can be multiple positions per instrument.
1162    /// This can be in LONG/SHORT directions, by position/ticket ID, or tracked virtually by
1163    /// Nautilus.
1164    Hedging = 2,
1165}
1166
1167/// The kind of option contract.
1168#[repr(C)]
1169#[derive(
1170    Copy,
1171    Clone,
1172    Debug,
1173    Display,
1174    Hash,
1175    PartialEq,
1176    Eq,
1177    PartialOrd,
1178    Ord,
1179    AsRefStr,
1180    FromRepr,
1181    EnumIter,
1182    EnumString,
1183)]
1184#[strum(ascii_case_insensitive)]
1185#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
1186#[cfg_attr(
1187    feature = "python",
1188    pyo3::pyclass(
1189        frozen,
1190        eq,
1191        eq_int,
1192        module = "nautilus_trader.model",
1193        from_py_object,
1194        rename_all = "SCREAMING_SNAKE_CASE",
1195    )
1196)]
1197#[cfg_attr(
1198    feature = "python",
1199    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
1200)]
1201pub enum OptionKind {
1202    /// A Call option gives the holder the right, but not the obligation, to buy an underlying asset at a specified strike price within a specified period of time.
1203    Call = 1,
1204    /// A Put option gives the holder the right, but not the obligation, to sell an underlying asset at a specified strike price within a specified period of time.
1205    Put = 2,
1206}
1207
1208/// Selects which option kinds an option chain carries at each strike position.
1209#[repr(C)]
1210#[derive(
1211    Copy,
1212    Clone,
1213    Debug,
1214    Default,
1215    Display,
1216    Hash,
1217    PartialEq,
1218    Eq,
1219    PartialOrd,
1220    Ord,
1221    AsRefStr,
1222    FromRepr,
1223    EnumIter,
1224    EnumString,
1225)]
1226#[strum(ascii_case_insensitive)]
1227#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
1228#[cfg_attr(
1229    feature = "python",
1230    pyo3::pyclass(
1231        frozen,
1232        eq,
1233        eq_int,
1234        module = "nautilus_trader.model",
1235        from_py_object,
1236        rename_all = "SCREAMING_SNAKE_CASE",
1237    )
1238)]
1239#[cfg_attr(
1240    feature = "python",
1241    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
1242)]
1243pub enum OptionSideFilter {
1244    /// Calls and puts at every strike.
1245    #[default]
1246    Both = 1,
1247    /// Calls only.
1248    Calls = 2,
1249    /// Puts only.
1250    Puts = 3,
1251    /// Out-of-the-money wings: puts below the ATM strike, calls above it, both at the ATM strike.
1252    Otm = 4,
1253}
1254
1255impl OptionSideFilter {
1256    /// Returns whether `kind` belongs to the chain at a strike whose ordering relative to the
1257    /// ATM strike is `position` (`Less` = below ATM, `Greater` = above ATM).
1258    #[must_use]
1259    pub fn includes(&self, kind: OptionKind, position: std::cmp::Ordering) -> bool {
1260        match self {
1261            Self::Both => true,
1262            Self::Calls => kind == OptionKind::Call,
1263            Self::Puts => kind == OptionKind::Put,
1264            Self::Otm => match position {
1265                std::cmp::Ordering::Less => kind == OptionKind::Put,
1266                std::cmp::Ordering::Greater => kind == OptionKind::Call,
1267                std::cmp::Ordering::Equal => true,
1268            },
1269        }
1270    }
1271}
1272
1273/// The numeraire convention for option greeks published by a venue.
1274///
1275/// Crypto option venues commonly publish two parallel greek sets for the same
1276/// instrument: Black-Scholes greeks in USD, and price-adjusted greeks denominated
1277/// in the underlying/coin units. Deribit and OKX both expose the distinction;
1278/// see the OKX reference for the canonical definition:
1279/// <https://www.okx.com/docs-v5/en/#public-data-websocket-option-market-data>.
1280///
1281/// This is orthogonal to the percent-greeks transformation in the internal
1282/// [`GreeksCalculator`](../../../nautilus_common/greeks/struct.GreeksCalculator.html),
1283/// which rescales the delta/gamma input step rather than the numeraire.
1284#[repr(C)]
1285#[derive(
1286    Copy,
1287    Clone,
1288    Debug,
1289    Default,
1290    Display,
1291    Hash,
1292    PartialEq,
1293    Eq,
1294    PartialOrd,
1295    Ord,
1296    AsRefStr,
1297    FromRepr,
1298    EnumIter,
1299    EnumString,
1300)]
1301#[strum(ascii_case_insensitive)]
1302#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
1303#[cfg_attr(
1304    feature = "python",
1305    pyo3::pyclass(
1306        frozen,
1307        eq,
1308        eq_int,
1309        module = "nautilus_trader.model",
1310        from_py_object,
1311        rename_all = "SCREAMING_SNAKE_CASE",
1312    )
1313)]
1314#[cfg_attr(
1315    feature = "python",
1316    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
1317)]
1318pub enum GreeksConvention {
1319    /// Black-Scholes greeks in USD.
1320    #[default]
1321    BlackScholes = 1,
1322    /// Price-adjusted greeks in the underlying/coin units.
1323    PriceAdjusted = 2,
1324}
1325
1326/// Defines when OTO (One-Triggers-Other) child orders are released.
1327#[repr(C)]
1328#[derive(
1329    Copy,
1330    Clone,
1331    Debug,
1332    Default,
1333    Display,
1334    Hash,
1335    PartialEq,
1336    Eq,
1337    PartialOrd,
1338    Ord,
1339    AsRefStr,
1340    FromRepr,
1341    EnumIter,
1342    EnumString,
1343)]
1344#[strum(ascii_case_insensitive)]
1345#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
1346#[cfg_attr(
1347    feature = "python",
1348    pyo3::pyclass(
1349        frozen,
1350        eq,
1351        eq_int,
1352        module = "nautilus_trader.model",
1353        from_py_object,
1354        rename_all = "SCREAMING_SNAKE_CASE",
1355    )
1356)]
1357#[cfg_attr(
1358    feature = "python",
1359    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
1360)]
1361pub enum OtoTriggerMode {
1362    /// Release child order(s) pro-rata to each partial fill (default).
1363    #[default]
1364    Partial = 0,
1365    /// Release child order(s) only once the parent is fully filled.
1366    Full = 1,
1367}
1368
1369/// The order side (BUY or SELL).
1370///
1371/// Python retains `NO_ORDER_SIDE` as a compatibility alias for `None`. The alias is not an enum
1372/// variant and may be removed in a future version.
1373#[repr(C)]
1374#[derive(
1375    Copy,
1376    Clone,
1377    Debug,
1378    Display,
1379    Hash,
1380    PartialEq,
1381    Eq,
1382    PartialOrd,
1383    Ord,
1384    AsRefStr,
1385    FromRepr,
1386    EnumIter,
1387    EnumString,
1388)]
1389#[strum(ascii_case_insensitive)]
1390#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
1391#[cfg_attr(
1392    feature = "python",
1393    pyo3::pyclass(
1394        frozen,
1395        eq,
1396        eq_int,
1397        module = "nautilus_trader.model",
1398        from_py_object,
1399        rename_all = "SCREAMING_SNAKE_CASE",
1400    )
1401)]
1402#[cfg_attr(
1403    feature = "python",
1404    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
1405)]
1406pub enum OrderSide {
1407    /// The order is a BUY.
1408    Buy = 1,
1409    /// The order is a SELL.
1410    Sell = 2,
1411}
1412
1413impl OrderSide {
1414    /// Returns the opposite order side.
1415    #[must_use]
1416    pub fn opposite(&self) -> Self {
1417        match &self {
1418            Self::Buy => Self::Sell,
1419            Self::Sell => Self::Buy,
1420        }
1421    }
1422}
1423
1424/// The status for a specific order.
1425///
1426/// An order is considered _open_ for the following status:
1427///  - `ACCEPTED`
1428///  - `TRIGGERED`
1429///  - `PENDING_UPDATE`
1430///  - `PENDING_CANCEL`
1431///  - `PARTIALLY_FILLED`
1432///
1433/// An order is considered _in-flight_ for the following status:
1434///  - `SUBMITTED`
1435///  - `PENDING_UPDATE`
1436///  - `PENDING_CANCEL`
1437///
1438/// An order is considered _closed_ for the following status:
1439///  - `DENIED`
1440///  - `REJECTED`
1441///  - `CANCELED`
1442///  - `EXPIRED`
1443///  - `FILLED`
1444///  - `VOIDED`
1445#[repr(C)]
1446#[derive(
1447    Copy,
1448    Clone,
1449    Debug,
1450    Display,
1451    Hash,
1452    PartialEq,
1453    Eq,
1454    PartialOrd,
1455    Ord,
1456    AsRefStr,
1457    FromRepr,
1458    EnumIter,
1459    EnumString,
1460)]
1461#[strum(ascii_case_insensitive)]
1462#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
1463#[cfg_attr(
1464    feature = "python",
1465    pyo3::pyclass(
1466        frozen,
1467        eq,
1468        eq_int,
1469        module = "nautilus_trader.model",
1470        from_py_object,
1471        rename_all = "SCREAMING_SNAKE_CASE",
1472    )
1473)]
1474#[cfg_attr(
1475    feature = "python",
1476    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
1477)]
1478pub enum OrderStatus {
1479    /// The order is initialized (instantiated) within the Nautilus system.
1480    Initialized = 1,
1481    /// The order was denied by the Nautilus system, either for being invalid, unprocessable, or exceeding a risk limit.
1482    Denied = 2,
1483    /// The order became emulated by the Nautilus system in the `OrderEmulator` component.
1484    Emulated = 3,
1485    /// The order was released by the Nautilus system from the `OrderEmulator` component.
1486    Released = 4,
1487    /// The order was submitted by the Nautilus system to the external service or trading venue (awaiting acknowledgement).
1488    Submitted = 5,
1489    /// The order was acknowledged by the trading venue as being received and valid (may now be working).
1490    Accepted = 6,
1491    /// The order was rejected by the trading venue.
1492    Rejected = 7,
1493    /// The order was canceled (closed/done).
1494    Canceled = 8,
1495    /// The order reached a GTD expiration (closed/done).
1496    Expired = 9,
1497    /// The order STOP price was triggered on a trading venue.
1498    Triggered = 10,
1499    /// The order is currently pending a request to modify on a trading venue.
1500    PendingUpdate = 11,
1501    /// The order is currently pending a request to cancel on a trading venue.
1502    PendingCancel = 12,
1503    /// The order has been partially filled on a trading venue.
1504    PartiallyFilled = 13,
1505    /// The order has been completely filled on a trading venue (closed/done).
1506    Filled = 14,
1507    /// The order is terminal after an authoritative venue void or fill correction.
1508    Voided = 15,
1509}
1510
1511impl OrderStatus {
1512    /// Returns whether the order status represents an open (working) order at the venue.
1513    ///
1514    /// This excludes `Submitted`, which is in-flight rather than working. When filtering venue
1515    /// order status reports for orders the venue still holds, use `is_open() || is_inflight()`:
1516    /// a venue that reports a resting order as pending maps it to `Submitted`, and testing
1517    /// `is_open()` alone silently drops it from reconciliation.
1518    #[must_use]
1519    pub const fn is_open(self) -> bool {
1520        matches!(
1521            self,
1522            Self::Accepted
1523                | Self::Triggered
1524                | Self::PendingUpdate
1525                | Self::PendingCancel
1526                | Self::PartiallyFilled
1527        )
1528    }
1529
1530    /// Returns whether the order status represents a terminal (closed) state.
1531    #[must_use]
1532    pub const fn is_closed(self) -> bool {
1533        matches!(
1534            self,
1535            Self::Denied
1536                | Self::Rejected
1537                | Self::Canceled
1538                | Self::Expired
1539                | Self::Filled
1540                | Self::Voided
1541        )
1542    }
1543
1544    /// Returns whether the order status represents an in-flight request to the venue.
1545    ///
1546    /// `PENDING_UPDATE` and `PENDING_CANCEL` are both open and in-flight: the order is working at
1547    /// the venue while a modify or cancel request is outstanding.
1548    #[must_use]
1549    pub const fn is_inflight(self) -> bool {
1550        matches!(
1551            self,
1552            Self::Submitted | Self::PendingUpdate | Self::PendingCancel
1553        )
1554    }
1555
1556    /// Returns whether the order can be cancelled from this status.
1557    #[must_use]
1558    pub const fn is_cancellable(self) -> bool {
1559        matches!(
1560            self,
1561            Self::Accepted | Self::Triggered | Self::PendingUpdate | Self::PartiallyFilled
1562        )
1563    }
1564}
1565
1566/// The type of order.
1567#[repr(C)]
1568#[derive(
1569    Copy,
1570    Clone,
1571    Debug,
1572    Display,
1573    Hash,
1574    PartialEq,
1575    Eq,
1576    PartialOrd,
1577    Ord,
1578    AsRefStr,
1579    FromRepr,
1580    EnumIter,
1581    EnumString,
1582)]
1583#[strum(ascii_case_insensitive)]
1584#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
1585#[cfg_attr(
1586    feature = "python",
1587    pyo3::pyclass(
1588        frozen,
1589        eq,
1590        eq_int,
1591        module = "nautilus_trader.model",
1592        from_py_object,
1593        rename_all = "SCREAMING_SNAKE_CASE",
1594    )
1595)]
1596#[cfg_attr(
1597    feature = "python",
1598    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
1599)]
1600pub enum OrderType {
1601    /// A market order to buy or sell at the best available price in the current market.
1602    Market = 1,
1603    /// A limit order to buy or sell at a specific price or better.
1604    Limit = 2,
1605    /// A stop market order to buy or sell once the price reaches the specified stop/trigger price. When the stop price is reached, the order effectively becomes a market order.
1606    StopMarket = 3,
1607    /// A stop limit order to buy or sell which combines the features of a stop order and a limit order. Once the stop/trigger price is reached, a stop-limit order effectively becomes a limit order.
1608    StopLimit = 4,
1609    /// A market-to-limit order is a market order that is to be executed as a limit order at the current best market price after reaching the market.
1610    MarketToLimit = 5,
1611    /// A market-if-touched order effectively becomes a market order when the specified trigger price is reached.
1612    MarketIfTouched = 6,
1613    /// A limit-if-touched order effectively becomes a limit order when the specified trigger price is reached.
1614    LimitIfTouched = 7,
1615    /// A trailing stop market order sets the stop/trigger price at a fixed "trailing offset" amount from the market.
1616    TrailingStopMarket = 8,
1617    /// A trailing stop limit order combines the features of a trailing stop order with those of a limit order.
1618    TrailingStopLimit = 9,
1619}
1620
1621/// The type of position adjustment.
1622#[repr(C)]
1623#[derive(
1624    Copy,
1625    Clone,
1626    Debug,
1627    Display,
1628    Hash,
1629    PartialEq,
1630    Eq,
1631    PartialOrd,
1632    Ord,
1633    AsRefStr,
1634    FromRepr,
1635    EnumIter,
1636    EnumString,
1637)]
1638#[strum(ascii_case_insensitive)]
1639#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
1640#[cfg_attr(
1641    feature = "python",
1642    pyo3::pyclass(
1643        frozen,
1644        eq,
1645        eq_int,
1646        module = "nautilus_trader.model",
1647        from_py_object,
1648        rename_all = "SCREAMING_SNAKE_CASE",
1649    )
1650)]
1651#[cfg_attr(
1652    feature = "python",
1653    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
1654)]
1655pub enum PositionAdjustmentType {
1656    /// Commission adjustment affecting position quantity.
1657    Commission = 1,
1658    /// Funding payment affecting position realized PnL.
1659    Funding = 2,
1660}
1661
1662impl FromU8 for PositionAdjustmentType {
1663    fn from_u8(value: u8) -> Option<Self> {
1664        Self::from_repr(usize::from(value))
1665    }
1666}
1667
1668/// The position side (FLAT, LONG, or SHORT).
1669///
1670/// Python retains `NO_POSITION_SIDE` as a compatibility alias for `None`. The alias is not an enum
1671/// variant and may be removed in a future version.
1672#[repr(C)]
1673#[derive(
1674    Copy,
1675    Clone,
1676    Debug,
1677    Display,
1678    Hash,
1679    PartialEq,
1680    Eq,
1681    PartialOrd,
1682    Ord,
1683    AsRefStr,
1684    FromRepr,
1685    EnumIter,
1686    EnumString,
1687)]
1688#[strum(ascii_case_insensitive)]
1689#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
1690#[cfg_attr(
1691    feature = "python",
1692    pyo3::pyclass(
1693        frozen,
1694        eq,
1695        eq_int,
1696        module = "nautilus_trader.model",
1697        from_py_object,
1698        rename_all = "SCREAMING_SNAKE_CASE",
1699    )
1700)]
1701#[cfg_attr(
1702    feature = "python",
1703    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
1704)]
1705pub enum PositionSide {
1706    /// A neutral/flat position, where no position is currently held in the market.
1707    Flat = 1,
1708    /// A long position in the market, typically acquired through one or many BUY orders.
1709    Long = 2,
1710    /// A short position in the market, typically acquired through one or many SELL orders.
1711    Short = 3,
1712}
1713
1714/// Serde compatibility for an optional order side previously encoded with `NO_ORDER_SIDE`.
1715pub mod serde_option_order_side {
1716    use serde::{Deserializer, Serializer};
1717
1718    use super::{OrderSide, deserialize_optional_enum, serialize_optional_enum};
1719
1720    /// Serializes an optional order side using the legacy no-side token.
1721    ///
1722    /// # Errors
1723    ///
1724    /// Returns an error if the serializer cannot encode the value.
1725    pub fn serialize<S>(value: &Option<OrderSide>, serializer: S) -> Result<S::Ok, S::Error>
1726    where
1727        S: Serializer,
1728    {
1729        serialize_optional_enum(value.as_ref(), serializer, "NO_ORDER_SIDE")
1730    }
1731
1732    /// Deserializes an optional order side from a side token or null.
1733    ///
1734    /// # Errors
1735    ///
1736    /// Returns an error if the input is not a valid order side.
1737    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<OrderSide>, D::Error>
1738    where
1739        D: Deserializer<'de>,
1740    {
1741        deserialize_optional_enum(
1742            deserializer,
1743            "NO_ORDER_SIDE",
1744            "BUY, SELL, NO_ORDER_SIDE, or null",
1745        )
1746    }
1747}
1748
1749/// Serde compatibility for an optional position side previously encoded with `NO_POSITION_SIDE`.
1750pub mod serde_option_position_side {
1751    use serde::{Deserializer, Serializer};
1752
1753    use super::{PositionSide, deserialize_optional_enum, serialize_optional_enum};
1754
1755    /// Serializes an optional position side using the legacy no-side token.
1756    ///
1757    /// # Errors
1758    ///
1759    /// Returns an error if the serializer cannot encode the value.
1760    pub fn serialize<S>(value: &Option<PositionSide>, serializer: S) -> Result<S::Ok, S::Error>
1761    where
1762        S: Serializer,
1763    {
1764        serialize_optional_enum(value.as_ref(), serializer, "NO_POSITION_SIDE")
1765    }
1766
1767    /// Deserializes an optional position side from a side token or null.
1768    ///
1769    /// # Errors
1770    ///
1771    /// Returns an error if the input is not a valid position side.
1772    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<PositionSide>, D::Error>
1773    where
1774        D: Deserializer<'de>,
1775    {
1776        deserialize_optional_enum(
1777            deserializer,
1778            "NO_POSITION_SIDE",
1779            "FLAT, LONG, SHORT, NO_POSITION_SIDE, or null",
1780        )
1781    }
1782}
1783
1784/// Serde compatibility for an optional contingency type previously encoded with `NO_CONTINGENCY`.
1785pub mod serde_option_contingency_type {
1786    use serde::{Deserializer, Serializer};
1787
1788    use super::{ContingencyType, deserialize_optional_enum, serialize_optional_enum};
1789
1790    /// Serializes an optional contingency type using the legacy no-contingency token.
1791    ///
1792    /// # Errors
1793    ///
1794    /// Returns an error if the serializer cannot encode the value.
1795    pub fn serialize<S>(value: &Option<ContingencyType>, serializer: S) -> Result<S::Ok, S::Error>
1796    where
1797        S: Serializer,
1798    {
1799        serialize_optional_enum(value.as_ref(), serializer, "NO_CONTINGENCY")
1800    }
1801
1802    /// Deserializes an optional contingency type from a contingency token or null.
1803    ///
1804    /// # Errors
1805    ///
1806    /// Returns an error if the input is not a valid contingency type.
1807    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<ContingencyType>, D::Error>
1808    where
1809        D: Deserializer<'de>,
1810    {
1811        deserialize_optional_enum(
1812            deserializer,
1813            "NO_CONTINGENCY",
1814            "OCO, OTO, OUO, NO_CONTINGENCY, or null",
1815        )
1816    }
1817}
1818
1819/// Serde compatibility for an optional trailing offset type previously encoded with
1820/// `NO_TRAILING_OFFSET`.
1821pub mod serde_option_trailing_offset_type {
1822    use serde::{Deserializer, Serializer};
1823
1824    use super::{TrailingOffsetType, deserialize_optional_enum, serialize_optional_enum};
1825
1826    /// Serializes an optional trailing offset type using the legacy no-offset token.
1827    ///
1828    /// # Errors
1829    ///
1830    /// Returns an error if the serializer cannot encode the value.
1831    pub fn serialize<S>(
1832        value: &Option<TrailingOffsetType>,
1833        serializer: S,
1834    ) -> Result<S::Ok, S::Error>
1835    where
1836        S: Serializer,
1837    {
1838        serialize_optional_enum(value.as_ref(), serializer, "NO_TRAILING_OFFSET")
1839    }
1840
1841    /// Deserializes an optional trailing offset type from an offset token or null.
1842    ///
1843    /// # Errors
1844    ///
1845    /// Returns an error if the input is not a valid trailing offset type.
1846    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<TrailingOffsetType>, D::Error>
1847    where
1848        D: Deserializer<'de>,
1849    {
1850        deserialize_optional_enum(
1851            deserializer,
1852            "NO_TRAILING_OFFSET",
1853            "PRICE, BASIS_POINTS, TICKS, PRICE_TIER, NO_TRAILING_OFFSET, or null",
1854        )
1855    }
1856}
1857
1858/// Serde compatibility for an optional trigger type previously encoded with `NO_TRIGGER`.
1859pub mod serde_option_trigger_type {
1860    use serde::{Deserializer, Serializer};
1861
1862    use super::{TriggerType, deserialize_optional_enum, serialize_optional_enum};
1863
1864    /// Serializes an optional trigger type using the legacy no-trigger token.
1865    ///
1866    /// # Errors
1867    ///
1868    /// Returns an error if the serializer cannot encode the value.
1869    pub fn serialize<S>(value: &Option<TriggerType>, serializer: S) -> Result<S::Ok, S::Error>
1870    where
1871        S: Serializer,
1872    {
1873        serialize_optional_enum(value.as_ref(), serializer, "NO_TRIGGER")
1874    }
1875
1876    /// Deserializes an optional trigger type from a trigger token or null.
1877    ///
1878    /// # Errors
1879    ///
1880    /// Returns an error if the input is not a valid trigger type.
1881    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<TriggerType>, D::Error>
1882    where
1883        D: Deserializer<'de>,
1884    {
1885        deserialize_optional_enum(
1886            deserializer,
1887            "NO_TRIGGER",
1888            "a trigger type, NO_TRIGGER, or null",
1889        )
1890    }
1891}
1892
1893fn serialize_optional_enum<S, T>(
1894    value: Option<&T>,
1895    serializer: S,
1896    none_token: &'static str,
1897) -> Result<S::Ok, S::Error>
1898where
1899    S: Serializer,
1900    T: AsRef<str>,
1901{
1902    serializer.serialize_str(value.map_or(none_token, AsRef::as_ref))
1903}
1904
1905fn deserialize_optional_enum<'de, D, T>(
1906    deserializer: D,
1907    none_token: &'static str,
1908    expected: &'static str,
1909) -> Result<Option<T>, D::Error>
1910where
1911    D: Deserializer<'de>,
1912    T: FromStr,
1913    T::Err: Display,
1914{
1915    struct OptionalEnumVisitor<T> {
1916        none_token: &'static str,
1917        expected: &'static str,
1918        marker: PhantomData<T>,
1919    }
1920
1921    impl<'de, T> serde::de::Visitor<'de> for OptionalEnumVisitor<T>
1922    where
1923        T: FromStr,
1924        T::Err: Display,
1925    {
1926        type Value = Option<T>;
1927
1928        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1929            formatter.write_str(self.expected)
1930        }
1931
1932        fn visit_none<E>(self) -> Result<Self::Value, E> {
1933            Ok(None)
1934        }
1935
1936        fn visit_unit<E>(self) -> Result<Self::Value, E> {
1937            Ok(None)
1938        }
1939
1940        fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1941        where
1942            D: Deserializer<'de>,
1943        {
1944            let value = Cow::<'de, str>::deserialize(deserializer)?;
1945            if value.eq_ignore_ascii_case(self.none_token) {
1946                Ok(None)
1947            } else {
1948                T::from_str(&value)
1949                    .map(Some)
1950                    .map_err(serde::de::Error::custom)
1951            }
1952        }
1953    }
1954
1955    deserializer.deserialize_option(OptionalEnumVisitor {
1956        none_token,
1957        expected,
1958        marker: PhantomData,
1959    })
1960}
1961
1962/// The type of price for an instrument in a market.
1963#[repr(C)]
1964#[derive(
1965    Copy,
1966    Clone,
1967    Debug,
1968    Display,
1969    Hash,
1970    PartialEq,
1971    Eq,
1972    PartialOrd,
1973    Ord,
1974    AsRefStr,
1975    FromRepr,
1976    EnumIter,
1977    EnumString,
1978)]
1979#[strum(ascii_case_insensitive)]
1980#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
1981#[cfg_attr(
1982    feature = "python",
1983    pyo3::pyclass(
1984        frozen,
1985        eq,
1986        eq_int,
1987        module = "nautilus_trader.model",
1988        from_py_object,
1989        rename_all = "SCREAMING_SNAKE_CASE",
1990    )
1991)]
1992#[cfg_attr(
1993    feature = "python",
1994    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
1995)]
1996pub enum PriceType {
1997    // Bar price sources are not yet consistent with mark/index price subscriptions. The open
1998    // decisions are whether to add a `PriceType::Index` variant, whether to aggregate bars
1999    // internally from mark/index updates, and what the documented source derivation order is.
2000    /// The best quoted price at which buyers are willing to buy a quantity of an instrument.
2001    /// Often considered the best bid in the order book.
2002    Bid = 1,
2003    /// The best quoted price at which sellers are willing to sell a quantity of an instrument.
2004    /// Often considered the best ask in the order book.
2005    Ask = 2,
2006    /// The arithmetic midpoint between the best bid and ask quotes.
2007    Mid = 3,
2008    /// The price at which the last trade of an instrument was executed.
2009    Last = 4,
2010    /// A reference price reflecting an instrument's fair value, often used for portfolio
2011    /// calculations and risk management.
2012    Mark = 5,
2013}
2014
2015/// A record flag bit field, indicating event end and data information.
2016#[repr(C)]
2017#[derive(
2018    Copy,
2019    Clone,
2020    Debug,
2021    Display,
2022    Hash,
2023    PartialEq,
2024    Eq,
2025    PartialOrd,
2026    Ord,
2027    AsRefStr,
2028    FromRepr,
2029    EnumIter,
2030    EnumString,
2031)]
2032#[strum(ascii_case_insensitive)]
2033#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
2034#[cfg_attr(
2035    feature = "python",
2036    pyo3::pyclass(
2037        frozen,
2038        eq,
2039        eq_int,
2040        module = "nautilus_trader.model",
2041        from_py_object,
2042        rename_all = "SCREAMING_SNAKE_CASE",
2043    )
2044)]
2045#[cfg_attr(
2046    feature = "python",
2047    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
2048)]
2049#[allow(non_camel_case_types)]
2050pub enum RecordFlag {
2051    /// Last message in the book event or packet from the venue for a given `instrument_id`.
2052    F_LAST = 1 << 7, // 128
2053    /// Top-of-book message, not an individual order.
2054    F_TOB = 1 << 6, // 64
2055    /// Message sourced from a replay, such as a snapshot server.
2056    F_SNAPSHOT = 1 << 5, // 32
2057    /// Aggregated price level message, not an individual order.
2058    F_MBP = 1 << 4, // 16
2059    /// Reserved for future use.
2060    RESERVED_2 = 1 << 3, // 8
2061    /// Reserved for future use.
2062    RESERVED_1 = 1 << 2, // 4
2063}
2064
2065impl RecordFlag {
2066    /// Checks if the flag matches a given value.
2067    #[must_use]
2068    pub fn matches(self, value: u8) -> bool {
2069        (self as u8) & value != 0
2070    }
2071}
2072
2073/// The contractual settlement of an option, independent of its exercise style.
2074#[repr(C)]
2075#[derive(
2076    Copy,
2077    Clone,
2078    Debug,
2079    Display,
2080    Hash,
2081    PartialEq,
2082    Eq,
2083    PartialOrd,
2084    Ord,
2085    AsRefStr,
2086    FromRepr,
2087    EnumIter,
2088    EnumString,
2089)]
2090#[strum(ascii_case_insensitive)]
2091#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
2092#[cfg_attr(
2093    feature = "python",
2094    pyo3::pyclass(
2095        frozen,
2096        eq,
2097        eq_int,
2098        module = "nautilus_trader.model",
2099        from_py_object,
2100        rename_all = "SCREAMING_SNAKE_CASE",
2101    )
2102)]
2103#[cfg_attr(
2104    feature = "python",
2105    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
2106)]
2107pub enum SettlementType {
2108    /// Pays the option's intrinsic value in its settlement currency.
2109    Cash = 1,
2110    /// Delivers a position in the contractual underlying instrument.
2111    Physical = 2,
2112}
2113
2114/// The 'Time in Force' instruction for an order.
2115#[repr(C)]
2116#[derive(
2117    Copy,
2118    Clone,
2119    Debug,
2120    Display,
2121    Hash,
2122    PartialEq,
2123    Eq,
2124    PartialOrd,
2125    Ord,
2126    AsRefStr,
2127    FromRepr,
2128    EnumIter,
2129    EnumString,
2130)]
2131#[strum(ascii_case_insensitive)]
2132#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
2133#[cfg_attr(
2134    feature = "python",
2135    pyo3::pyclass(
2136        frozen,
2137        eq,
2138        eq_int,
2139        module = "nautilus_trader.model",
2140        from_py_object,
2141        rename_all = "SCREAMING_SNAKE_CASE",
2142    )
2143)]
2144#[cfg_attr(
2145    feature = "python",
2146    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
2147)]
2148pub enum TimeInForce {
2149    /// Good Till Cancel (GTC) - Remains active until canceled.
2150    Gtc = 1,
2151    /// Immediate or Cancel (IOC) - Executes immediately to the extent possible, with any unfilled portion canceled.
2152    Ioc = 2,
2153    /// Fill or Kill (FOK) - Executes in its entirety immediately or is canceled if full execution is not possible.
2154    Fok = 3,
2155    /// Good Till Date (GTD) - Remains active until the specified expiration date or time is reached.
2156    Gtd = 4,
2157    /// Day - Remains active until the close of the current trading session.
2158    Day = 5,
2159    /// At the Opening (ATO) - Executes at the market opening or expires if not filled.
2160    AtTheOpen = 6,
2161    /// At the Closing (ATC) - Executes at the market close or expires if not filled.
2162    AtTheClose = 7,
2163}
2164
2165/// The trading state for a node.
2166#[repr(C)]
2167#[derive(
2168    Copy,
2169    Clone,
2170    Debug,
2171    Display,
2172    Hash,
2173    PartialEq,
2174    Eq,
2175    PartialOrd,
2176    Ord,
2177    AsRefStr,
2178    FromRepr,
2179    EnumIter,
2180    EnumString,
2181)]
2182#[strum(ascii_case_insensitive)]
2183#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
2184#[cfg_attr(
2185    feature = "python",
2186    pyo3::pyclass(
2187        frozen,
2188        eq,
2189        eq_int,
2190        module = "nautilus_trader.model",
2191        from_py_object,
2192        rename_all = "SCREAMING_SNAKE_CASE",
2193    )
2194)]
2195#[cfg_attr(
2196    feature = "python",
2197    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
2198)]
2199pub enum TradingState {
2200    /// Normal trading operations.
2201    Active = 1,
2202    /// Only cancels, queries, and eligible reduce-only submissions are permitted.
2203    Reducing = 2,
2204    /// Only cancels and queries are permitted.
2205    Halted = 3,
2206}
2207
2208/// The trailing offset type for an order type which specifies a trailing stop/trigger or limit price.
2209///
2210/// Python retains `NO_TRAILING_OFFSET` as a compatibility alias for `None`. The alias is not an enum
2211/// variant and may be removed in a future version.
2212#[repr(C)]
2213#[derive(
2214    Copy,
2215    Clone,
2216    Debug,
2217    Display,
2218    Hash,
2219    PartialEq,
2220    Eq,
2221    PartialOrd,
2222    Ord,
2223    AsRefStr,
2224    FromRepr,
2225    EnumIter,
2226    EnumString,
2227)]
2228#[strum(ascii_case_insensitive)]
2229#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
2230#[cfg_attr(
2231    feature = "python",
2232    pyo3::pyclass(
2233        frozen,
2234        eq,
2235        eq_int,
2236        module = "nautilus_trader.model",
2237        from_py_object,
2238        rename_all = "SCREAMING_SNAKE_CASE",
2239    )
2240)]
2241#[cfg_attr(
2242    feature = "python",
2243    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
2244)]
2245pub enum TrailingOffsetType {
2246    /// The trailing offset is based on a market price.
2247    Price = 1,
2248    /// The trailing offset is based on a percentage represented in basis points, of a market price.
2249    BasisPoints = 2,
2250    /// The trailing offset is based on the number of ticks from a market price.
2251    Ticks = 3,
2252    /// The trailing offset is based on a price tier set by a specific trading venue.
2253    PriceTier = 4,
2254}
2255
2256/// The trigger type for the stop/trigger price of an order.
2257///
2258/// Python retains `NO_TRIGGER` as a compatibility alias for `None`. The alias is not an enum variant
2259/// and may be removed in a future version.
2260#[repr(C)]
2261#[derive(
2262    Copy,
2263    Clone,
2264    Debug,
2265    Display,
2266    Hash,
2267    PartialEq,
2268    Eq,
2269    PartialOrd,
2270    Ord,
2271    AsRefStr,
2272    FromRepr,
2273    EnumIter,
2274    EnumString,
2275)]
2276#[strum(ascii_case_insensitive)]
2277#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
2278#[cfg_attr(
2279    feature = "python",
2280    pyo3::pyclass(
2281        frozen,
2282        eq,
2283        eq_int,
2284        module = "nautilus_trader.model",
2285        from_py_object,
2286        rename_all = "SCREAMING_SNAKE_CASE",
2287    )
2288)]
2289#[cfg_attr(
2290    feature = "python",
2291    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.model")
2292)]
2293pub enum TriggerType {
2294    /// The default trigger type set by the trading venue.
2295    Default = 1,
2296    /// Based on the last traded price for the instrument.
2297    LastPrice = 2,
2298    /// Based on the mark price for the instrument.
2299    MarkPrice = 3,
2300    /// Based on the index price for the instrument.
2301    IndexPrice = 4,
2302    /// Based on the top-of-book quoted prices for the instrument.
2303    BidAsk = 5,
2304    /// Based on a 'double match' of the last traded price for the instrument
2305    DoubleLast = 6,
2306    /// Based on a 'double match' of the bid/ask price for the instrument
2307    DoubleBidAsk = 7,
2308    /// Based on both the [`TriggerType::LastPrice`] and [`TriggerType::BidAsk`].
2309    LastOrBidAsk = 8,
2310    /// Based on the mid-point of the [`TriggerType::BidAsk`].
2311    MidPoint = 9,
2312}
2313
2314enum_strum_serde!(AccountType);
2315enum_strum_serde!(AggregationSource);
2316enum_strum_serde!(AggressorSide);
2317enum_strum_serde!(AssetClass);
2318enum_strum_serde!(AvgPxReconciliation);
2319enum_strum_serde!(BarAggregation);
2320enum_strum_serde!(BarIntervalType);
2321enum_strum_serde!(BetSide);
2322enum_strum_serde!(BookAction);
2323enum_strum_serde!(BookType);
2324enum_strum_serde!(ContingencyType);
2325enum_strum_serde!(ContinuousFutureAdjustmentType);
2326enum_strum_serde!(CurrencyType);
2327enum_strum_serde!(ExerciseStyle);
2328enum_strum_serde!(GreeksConvention);
2329enum_strum_serde!(InstrumentClass);
2330enum_strum_serde!(InstrumentCloseType);
2331enum_strum_serde!(LiquiditySide);
2332enum_strum_serde!(MarketStatus);
2333enum_strum_serde!(MarketStatusAction);
2334enum_strum_serde!(OmsType);
2335enum_strum_serde!(OptionKind);
2336enum_strum_serde!(OptionSideFilter);
2337enum_strum_serde!(OrderSide);
2338enum_strum_serde!(OrderStatus);
2339enum_strum_serde!(OrderType);
2340enum_strum_serde!(OtoTriggerMode);
2341enum_strum_serde!(PositionAdjustmentType);
2342enum_strum_serde!(PositionSide);
2343enum_strum_serde!(PriceType);
2344enum_strum_serde!(RecordFlag);
2345enum_strum_serde!(SettlementType);
2346enum_strum_serde!(TimeInForce);
2347enum_strum_serde!(TradingState);
2348enum_strum_serde!(TrailingOffsetType);
2349enum_strum_serde!(TriggerType);
2350
2351#[cfg(test)]
2352mod tests {
2353    use rstest::rstest;
2354    use serde::{Serialize, de::DeserializeOwned};
2355    use strum::IntoEnumIterator;
2356
2357    use super::*;
2358
2359    #[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
2360    struct OptionalSides {
2361        #[serde(with = "serde_option_order_side")]
2362        order: Option<OrderSide>,
2363        #[serde(with = "serde_option_position_side")]
2364        position: Option<PositionSide>,
2365    }
2366
2367    #[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
2368    struct OptionalOrderTypes {
2369        #[serde(with = "serde_option_contingency_type")]
2370        contingency: Option<ContingencyType>,
2371        #[serde(with = "serde_option_trailing_offset_type")]
2372        trailing_offset: Option<TrailingOffsetType>,
2373        #[serde(with = "serde_option_trigger_type")]
2374        trigger: Option<TriggerType>,
2375    }
2376
2377    #[rstest]
2378    fn test_optional_sides_serde_preserves_legacy_none_tokens() {
2379        let value = OptionalSides {
2380            order: None,
2381            position: None,
2382        };
2383
2384        let json = serde_json::to_string(&value).unwrap();
2385        let decoded: OptionalSides = serde_json::from_str(&json).unwrap();
2386
2387        assert_eq!(
2388            json,
2389            r#"{"order":"NO_ORDER_SIDE","position":"NO_POSITION_SIDE"}"#
2390        );
2391        assert_eq!(decoded, value);
2392    }
2393
2394    #[rstest]
2395    fn test_optional_sides_serde_accepts_null_and_valid_sides() {
2396        let json = r#"{"order":null,"position":"LONG"}"#;
2397        let decoded: OptionalSides = serde_json::from_str(json).unwrap();
2398
2399        assert_eq!(
2400            decoded,
2401            OptionalSides {
2402                order: None,
2403                position: Some(PositionSide::Long),
2404            }
2405        );
2406    }
2407
2408    #[rstest]
2409    fn test_optional_order_types_serde_preserves_legacy_none_tokens() {
2410        let value = OptionalOrderTypes {
2411            contingency: None,
2412            trailing_offset: None,
2413            trigger: None,
2414        };
2415
2416        let json = serde_json::to_string(&value).unwrap();
2417        let decoded: OptionalOrderTypes = serde_json::from_str(&json).unwrap();
2418
2419        assert_eq!(
2420            json,
2421            r#"{"contingency":"NO_CONTINGENCY","trailing_offset":"NO_TRAILING_OFFSET","trigger":"NO_TRIGGER"}"#,
2422        );
2423        assert_eq!(decoded, value);
2424    }
2425
2426    #[rstest]
2427    fn test_optional_order_types_serde_accepts_null_and_valid_values() {
2428        let json = r#"{"contingency":null,"trailing_offset":"PRICE","trigger":"LAST_PRICE"}"#;
2429        let decoded: OptionalOrderTypes = serde_json::from_str(json).unwrap();
2430
2431        assert_eq!(
2432            decoded,
2433            OptionalOrderTypes {
2434                contingency: None,
2435                trailing_offset: Some(TrailingOffsetType::Price),
2436                trigger: Some(TriggerType::LastPrice),
2437            },
2438        );
2439    }
2440
2441    #[rstest]
2442    #[case(r#"{"contingency":"INVALID","trailing_offset":"NO_TRAILING_OFFSET","trigger":"NO_TRIGGER"}"#)]
2443    #[case(
2444        r#"{"contingency":"NO_CONTINGENCY","trailing_offset":"INVALID","trigger":"NO_TRIGGER"}"#
2445    )]
2446    #[case(r#"{"contingency":"NO_CONTINGENCY","trailing_offset":"NO_TRAILING_OFFSET","trigger":"INVALID"}"#)]
2447    fn test_optional_order_types_serde_rejects_invalid_values(#[case] json: &str) {
2448        assert!(serde_json::from_str::<OptionalOrderTypes>(json).is_err());
2449    }
2450
2451    #[rstest]
2452    #[case::bet_side_back(BetSide::Back, r#""BACK""#)]
2453    #[case::bet_side_lay(BetSide::Lay, r#""LAY""#)]
2454    fn test_bet_side_serde_uses_canonical_label(#[case] value: BetSide, #[case] expected: &str) {
2455        let json = serde_json::to_string(&value).unwrap();
2456
2457        assert_eq!(json, expected);
2458        assert_eq!(serde_json::from_str::<BetSide>(&json).unwrap(), value);
2459    }
2460
2461    #[rstest]
2462    #[case::oto_trigger_mode_partial(OtoTriggerMode::Partial, r#""PARTIAL""#)]
2463    #[case::oto_trigger_mode_full(OtoTriggerMode::Full, r#""FULL""#)]
2464    fn test_oto_trigger_mode_serde_uses_canonical_label(
2465        #[case] value: OtoTriggerMode,
2466        #[case] expected: &str,
2467    ) {
2468        let json = serde_json::to_string(&value).unwrap();
2469
2470        assert_eq!(json, expected);
2471        assert_eq!(
2472            serde_json::from_str::<OtoTriggerMode>(&json).unwrap(),
2473            value
2474        );
2475    }
2476
2477    #[rstest]
2478    #[case::pascal(r#""Back""#, BetSide::Back)]
2479    #[case::lower(r#""lay""#, BetSide::Lay)]
2480    fn test_bet_side_serde_is_case_insensitive(#[case] json: &str, #[case] expected: BetSide) {
2481        assert_eq!(serde_json::from_str::<BetSide>(json).unwrap(), expected);
2482    }
2483
2484    #[rstest]
2485    #[case::wrong_domain(r#""BUY""#)]
2486    #[case::empty(r#""""#)]
2487    fn test_bet_side_serde_rejects_unknown_label(#[case] json: &str) {
2488        assert!(serde_json::from_str::<BetSide>(json).is_err());
2489    }
2490
2491    #[rstest]
2492    #[case::no_aggressor(0, Some(AggressorSide::NoAggressor))]
2493    #[case::buy(1, Some(AggressorSide::Buy))]
2494    #[case::sell(2, Some(AggressorSide::Sell))]
2495    #[case::invalid(3, None)]
2496    #[case::max_u8(255, None)]
2497    fn test_aggressor_side_from_u8(#[case] value: u8, #[case] expected: Option<AggressorSide>) {
2498        assert_eq!(AggressorSide::from_u8(value), expected);
2499    }
2500
2501    #[rstest]
2502    #[case::active(TradingState::Active, 1)]
2503    #[case::reducing(TradingState::Reducing, 2)]
2504    #[case::halted(TradingState::Halted, 3)]
2505    fn test_trading_state_discriminants(#[case] state: TradingState, #[case] value: usize) {
2506        assert_eq!(state as usize, value);
2507        assert_eq!(TradingState::from_repr(value), Some(state));
2508    }
2509
2510    #[rstest]
2511    #[case(AggressorSide::NoAggressor, "NO_AGGRESSOR")]
2512    #[case(AggressorSide::Buy, "BUY")]
2513    #[case(AggressorSide::Sell, "SELL")]
2514    fn test_aggressor_side_to_string(#[case] value: AggressorSide, #[case] expected: &str) {
2515        assert_eq!(value.to_string(), expected);
2516        assert_eq!(value.as_ref(), expected);
2517    }
2518
2519    #[rstest]
2520    #[case(AggressorSide::NoAggressor, "NO_AGGRESSOR")]
2521    #[case(AggressorSide::Buy, "BUY")]
2522    #[case(AggressorSide::Sell, "SELL")]
2523    #[case(AggressorSide::Buy, "BUYER")]
2524    #[case(AggressorSide::Sell, "SELLER")]
2525    #[case(AggressorSide::Buy, "buy")]
2526    #[case(AggressorSide::Sell, "seller")]
2527    fn test_aggressor_side_from_str(#[case] expected: AggressorSide, #[case] value: &str) {
2528        assert_eq!(AggressorSide::from_str(value), Ok(expected));
2529    }
2530
2531    #[rstest]
2532    #[case(AggressorSide::Buy, "\"BUY\"")]
2533    #[case(AggressorSide::Sell, "\"SELL\"")]
2534    #[case(AggressorSide::NoAggressor, "\"NO_AGGRESSOR\"")]
2535    fn test_aggressor_side_serde_roundtrip(#[case] input: AggressorSide, #[case] expected: &str) {
2536        let json = serde_json::to_string(&input).unwrap();
2537        assert_eq!(json, expected);
2538        let parsed: AggressorSide = serde_json::from_str(expected).unwrap();
2539        assert_eq!(parsed, input);
2540    }
2541
2542    #[rstest]
2543    #[case("BUYER", AggressorSide::Buy)]
2544    #[case("SELLER", AggressorSide::Sell)]
2545    fn test_aggressor_side_serde_accepts_historical(
2546        #[case] value: &str,
2547        #[case] expected: AggressorSide,
2548    ) {
2549        let parsed: AggressorSide = serde_json::from_str(&format!("\"{value}\"")).unwrap();
2550        assert_eq!(parsed, expected);
2551    }
2552
2553    #[rstest]
2554    #[case(GreeksConvention::BlackScholes, "\"BLACK_SCHOLES\"")]
2555    #[case(GreeksConvention::PriceAdjusted, "\"PRICE_ADJUSTED\"")]
2556    fn test_greeks_convention_serde_roundtrip(
2557        #[case] input: GreeksConvention,
2558        #[case] expected: &str,
2559    ) {
2560        let json = serde_json::to_string(&input).unwrap();
2561        assert_eq!(json, expected);
2562        let parsed: GreeksConvention = serde_json::from_str(expected).unwrap();
2563        assert_eq!(parsed, input);
2564    }
2565
2566    #[rstest]
2567    fn test_greeks_convention_default_is_black_scholes() {
2568        assert_eq!(GreeksConvention::default(), GreeksConvention::BlackScholes);
2569    }
2570
2571    #[rstest]
2572    #[case(ContinuousFutureAdjustmentType::BackwardSpread, false, true)]
2573    #[case(ContinuousFutureAdjustmentType::ForwardSpread, false, false)]
2574    #[case(ContinuousFutureAdjustmentType::BackwardRatio, true, true)]
2575    #[case(ContinuousFutureAdjustmentType::ForwardRatio, true, false)]
2576    fn test_continuous_future_adjustment_type_predicates(
2577        #[case] mode: ContinuousFutureAdjustmentType,
2578        #[case] expected_is_ratio: bool,
2579        #[case] expected_is_backward: bool,
2580    ) {
2581        assert_eq!(mode.is_ratio(), expected_is_ratio);
2582        assert_eq!(mode.is_backward(), expected_is_backward);
2583    }
2584
2585    #[rstest]
2586    #[case(ContinuousFutureAdjustmentType::BackwardSpread, "\"BACKWARD_SPREAD\"")]
2587    #[case(ContinuousFutureAdjustmentType::ForwardSpread, "\"FORWARD_SPREAD\"")]
2588    #[case(ContinuousFutureAdjustmentType::BackwardRatio, "\"BACKWARD_RATIO\"")]
2589    #[case(ContinuousFutureAdjustmentType::ForwardRatio, "\"FORWARD_RATIO\"")]
2590    fn test_continuous_future_adjustment_type_serde_roundtrip(
2591        #[case] input: ContinuousFutureAdjustmentType,
2592        #[case] expected: &str,
2593    ) {
2594        let json = serde_json::to_string(&input).unwrap();
2595        assert_eq!(json, expected);
2596        let parsed: ContinuousFutureAdjustmentType = serde_json::from_str(expected).unwrap();
2597        assert_eq!(parsed, input);
2598    }
2599
2600    #[rstest]
2601    fn test_continuous_future_adjustment_type_default_is_backward_spread() {
2602        assert_eq!(
2603            ContinuousFutureAdjustmentType::default(),
2604            ContinuousFutureAdjustmentType::BackwardSpread,
2605        );
2606    }
2607
2608    #[rstest]
2609    #[case(InstrumentClass::Future, true)]
2610    #[case(InstrumentClass::Option, true)]
2611    #[case(InstrumentClass::FuturesSpread, true)]
2612    #[case(InstrumentClass::OptionSpread, true)]
2613    #[case(InstrumentClass::Spot, false)]
2614    #[case(InstrumentClass::Swap, false)]
2615    #[case(InstrumentClass::Forward, false)]
2616    #[case(InstrumentClass::Cfd, false)]
2617    #[case(InstrumentClass::Bond, false)]
2618    #[case(InstrumentClass::Warrant, false)]
2619    #[case(InstrumentClass::SportsBetting, false)]
2620    #[case(InstrumentClass::BinaryOption, false)]
2621    fn test_instrument_class_allows_negative_price(
2622        #[case] class: InstrumentClass,
2623        #[case] expected: bool,
2624    ) {
2625        assert_eq!(class.allows_negative_price(), expected);
2626    }
2627
2628    #[rstest]
2629    #[case(InstrumentClass::Option, true)]
2630    #[case(InstrumentClass::OptionSpread, true)]
2631    #[case(InstrumentClass::BinaryOption, true)]
2632    #[case(InstrumentClass::Warrant, true)]
2633    #[case(InstrumentClass::Spot, false)]
2634    #[case(InstrumentClass::Swap, false)]
2635    #[case(InstrumentClass::Future, false)]
2636    #[case(InstrumentClass::FuturesSpread, false)]
2637    #[case(InstrumentClass::Forward, false)]
2638    #[case(InstrumentClass::Cfd, false)]
2639    #[case(InstrumentClass::Bond, false)]
2640    #[case(InstrumentClass::SportsBetting, false)]
2641    fn test_instrument_class_is_premium_based(
2642        #[case] class: InstrumentClass,
2643        #[case] expected: bool,
2644    ) {
2645        assert_eq!(class.is_premium_based(), expected);
2646    }
2647
2648    #[rstest]
2649    #[case(InstrumentClass::Option, true, false)]
2650    #[case(InstrumentClass::OptionSpread, true, false)]
2651    #[case(InstrumentClass::BinaryOption, true, false)]
2652    #[case(InstrumentClass::Warrant, true, false)]
2653    #[case(InstrumentClass::Spot, true, true)]
2654    #[case(InstrumentClass::Swap, true, true)]
2655    #[case(InstrumentClass::Future, true, true)]
2656    #[case(InstrumentClass::FuturesSpread, true, true)]
2657    #[case(InstrumentClass::Forward, true, true)]
2658    #[case(InstrumentClass::Cfd, true, true)]
2659    #[case(InstrumentClass::Bond, true, true)]
2660    #[case(InstrumentClass::SportsBetting, true, true)]
2661    #[case(InstrumentClass::Future, false, false)]
2662    #[case(InstrumentClass::Option, false, false)]
2663    fn test_instrument_class_divides_notional_by_price(
2664        #[case] class: InstrumentClass,
2665        #[case] is_inverse: bool,
2666        #[case] expected: bool,
2667    ) {
2668        assert_eq!(class.divides_notional_by_price(is_inverse), expected);
2669    }
2670
2671    #[rstest]
2672    #[case("FUT", Some(InstrumentClass::Future))]
2673    #[case("FUTURE", Some(InstrumentClass::Future))]
2674    #[case("OPT", Some(InstrumentClass::Option))]
2675    #[case("OPTION", Some(InstrumentClass::Option))]
2676    #[case("fut", None)]
2677    #[case("Fut", None)]
2678    #[case("option", None)]
2679    #[case("Option", None)]
2680    #[case("SPREAD", None)]
2681    #[case("UNKNOWN", None)]
2682    #[case("", None)]
2683    fn test_instrument_class_try_from_parent_suffix(
2684        #[case] suffix: &str,
2685        #[case] expected: Option<InstrumentClass>,
2686    ) {
2687        assert_eq!(InstrumentClass::try_from_parent_suffix(suffix), expected);
2688    }
2689
2690    #[rstest]
2691    #[case(InstrumentClass::Future, Some("FUT"))]
2692    #[case(InstrumentClass::Option, Some("OPT"))]
2693    #[case(InstrumentClass::Spot, None)]
2694    #[case(InstrumentClass::Swap, None)]
2695    #[case(InstrumentClass::FuturesSpread, None)]
2696    #[case(InstrumentClass::Forward, None)]
2697    #[case(InstrumentClass::Cfd, None)]
2698    #[case(InstrumentClass::Bond, None)]
2699    #[case(InstrumentClass::OptionSpread, None)]
2700    #[case(InstrumentClass::Warrant, None)]
2701    #[case(InstrumentClass::SportsBetting, None)]
2702    #[case(InstrumentClass::BinaryOption, None)]
2703    fn test_instrument_class_parent_suffix(
2704        #[case] class: InstrumentClass,
2705        #[case] expected: Option<&'static str>,
2706    ) {
2707        assert_eq!(class.parent_suffix(), expected);
2708    }
2709
2710    #[rstest]
2711    #[case(InstrumentClass::Future)]
2712    #[case(InstrumentClass::Option)]
2713    fn test_instrument_class_parent_suffix_roundtrip(#[case] class: InstrumentClass) {
2714        let suffix = class.parent_suffix().unwrap();
2715        assert_eq!(InstrumentClass::try_from_parent_suffix(suffix), Some(class));
2716    }
2717
2718    /// Asserts the string and serde contract shared by every enum registered with
2719    /// [`enum_strum_serde`]: `AsRef` and `Display` agree, parsing accepts the emitted name in any
2720    /// ASCII case, and JSON round-trips through that same name.
2721    fn assert_enum_string_contract<T>(type_name: &str)
2722    where
2723        T: IntoEnumIterator
2724            + Copy
2725            + std::fmt::Debug
2726            + PartialEq
2727            + Display
2728            + AsRef<str>
2729            + FromStr
2730            + Serialize
2731            + DeserializeOwned,
2732    {
2733        for variant in T::iter() {
2734            let wire = variant.to_string();
2735            assert_eq!(
2736                variant.as_ref(),
2737                wire,
2738                "{type_name}::{variant:?} must expose the same name through `AsRef` and `Display`",
2739            );
2740            assert_eq!(
2741                T::from_str(&wire).ok(),
2742                Some(variant),
2743                "{type_name} must parse `{wire}` back to {variant:?}",
2744            );
2745            assert_eq!(
2746                T::from_str(&wire.to_ascii_lowercase()).ok(),
2747                Some(variant),
2748                "{type_name} must parse `{wire}` case-insensitively",
2749            );
2750            let json = serde_json::to_string(&variant).unwrap();
2751            assert_eq!(
2752                json,
2753                format!("\"{wire}\""),
2754                "{type_name}::{variant:?} must serialize as its display name",
2755            );
2756            assert_eq!(
2757                serde_json::from_str::<T>(&json).unwrap(),
2758                variant,
2759                "{type_name}::{variant:?} must round-trip through JSON",
2760            );
2761        }
2762    }
2763
2764    #[rstest]
2765    fn test_enum_string_and_serde_contract() {
2766        macro_rules! assert_contract {
2767            ($($t:ty),+ $(,)?) => {
2768                $(assert_enum_string_contract::<$t>(stringify!($t));)+
2769            };
2770        }
2771
2772        assert_contract!(
2773            AccountType,
2774            AggregationSource,
2775            AggressorSide,
2776            AssetClass,
2777            AvgPxReconciliation,
2778            BarAggregation,
2779            BarIntervalType,
2780            BetSide,
2781            BookAction,
2782            BookType,
2783            ContingencyType,
2784            ContinuousFutureAdjustmentType,
2785            CurrencyType,
2786            ExerciseStyle,
2787            GreeksConvention,
2788            InstrumentClass,
2789            InstrumentCloseType,
2790            LiquiditySide,
2791            MarketStatus,
2792            MarketStatusAction,
2793            OmsType,
2794            OptionKind,
2795            OrderSide,
2796            OrderStatus,
2797            OrderType,
2798            OtoTriggerMode,
2799            PositionAdjustmentType,
2800            PositionSide,
2801            PriceType,
2802            RecordFlag,
2803            SettlementType,
2804            TimeInForce,
2805            TradingState,
2806            TrailingOffsetType,
2807            TriggerType,
2808        );
2809    }
2810
2811    /// Every enum variant's wire name, as `Type::Variant=NAME`.
2812    ///
2813    /// These names are persisted in catalogs and exchanged with adapters and the Python bindings,
2814    /// so a variant rename or a change to strum's casing rules must be a deliberate edit here.
2815    const EXPECTED_WIRE_NAMES: &[&str] = &[
2816        "AccountType::Betting=BETTING",
2817        "AccountType::Cash=CASH",
2818        "AccountType::Margin=MARGIN",
2819        "AccountType::Wallet=WALLET",
2820        "AggregationSource::External=EXTERNAL",
2821        "AggregationSource::Internal=INTERNAL",
2822        "AggressorSide::Buy=BUY",
2823        "AggressorSide::NoAggressor=NO_AGGRESSOR",
2824        "AggressorSide::Sell=SELL",
2825        "AssetClass::Alternative=ALTERNATIVE",
2826        "AssetClass::Commodity=COMMODITY",
2827        "AssetClass::Cryptocurrency=CRYPTOCURRENCY",
2828        "AssetClass::Debt=DEBT",
2829        "AssetClass::Equity=EQUITY",
2830        "AssetClass::FX=FX",
2831        "AssetClass::Index=INDEX",
2832        "AvgPxReconciliation::Match=MATCH",
2833        "AvgPxReconciliation::OpeningOnly=OPENING_ONLY",
2834        "BarAggregation::Day=DAY",
2835        "BarAggregation::Hour=HOUR",
2836        "BarAggregation::Millisecond=MILLISECOND",
2837        "BarAggregation::Minute=MINUTE",
2838        "BarAggregation::Month=MONTH",
2839        "BarAggregation::Renko=RENKO",
2840        "BarAggregation::Second=SECOND",
2841        "BarAggregation::Tick=TICK",
2842        "BarAggregation::TickImbalance=TICK_IMBALANCE",
2843        "BarAggregation::TickRuns=TICK_RUNS",
2844        "BarAggregation::Value=VALUE",
2845        "BarAggregation::ValueImbalance=VALUE_IMBALANCE",
2846        "BarAggregation::ValueRuns=VALUE_RUNS",
2847        "BarAggregation::Volume=VOLUME",
2848        "BarAggregation::VolumeImbalance=VOLUME_IMBALANCE",
2849        "BarAggregation::VolumeRuns=VOLUME_RUNS",
2850        "BarAggregation::Week=WEEK",
2851        "BarAggregation::Year=YEAR",
2852        "BarIntervalType::LeftOpen=LEFT_OPEN",
2853        "BarIntervalType::RightOpen=RIGHT_OPEN",
2854        "BetSide::Back=BACK",
2855        "BetSide::Lay=LAY",
2856        "BookAction::Add=ADD",
2857        "BookAction::Clear=CLEAR",
2858        "BookAction::Delete=DELETE",
2859        "BookAction::Update=UPDATE",
2860        "BookType::L1_MBP=L1_MBP",
2861        "BookType::L2_MBP=L2_MBP",
2862        "BookType::L3_MBO=L3_MBO",
2863        "ContingencyType::Oco=OCO",
2864        "ContingencyType::Oto=OTO",
2865        "ContingencyType::Ouo=OUO",
2866        "ContinuousFutureAdjustmentType::BackwardRatio=BACKWARD_RATIO",
2867        "ContinuousFutureAdjustmentType::BackwardSpread=BACKWARD_SPREAD",
2868        "ContinuousFutureAdjustmentType::ForwardRatio=FORWARD_RATIO",
2869        "ContinuousFutureAdjustmentType::ForwardSpread=FORWARD_SPREAD",
2870        "CurrencyType::CommodityBacked=COMMODITY_BACKED",
2871        "CurrencyType::Crypto=CRYPTO",
2872        "CurrencyType::Fiat=FIAT",
2873        "ExerciseStyle::American=AMERICAN",
2874        "ExerciseStyle::Bermudan=BERMUDAN",
2875        "ExerciseStyle::European=EUROPEAN",
2876        "GreeksConvention::BlackScholes=BLACK_SCHOLES",
2877        "GreeksConvention::PriceAdjusted=PRICE_ADJUSTED",
2878        "InstrumentClass::BinaryOption=BINARY_OPTION",
2879        "InstrumentClass::Bond=BOND",
2880        "InstrumentClass::Cfd=CFD",
2881        "InstrumentClass::Forward=FORWARD",
2882        "InstrumentClass::Future=FUTURE",
2883        "InstrumentClass::FuturesSpread=FUTURES_SPREAD",
2884        "InstrumentClass::Option=OPTION",
2885        "InstrumentClass::OptionSpread=OPTION_SPREAD",
2886        "InstrumentClass::SportsBetting=SPORTS_BETTING",
2887        "InstrumentClass::Spot=SPOT",
2888        "InstrumentClass::Swap=SWAP",
2889        "InstrumentClass::Warrant=WARRANT",
2890        "InstrumentCloseType::ContractExpired=CONTRACT_EXPIRED",
2891        "InstrumentCloseType::EndOfSession=END_OF_SESSION",
2892        "LiquiditySide::Maker=MAKER",
2893        "LiquiditySide::NoLiquiditySide=NO_LIQUIDITY_SIDE",
2894        "LiquiditySide::Taker=TAKER",
2895        "MarketStatus::Closed=CLOSED",
2896        "MarketStatus::Halted=HALTED",
2897        "MarketStatus::NotAvailable=NOT_AVAILABLE",
2898        "MarketStatus::Open=OPEN",
2899        "MarketStatus::Paused=PAUSED",
2900        "MarketStatus::Suspended=SUSPENDED",
2901        "MarketStatusAction::Close=CLOSE",
2902        "MarketStatusAction::Cross=CROSS",
2903        "MarketStatusAction::Halt=HALT",
2904        "MarketStatusAction::NewPriceIndication=NEW_PRICE_INDICATION",
2905        "MarketStatusAction::None=NONE",
2906        "MarketStatusAction::NotAvailableForTrading=NOT_AVAILABLE_FOR_TRADING",
2907        "MarketStatusAction::Pause=PAUSE",
2908        "MarketStatusAction::PostClose=POST_CLOSE",
2909        "MarketStatusAction::PreClose=PRE_CLOSE",
2910        "MarketStatusAction::PreCross=PRE_CROSS",
2911        "MarketStatusAction::PreOpen=PRE_OPEN",
2912        "MarketStatusAction::Quoting=QUOTING",
2913        "MarketStatusAction::Rotation=ROTATION",
2914        "MarketStatusAction::ShortSellRestrictionChange=SHORT_SELL_RESTRICTION_CHANGE",
2915        "MarketStatusAction::Suspend=SUSPEND",
2916        "MarketStatusAction::Trading=TRADING",
2917        "OmsType::Hedging=HEDGING",
2918        "OmsType::Netting=NETTING",
2919        "OmsType::Unspecified=UNSPECIFIED",
2920        "OptionKind::Call=CALL",
2921        "OptionKind::Put=PUT",
2922        "OrderSide::Buy=BUY",
2923        "OrderSide::Sell=SELL",
2924        "OrderStatus::Accepted=ACCEPTED",
2925        "OrderStatus::Canceled=CANCELED",
2926        "OrderStatus::Denied=DENIED",
2927        "OrderStatus::Emulated=EMULATED",
2928        "OrderStatus::Expired=EXPIRED",
2929        "OrderStatus::Filled=FILLED",
2930        "OrderStatus::Initialized=INITIALIZED",
2931        "OrderStatus::PartiallyFilled=PARTIALLY_FILLED",
2932        "OrderStatus::PendingCancel=PENDING_CANCEL",
2933        "OrderStatus::PendingUpdate=PENDING_UPDATE",
2934        "OrderStatus::Rejected=REJECTED",
2935        "OrderStatus::Released=RELEASED",
2936        "OrderStatus::Submitted=SUBMITTED",
2937        "OrderStatus::Triggered=TRIGGERED",
2938        "OrderStatus::Voided=VOIDED",
2939        "OrderType::Limit=LIMIT",
2940        "OrderType::LimitIfTouched=LIMIT_IF_TOUCHED",
2941        "OrderType::Market=MARKET",
2942        "OrderType::MarketIfTouched=MARKET_IF_TOUCHED",
2943        "OrderType::MarketToLimit=MARKET_TO_LIMIT",
2944        "OrderType::StopLimit=STOP_LIMIT",
2945        "OrderType::StopMarket=STOP_MARKET",
2946        "OrderType::TrailingStopLimit=TRAILING_STOP_LIMIT",
2947        "OrderType::TrailingStopMarket=TRAILING_STOP_MARKET",
2948        "OtoTriggerMode::Full=FULL",
2949        "OtoTriggerMode::Partial=PARTIAL",
2950        "PositionAdjustmentType::Commission=COMMISSION",
2951        "PositionAdjustmentType::Funding=FUNDING",
2952        "PositionSide::Flat=FLAT",
2953        "PositionSide::Long=LONG",
2954        "PositionSide::Short=SHORT",
2955        "PriceType::Ask=ASK",
2956        "PriceType::Bid=BID",
2957        "PriceType::Last=LAST",
2958        "PriceType::Mark=MARK",
2959        "PriceType::Mid=MID",
2960        "RecordFlag::F_LAST=F_LAST",
2961        "RecordFlag::F_MBP=F_MBP",
2962        "RecordFlag::F_SNAPSHOT=F_SNAPSHOT",
2963        "RecordFlag::F_TOB=F_TOB",
2964        "RecordFlag::RESERVED_1=RESERVED_1",
2965        "RecordFlag::RESERVED_2=RESERVED_2",
2966        "SettlementType::Cash=CASH",
2967        "SettlementType::Physical=PHYSICAL",
2968        "TimeInForce::AtTheClose=AT_THE_CLOSE",
2969        "TimeInForce::AtTheOpen=AT_THE_OPEN",
2970        "TimeInForce::Day=DAY",
2971        "TimeInForce::Fok=FOK",
2972        "TimeInForce::Gtc=GTC",
2973        "TimeInForce::Gtd=GTD",
2974        "TimeInForce::Ioc=IOC",
2975        "TradingState::Active=ACTIVE",
2976        "TradingState::Halted=HALTED",
2977        "TradingState::Reducing=REDUCING",
2978        "TrailingOffsetType::BasisPoints=BASIS_POINTS",
2979        "TrailingOffsetType::Price=PRICE",
2980        "TrailingOffsetType::PriceTier=PRICE_TIER",
2981        "TrailingOffsetType::Ticks=TICKS",
2982        "TriggerType::BidAsk=BID_ASK",
2983        "TriggerType::Default=DEFAULT",
2984        "TriggerType::DoubleBidAsk=DOUBLE_BID_ASK",
2985        "TriggerType::DoubleLast=DOUBLE_LAST",
2986        "TriggerType::IndexPrice=INDEX_PRICE",
2987        "TriggerType::LastOrBidAsk=LAST_OR_BID_ASK",
2988        "TriggerType::LastPrice=LAST_PRICE",
2989        "TriggerType::MarkPrice=MARK_PRICE",
2990        "TriggerType::MidPoint=MID_POINT",
2991    ];
2992
2993    #[rstest]
2994    fn test_enum_wire_names_are_stable() {
2995        let mut actual = Vec::new();
2996        macro_rules! collect_wire_names {
2997            ($($t:ty),+ $(,)?) => {
2998                $(for variant in <$t>::iter() {
2999                    actual.push(format!("{}::{variant:?}={variant}", stringify!($t)));
3000                })+
3001            };
3002        }
3003
3004        collect_wire_names!(
3005            AccountType,
3006            AggregationSource,
3007            AggressorSide,
3008            AssetClass,
3009            AvgPxReconciliation,
3010            BarAggregation,
3011            BarIntervalType,
3012            BetSide,
3013            BookAction,
3014            BookType,
3015            ContingencyType,
3016            ContinuousFutureAdjustmentType,
3017            CurrencyType,
3018            ExerciseStyle,
3019            GreeksConvention,
3020            InstrumentClass,
3021            InstrumentCloseType,
3022            LiquiditySide,
3023            MarketStatus,
3024            MarketStatusAction,
3025            OmsType,
3026            OptionKind,
3027            OrderSide,
3028            OrderStatus,
3029            OrderType,
3030            OtoTriggerMode,
3031            PositionAdjustmentType,
3032            PositionSide,
3033            PriceType,
3034            RecordFlag,
3035            SettlementType,
3036            TimeInForce,
3037            TradingState,
3038            TrailingOffsetType,
3039            TriggerType,
3040        );
3041
3042        actual.sort();
3043
3044        assert_eq!(
3045            actual.len(),
3046            EXPECTED_WIRE_NAMES.len(),
3047            "variant count changed; update `EXPECTED_WIRE_NAMES`",
3048        );
3049
3050        for (got, expected) in actual.iter().zip(EXPECTED_WIRE_NAMES) {
3051            assert_eq!(got, expected);
3052        }
3053    }
3054
3055    /// Pins each numeric discriminant to its variant with literal values.
3056    ///
3057    /// These numbers are written into Parquet catalogs and SBE payloads, and `MarketStatusAction`
3058    /// additionally mirrors Databento's external DBN `StatusMsg.action` numbering. The conversions
3059    /// delegate to the derived `from_repr`, so comparing them against `from_repr` would be a
3060    /// tautology: only literal expected values catch a renumbered variant, which would otherwise
3061    /// change encode and decode together and silently misread already-persisted data.
3062    macro_rules! assert_numeric_mapping {
3063        ($t:ty, $from:ident, $width:ty, $($value:literal => $variant:expr),+ $(,)?) => {{
3064            let valid: &[$width] = &[$($value),+];
3065            $(
3066                assert_eq!(
3067                    <$t>::$from($value),
3068                    Some($variant),
3069                    "{}::{}({}) must map to the pinned variant",
3070                    stringify!($t),
3071                    stringify!($from),
3072                    $value,
3073                );
3074            )+
3075
3076            for value in <$width>::MIN..=<$width>::MAX {
3077                if !valid.contains(&value) {
3078                    assert_eq!(
3079                        <$t>::$from(value),
3080                        None,
3081                        "{} must reject {value}",
3082                        stringify!($t),
3083                    );
3084                }
3085            }
3086        }};
3087    }
3088
3089    #[rstest]
3090    fn test_from_u8_pins_numeric_discriminants() {
3091        assert_numeric_mapping!(
3092            AggressorSide, from_u8, u8,
3093            0 => AggressorSide::NoAggressor,
3094            1 => AggressorSide::Buy,
3095            2 => AggressorSide::Sell,
3096        );
3097        assert_numeric_mapping!(
3098            AssetClass, from_u8, u8,
3099            1 => AssetClass::FX,
3100            2 => AssetClass::Equity,
3101            3 => AssetClass::Commodity,
3102            4 => AssetClass::Debt,
3103            5 => AssetClass::Index,
3104            6 => AssetClass::Cryptocurrency,
3105            7 => AssetClass::Alternative,
3106        );
3107        assert_numeric_mapping!(
3108            BookAction, from_u8, u8,
3109            1 => BookAction::Add,
3110            2 => BookAction::Update,
3111            3 => BookAction::Delete,
3112            4 => BookAction::Clear,
3113        );
3114        assert_numeric_mapping!(
3115            BookType, from_u8, u8,
3116            1 => BookType::L1_MBP,
3117            2 => BookType::L2_MBP,
3118            3 => BookType::L3_MBO,
3119        );
3120        assert_numeric_mapping!(
3121            InstrumentCloseType, from_u8, u8,
3122            1 => InstrumentCloseType::EndOfSession,
3123            2 => InstrumentCloseType::ContractExpired,
3124        );
3125        assert_numeric_mapping!(
3126            PositionAdjustmentType, from_u8, u8,
3127            1 => PositionAdjustmentType::Commission,
3128            2 => PositionAdjustmentType::Funding,
3129        );
3130    }
3131
3132    #[rstest]
3133    fn test_market_status_action_from_u16_pins_numeric_discriminants() {
3134        assert_numeric_mapping!(
3135            MarketStatusAction, from_u16, u16,
3136            0 => MarketStatusAction::None,
3137            1 => MarketStatusAction::PreOpen,
3138            2 => MarketStatusAction::PreCross,
3139            3 => MarketStatusAction::Quoting,
3140            4 => MarketStatusAction::Cross,
3141            5 => MarketStatusAction::Rotation,
3142            6 => MarketStatusAction::NewPriceIndication,
3143            7 => MarketStatusAction::Trading,
3144            8 => MarketStatusAction::Halt,
3145            9 => MarketStatusAction::Pause,
3146            10 => MarketStatusAction::Suspend,
3147            11 => MarketStatusAction::PreClose,
3148            12 => MarketStatusAction::Close,
3149            13 => MarketStatusAction::PostClose,
3150            14 => MarketStatusAction::ShortSellRestrictionChange,
3151            15 => MarketStatusAction::NotAvailableForTrading,
3152        );
3153    }
3154
3155    #[rstest]
3156    #[case(OrderStatus::Initialized, false, false, false, false)]
3157    #[case(OrderStatus::Denied, false, true, false, false)]
3158    #[case(OrderStatus::Emulated, false, false, false, false)]
3159    #[case(OrderStatus::Released, false, false, false, false)]
3160    #[case(OrderStatus::Submitted, false, false, false, true)]
3161    #[case(OrderStatus::Accepted, true, false, true, false)]
3162    #[case(OrderStatus::Rejected, false, true, false, false)]
3163    #[case(OrderStatus::Canceled, false, true, false, false)]
3164    #[case(OrderStatus::Expired, false, true, false, false)]
3165    #[case(OrderStatus::Triggered, true, false, true, false)]
3166    #[case(OrderStatus::PendingUpdate, true, false, true, true)]
3167    #[case(OrderStatus::PendingCancel, true, false, false, true)]
3168    #[case(OrderStatus::PartiallyFilled, true, false, true, false)]
3169    #[case(OrderStatus::Filled, false, true, false, false)]
3170    #[case(OrderStatus::Voided, false, true, false, false)]
3171    fn test_order_status_predicates(
3172        #[case] status: OrderStatus,
3173        #[case] expected_open: bool,
3174        #[case] expected_closed: bool,
3175        #[case] expected_cancellable: bool,
3176        #[case] expected_inflight: bool,
3177    ) {
3178        assert_eq!(status.is_open(), expected_open, "{status} is_open");
3179        assert_eq!(status.is_closed(), expected_closed, "{status} is_closed");
3180        assert_eq!(
3181            status.is_cancellable(),
3182            expected_cancellable,
3183            "{status} is_cancellable",
3184        );
3185        assert_eq!(
3186            status.is_inflight(),
3187            expected_inflight,
3188            "{status} is_inflight"
3189        );
3190    }
3191
3192    #[rstest]
3193    fn test_order_status_predicates_hold_across_all_variants() {
3194        for status in OrderStatus::iter() {
3195            assert!(
3196                !(status.is_open() && status.is_closed()),
3197                "{status} cannot be both open and closed",
3198            );
3199            assert!(
3200                !status.is_cancellable() || status.is_open(),
3201                "{status} must be open to be cancellable",
3202            );
3203            assert!(
3204                !(status.is_inflight() && status.is_closed()),
3205                "{status} cannot be both in-flight and closed",
3206            );
3207        }
3208    }
3209
3210    #[rstest]
3211    #[case(OrderSide::Buy, OrderSide::Sell)]
3212    #[case(OrderSide::Sell, OrderSide::Buy)]
3213    fn test_order_side_opposite(#[case] side: OrderSide, #[case] expected: OrderSide) {
3214        assert_eq!(side.opposite(), expected);
3215        assert_eq!(side.opposite().opposite(), side);
3216    }
3217
3218    #[rstest]
3219    #[case(BetSide::Back, BetSide::Lay)]
3220    #[case(BetSide::Lay, BetSide::Back)]
3221    fn test_bet_side_opposite(#[case] side: BetSide, #[case] expected: BetSide) {
3222        assert_eq!(side.opposite(), expected);
3223        assert_eq!(side.opposite().opposite(), side);
3224    }
3225
3226    #[rstest]
3227    #[case(OrderSide::Buy, BetSide::Back)]
3228    #[case(OrderSide::Sell, BetSide::Lay)]
3229    fn test_bet_side_from_order_side(#[case] side: OrderSide, #[case] expected: BetSide) {
3230        assert_eq!(BetSide::from(side), expected);
3231    }
3232
3233    #[rstest]
3234    #[case(RecordFlag::F_LAST, 0b0000_0000, false)]
3235    #[case(RecordFlag::F_LAST, 0b1000_0000, true)]
3236    #[case(RecordFlag::F_LAST, 0b0111_1111, false)]
3237    #[case(RecordFlag::F_TOB, 0b1100_0000, true)]
3238    #[case(RecordFlag::F_TOB, 0b1000_0000, false)]
3239    #[case(RecordFlag::F_SNAPSHOT, 0b0010_0000, true)]
3240    #[case(RecordFlag::F_SNAPSHOT, 0b1101_1111, false)]
3241    #[case(RecordFlag::F_MBP, 0b0001_0000, true)]
3242    #[case(RecordFlag::RESERVED_2, 0b0000_1000, true)]
3243    #[case(RecordFlag::RESERVED_1, 0b0000_0100, true)]
3244    #[case(RecordFlag::RESERVED_1, 0b0000_1000, false)]
3245    #[case(RecordFlag::F_LAST, u8::MAX, true)]
3246    fn test_record_flag_matches(
3247        #[case] flag: RecordFlag,
3248        #[case] value: u8,
3249        #[case] expected: bool,
3250    ) {
3251        assert_eq!(flag.matches(value), expected);
3252    }
3253
3254    #[rstest]
3255    fn test_record_flag_matches_only_its_own_bit() {
3256        for flag in RecordFlag::iter() {
3257            let bit = flag as u8;
3258            assert_eq!(bit.count_ones(), 1, "{flag} must occupy exactly one bit");
3259            assert!(flag.matches(bit), "{flag} must match its own bit");
3260            assert!(
3261                !flag.matches(!bit),
3262                "{flag} must not match the inverse mask"
3263            );
3264        }
3265    }
3266
3267    #[rstest]
3268    #[case(InstrumentClass::Future, true)]
3269    #[case(InstrumentClass::FuturesSpread, true)]
3270    #[case(InstrumentClass::Option, true)]
3271    #[case(InstrumentClass::OptionSpread, true)]
3272    #[case(InstrumentClass::Spot, false)]
3273    #[case(InstrumentClass::Swap, false)]
3274    #[case(InstrumentClass::Forward, false)]
3275    #[case(InstrumentClass::Cfd, false)]
3276    #[case(InstrumentClass::Bond, false)]
3277    #[case(InstrumentClass::Warrant, false)]
3278    #[case(InstrumentClass::SportsBetting, false)]
3279    #[case(InstrumentClass::BinaryOption, false)]
3280    fn test_instrument_class_has_expiration(
3281        #[case] class: InstrumentClass,
3282        #[case] expected: bool,
3283    ) {
3284        assert_eq!(class.has_expiration(), expected);
3285    }
3286
3287    #[rstest]
3288    fn test_optional_sides_serde_round_trips_present_values() {
3289        let value = OptionalSides {
3290            order: Some(OrderSide::Sell),
3291            position: Some(PositionSide::Short),
3292        };
3293
3294        let json = serde_json::to_string(&value).unwrap();
3295
3296        assert_eq!(json, r#"{"order":"SELL","position":"SHORT"}"#);
3297        assert_eq!(serde_json::from_str::<OptionalSides>(&json).unwrap(), value);
3298    }
3299
3300    #[rstest]
3301    #[case(r#"{"order":"no_order_side","position":"FLAT"}"#)]
3302    #[case(r#"{"order":"No_Order_Side","position":"FLAT"}"#)]
3303    fn test_optional_sides_serde_accepts_none_token_in_any_case(#[case] json: &str) {
3304        let decoded: OptionalSides = serde_json::from_str(json).unwrap();
3305
3306        assert_eq!(
3307            decoded,
3308            OptionalSides {
3309                order: None,
3310                position: Some(PositionSide::Flat),
3311            },
3312        );
3313    }
3314
3315    #[rstest]
3316    #[case(r#"{"order":"INVALID","position":"FLAT"}"#)]
3317    #[case(r#"{"order":5,"position":"FLAT"}"#)]
3318    #[case(r#"{"order":"BUY","position":"INVALID"}"#)]
3319    #[case(r#"{"order":"BUY","position":true}"#)]
3320    fn test_optional_sides_serde_rejects_invalid_values(#[case] json: &str) {
3321        assert!(serde_json::from_str::<OptionalSides>(json).is_err());
3322    }
3323
3324    #[rstest]
3325    #[case(
3326        OptionSideFilter::Both,
3327        OptionKind::Call,
3328        std::cmp::Ordering::Less,
3329        true
3330    )]
3331    #[case(
3332        OptionSideFilter::Both,
3333        OptionKind::Put,
3334        std::cmp::Ordering::Greater,
3335        true
3336    )]
3337    #[case(
3338        OptionSideFilter::Calls,
3339        OptionKind::Call,
3340        std::cmp::Ordering::Less,
3341        true
3342    )]
3343    #[case(
3344        OptionSideFilter::Calls,
3345        OptionKind::Put,
3346        std::cmp::Ordering::Less,
3347        false
3348    )]
3349    #[case(
3350        OptionSideFilter::Puts,
3351        OptionKind::Put,
3352        std::cmp::Ordering::Greater,
3353        true
3354    )]
3355    #[case(
3356        OptionSideFilter::Puts,
3357        OptionKind::Call,
3358        std::cmp::Ordering::Greater,
3359        false
3360    )]
3361    #[case(OptionSideFilter::Otm, OptionKind::Put, std::cmp::Ordering::Less, true)]
3362    #[case(
3363        OptionSideFilter::Otm,
3364        OptionKind::Call,
3365        std::cmp::Ordering::Less,
3366        false
3367    )]
3368    #[case(
3369        OptionSideFilter::Otm,
3370        OptionKind::Call,
3371        std::cmp::Ordering::Greater,
3372        true
3373    )]
3374    #[case(
3375        OptionSideFilter::Otm,
3376        OptionKind::Put,
3377        std::cmp::Ordering::Greater,
3378        false
3379    )]
3380    #[case(
3381        OptionSideFilter::Otm,
3382        OptionKind::Call,
3383        std::cmp::Ordering::Equal,
3384        true
3385    )]
3386    #[case(
3387        OptionSideFilter::Otm,
3388        OptionKind::Put,
3389        std::cmp::Ordering::Equal,
3390        true
3391    )]
3392    fn test_option_side_filter_includes(
3393        #[case] filter: OptionSideFilter,
3394        #[case] kind: OptionKind,
3395        #[case] position: std::cmp::Ordering,
3396        #[case] expected: bool,
3397    ) {
3398        assert_eq!(filter.includes(kind, position), expected);
3399    }
3400}