Skip to main content

nautilus_model/events/order/
mod.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use indexmap::IndexMap;
17use nautilus_core::{UUID4, UnixNanos};
18use rust_decimal::Decimal;
19use ustr::Ustr;
20
21use crate::{
22    enums::{
23        ContingencyType, LiquiditySide, OrderSide, OrderType, TimeInForce, TrailingOffsetType,
24        TriggerType,
25    },
26    identifiers::{
27        AccountId, ClientOrderId, ExecAlgorithmId, InstrumentId, OrderListId, PositionId,
28        StrategyId, TradeId, TraderId, VenueOrderId,
29    },
30    types::{Currency, Money, Price, Quantity},
31};
32
33pub mod accepted;
34pub mod accepted_batch;
35pub mod any;
36pub mod cancel_denied;
37pub mod cancel_rejected;
38pub mod canceled;
39pub mod canceled_batch;
40pub mod denied;
41pub mod denied_reason;
42pub mod emulated;
43pub mod expired;
44pub mod fill_voided;
45pub mod filled;
46pub mod initialized;
47pub mod modify_denied;
48pub mod modify_rejected;
49pub mod pending_cancel;
50pub mod pending_update;
51pub mod rejected;
52pub mod released;
53pub mod snapshot;
54pub mod submitted;
55pub mod submitted_batch;
56pub mod triggered;
57pub mod updated;
58
59#[cfg(any(test, feature = "test-support"))]
60pub mod spec;
61#[cfg(any(test, feature = "test-support"))]
62pub mod stubs;
63
64/// Represents a type of [`OrderEvent`].
65#[derive(Debug, PartialEq, Eq)]
66pub enum OrderEventType {
67    Initialized,
68    Denied,
69    Emulated,
70    Released,
71    Submitted,
72    Accepted,
73    Rejected,
74    Canceled,
75    Expired,
76    Triggered,
77    PendingUpdate,
78    PendingCancel,
79    ModifyDenied,
80    ModifyRejected,
81    CancelDenied,
82    CancelRejected,
83    Updated,
84    PartiallyFilled,
85    Filled,
86    FillVoided,
87}
88
89pub trait OrderEvent: 'static + Send {
90    fn id(&self) -> UUID4;
91    fn type_name(&self) -> &'static str;
92    fn order_type(&self) -> Option<OrderType>;
93    fn order_side(&self) -> Option<OrderSide>;
94    fn trader_id(&self) -> TraderId;
95    fn strategy_id(&self) -> StrategyId;
96    fn instrument_id(&self) -> InstrumentId;
97    fn trade_id(&self) -> Option<TradeId>;
98    fn currency(&self) -> Option<Currency>;
99    fn client_order_id(&self) -> ClientOrderId;
100    fn reason(&self) -> Option<Ustr>;
101    fn quantity(&self) -> Option<Quantity>;
102    fn time_in_force(&self) -> Option<TimeInForce>;
103    fn liquidity_side(&self) -> Option<LiquiditySide>;
104    fn post_only(&self) -> Option<bool>;
105    fn reduce_only(&self) -> Option<bool>;
106    fn quote_quantity(&self) -> Option<bool>;
107    fn reconciliation(&self) -> bool;
108    fn price(&self) -> Option<Price>;
109    fn last_px(&self) -> Option<Price>;
110    fn last_qty(&self) -> Option<Quantity>;
111    fn activation_price(&self) -> Option<Price>;
112    fn trigger_price(&self) -> Option<Price>;
113    fn trigger_type(&self) -> Option<TriggerType>;
114    fn limit_offset(&self) -> Option<Decimal>;
115    fn trailing_offset(&self) -> Option<Decimal>;
116    fn trailing_offset_type(&self) -> Option<TrailingOffsetType>;
117    fn expire_time(&self) -> Option<UnixNanos>;
118    fn display_qty(&self) -> Option<Quantity>;
119    fn emulation_trigger(&self) -> Option<TriggerType>;
120    fn trigger_instrument_id(&self) -> Option<InstrumentId>;
121    fn contingency_type(&self) -> Option<ContingencyType>;
122    fn order_list_id(&self) -> Option<OrderListId>;
123    fn linked_order_ids(&self) -> Option<Vec<ClientOrderId>>;
124    fn parent_order_id(&self) -> Option<ClientOrderId>;
125    fn exec_algorithm_id(&self) -> Option<ExecAlgorithmId>;
126    fn exec_algorithm_params(&self) -> Option<IndexMap<Ustr, Ustr>> {
127        None
128    }
129    fn exec_spawn_id(&self) -> Option<ClientOrderId>;
130    fn tags(&self) -> Option<Vec<Ustr>> {
131        None
132    }
133    fn venue_order_id(&self) -> Option<VenueOrderId>;
134    fn account_id(&self) -> Option<AccountId>;
135    fn position_id(&self) -> Option<PositionId>;
136    fn commission(&self) -> Option<Money>;
137    fn ts_event(&self) -> UnixNanos;
138    fn ts_init(&self) -> UnixNanos;
139    fn causation_id(&self) -> Option<UUID4> {
140        None
141    }
142    fn released_price(&self) -> Option<Price> {
143        None
144    }
145    fn protection_price(&self) -> Option<Price> {
146        None
147    }
148    fn due_post_only(&self) -> bool {
149        false
150    }
151    fn correction_id(&self) -> Option<Ustr> {
152        None
153    }
154    fn is_reopened(&self) -> bool {
155        false
156    }
157    fn info(&self) -> Option<IndexMap<Ustr, Ustr>> {
158        None
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use indexmap::IndexMap;
165    use rstest::rstest;
166    use rust_decimal_macros::dec;
167
168    use super::*;
169    use crate::events::order::{any::OrderEventAny, spec::*};
170
171    /// Returns the sorted names of every `Option` accessor that yields `Some` for `event`.
172    fn optional_fields_present(event: &dyn OrderEvent) -> Vec<&'static str> {
173        let mut present: Vec<&'static str> = [
174            ("activation_price", event.activation_price().is_some()),
175            ("account_id", event.account_id().is_some()),
176            ("causation_id", event.causation_id().is_some()),
177            ("commission", event.commission().is_some()),
178            ("contingency_type", event.contingency_type().is_some()),
179            ("correction_id", event.correction_id().is_some()),
180            ("currency", event.currency().is_some()),
181            ("display_qty", event.display_qty().is_some()),
182            ("emulation_trigger", event.emulation_trigger().is_some()),
183            ("exec_algorithm_id", event.exec_algorithm_id().is_some()),
184            (
185                "exec_algorithm_params",
186                event.exec_algorithm_params().is_some(),
187            ),
188            ("exec_spawn_id", event.exec_spawn_id().is_some()),
189            ("expire_time", event.expire_time().is_some()),
190            ("info", event.info().is_some()),
191            ("last_px", event.last_px().is_some()),
192            ("last_qty", event.last_qty().is_some()),
193            ("limit_offset", event.limit_offset().is_some()),
194            ("linked_order_ids", event.linked_order_ids().is_some()),
195            ("liquidity_side", event.liquidity_side().is_some()),
196            ("order_list_id", event.order_list_id().is_some()),
197            ("order_side", event.order_side().is_some()),
198            ("order_type", event.order_type().is_some()),
199            ("parent_order_id", event.parent_order_id().is_some()),
200            ("position_id", event.position_id().is_some()),
201            ("post_only", event.post_only().is_some()),
202            ("price", event.price().is_some()),
203            ("protection_price", event.protection_price().is_some()),
204            ("quantity", event.quantity().is_some()),
205            ("quote_quantity", event.quote_quantity().is_some()),
206            ("reason", event.reason().is_some()),
207            ("reduce_only", event.reduce_only().is_some()),
208            ("released_price", event.released_price().is_some()),
209            ("tags", event.tags().is_some()),
210            ("time_in_force", event.time_in_force().is_some()),
211            ("trade_id", event.trade_id().is_some()),
212            ("trailing_offset", event.trailing_offset().is_some()),
213            (
214                "trailing_offset_type",
215                event.trailing_offset_type().is_some(),
216            ),
217            (
218                "trigger_instrument_id",
219                event.trigger_instrument_id().is_some(),
220            ),
221            ("trigger_price", event.trigger_price().is_some()),
222            ("trigger_type", event.trigger_type().is_some()),
223            ("venue_order_id", event.venue_order_id().is_some()),
224        ]
225        .into_iter()
226        .filter(|(_, present)| *present)
227        .map(|(name, _)| name)
228        .collect();
229        present.sort_unstable();
230        present
231    }
232
233    fn params() -> IndexMap<Ustr, Ustr> {
234        IndexMap::from([(Ustr::from("k"), Ustr::from("v"))])
235    }
236
237    fn fully_populated_events() -> Vec<(OrderEventAny, Vec<&'static str>)> {
238        let venue_order_id = VenueOrderId::from("V-1");
239        let account_id = AccountId::from("SIM-001");
240        let reason = Ustr::from("REASON");
241        let px = Price::from("1.00");
242
243        vec![
244            (
245                OrderEventAny::Initialized(
246                    OrderInitializedSpec::builder()
247                        .price(px)
248                        .activation_price(px)
249                        .trigger_price(px)
250                        .trigger_type(TriggerType::LastPrice)
251                        .limit_offset(dec!(0.5))
252                        .trailing_offset(dec!(0.5))
253                        .trailing_offset_type(TrailingOffsetType::Price)
254                        .expire_time(UnixNanos::from(9))
255                        .display_qty(Quantity::from(1))
256                        .emulation_trigger(TriggerType::BidAsk)
257                        .trigger_instrument_id(InstrumentId::from("AUD/USD.SIM"))
258                        .contingency_type(ContingencyType::Oto)
259                        .order_list_id(OrderListId::from("OL-1"))
260                        .linked_order_ids(vec![ClientOrderId::from("O-2")])
261                        .parent_order_id(ClientOrderId::from("O-3"))
262                        .exec_algorithm_id(ExecAlgorithmId::from("TWAP"))
263                        .exec_algorithm_params(params())
264                        .exec_spawn_id(ClientOrderId::from("O-4"))
265                        .tags(vec![Ustr::from("TAG")])
266                        .build(),
267                ),
268                vec![
269                    "activation_price",
270                    "contingency_type",
271                    "display_qty",
272                    "emulation_trigger",
273                    "exec_algorithm_id",
274                    "exec_algorithm_params",
275                    "exec_spawn_id",
276                    "expire_time",
277                    "limit_offset",
278                    "linked_order_ids",
279                    "order_list_id",
280                    "order_side",
281                    "order_type",
282                    "parent_order_id",
283                    "post_only",
284                    "price",
285                    "quantity",
286                    "quote_quantity",
287                    "reduce_only",
288                    "tags",
289                    "time_in_force",
290                    "trailing_offset",
291                    "trailing_offset_type",
292                    "trigger_instrument_id",
293                    "trigger_price",
294                    "trigger_type",
295                ],
296            ),
297            (
298                OrderEventAny::Denied(OrderDeniedSpec::builder().build()),
299                vec!["reason"],
300            ),
301            (
302                OrderEventAny::Emulated(OrderEmulatedSpec::builder().build()),
303                vec![],
304            ),
305            (
306                OrderEventAny::Released(OrderReleasedSpec::builder().build()),
307                vec!["released_price"],
308            ),
309            (
310                OrderEventAny::Submitted(OrderSubmittedSpec::builder().build()),
311                vec!["account_id"],
312            ),
313            (
314                OrderEventAny::Accepted(OrderAcceptedSpec::builder().build()),
315                vec!["account_id", "venue_order_id"],
316            ),
317            (
318                OrderEventAny::Rejected(OrderRejectedSpec::builder().build()),
319                vec!["account_id", "reason"],
320            ),
321            (
322                OrderEventAny::Canceled(
323                    OrderCanceledSpec::builder()
324                        .venue_order_id(venue_order_id)
325                        .account_id(account_id)
326                        .reason(reason)
327                        .build(),
328                ),
329                vec!["account_id", "reason", "venue_order_id"],
330            ),
331            (
332                OrderEventAny::Expired(
333                    OrderExpiredSpec::builder()
334                        .venue_order_id(venue_order_id)
335                        .account_id(account_id)
336                        .build(),
337                ),
338                vec!["account_id", "venue_order_id"],
339            ),
340            (
341                OrderEventAny::Triggered(
342                    OrderTriggeredSpec::builder()
343                        .venue_order_id(venue_order_id)
344                        .account_id(account_id)
345                        .build(),
346                ),
347                vec!["account_id", "venue_order_id"],
348            ),
349            (
350                OrderEventAny::PendingUpdate(
351                    OrderPendingUpdateSpec::builder()
352                        .venue_order_id(venue_order_id)
353                        .account_id(account_id)
354                        .build(),
355                ),
356                vec!["account_id", "venue_order_id"],
357            ),
358            (
359                OrderEventAny::PendingCancel(
360                    OrderPendingCancelSpec::builder()
361                        .venue_order_id(venue_order_id)
362                        .account_id(account_id)
363                        .build(),
364                ),
365                vec!["account_id", "venue_order_id"],
366            ),
367            (
368                OrderEventAny::ModifyRejected(
369                    OrderModifyRejectedSpec::builder()
370                        .venue_order_id(venue_order_id)
371                        .account_id(account_id)
372                        .build(),
373                ),
374                vec!["account_id", "reason", "venue_order_id"],
375            ),
376            (
377                OrderEventAny::CancelRejected(
378                    OrderCancelRejectedSpec::builder()
379                        .venue_order_id(venue_order_id)
380                        .account_id(account_id)
381                        .build(),
382                ),
383                vec!["account_id", "reason", "venue_order_id"],
384            ),
385            (
386                OrderEventAny::Updated(
387                    OrderUpdatedSpec::builder()
388                        .venue_order_id(venue_order_id)
389                        .account_id(account_id)
390                        .price(px)
391                        .trigger_price(px)
392                        .protection_price(px)
393                        .build(),
394                ),
395                vec![
396                    "account_id",
397                    "price",
398                    "protection_price",
399                    "quantity",
400                    "quote_quantity",
401                    "trigger_price",
402                    "venue_order_id",
403                ],
404            ),
405            (
406                OrderEventAny::Filled(
407                    OrderFilledSpec::builder()
408                        .position_id(PositionId::from("P-1"))
409                        .commission(Money::from("1.00 USD"))
410                        .info(params())
411                        .build(),
412                ),
413                vec![
414                    "account_id",
415                    "commission",
416                    "currency",
417                    "info",
418                    "last_px",
419                    "last_qty",
420                    "liquidity_side",
421                    "order_side",
422                    "order_type",
423                    "position_id",
424                    "quantity",
425                    "trade_id",
426                    "venue_order_id",
427                ],
428            ),
429            (
430                OrderEventAny::FillVoided(
431                    OrderFillVoidedSpec::builder()
432                        .commission_voided(Money::from("1.00 USD"))
433                        .position_id(PositionId::from("P-1"))
434                        .reason(reason)
435                        .info(params())
436                        .build(),
437                ),
438                vec![
439                    "account_id",
440                    "commission",
441                    "correction_id",
442                    "currency",
443                    "info",
444                    "last_px",
445                    "last_qty",
446                    "liquidity_side",
447                    "order_side",
448                    "order_type",
449                    "position_id",
450                    "quantity",
451                    "reason",
452                    "trade_id",
453                    "venue_order_id",
454                ],
455            ),
456        ]
457    }
458
459    #[rstest]
460    fn test_optional_field_surface_matches_event_payload() {
461        for (event, expected) in fully_populated_events() {
462            let event_type = event.event_type();
463            let boxed = event.into_boxed();
464
465            assert_eq!(
466                optional_fields_present(boxed.as_ref()),
467                expected,
468                "optional accessor surface changed for {event_type:?}"
469            );
470        }
471    }
472
473    #[rstest]
474    fn test_initialized_accessors_map_distinct_fields() {
475        let event = OrderInitializedSpec::builder()
476            .quantity(Quantity::from(100))
477            .price(Price::from("1.00"))
478            .activation_price(Price::from("2.00"))
479            .trigger_price(Price::from("3.00"))
480            .trigger_type(TriggerType::LastPrice)
481            .emulation_trigger(TriggerType::BidAsk)
482            .limit_offset(dec!(0.5))
483            .trailing_offset(dec!(1.5))
484            .display_qty(Quantity::from(10))
485            .parent_order_id(ClientOrderId::from("O-PARENT"))
486            .exec_spawn_id(ClientOrderId::from("O-SPAWN"))
487            .ts_event(UnixNanos::from(7))
488            .ts_init(UnixNanos::from(8))
489            .build();
490
491        assert_eq!(event.price(), Some(Price::from("1.00")));
492        assert_eq!(event.activation_price(), Some(Price::from("2.00")));
493        assert_eq!(event.trigger_price(), Some(Price::from("3.00")));
494        assert_eq!(event.trigger_type(), Some(TriggerType::LastPrice));
495        assert_eq!(event.emulation_trigger(), Some(TriggerType::BidAsk));
496        assert_eq!(event.limit_offset(), Some(dec!(0.5)));
497        assert_eq!(event.trailing_offset(), Some(dec!(1.5)));
498        assert_eq!(event.quantity(), Some(Quantity::from(100)));
499        assert_eq!(event.display_qty(), Some(Quantity::from(10)));
500        assert_eq!(
501            event.parent_order_id(),
502            Some(ClientOrderId::from("O-PARENT"))
503        );
504        assert_eq!(event.exec_spawn_id(), Some(ClientOrderId::from("O-SPAWN")));
505        assert_eq!(event.ts_event(), UnixNanos::from(7));
506        assert_eq!(event.ts_init(), UnixNanos::from(8));
507    }
508
509    #[rstest]
510    fn test_filled_accessors_map_distinct_fields() {
511        let event = OrderFilledSpec::builder()
512            .last_qty(Quantity::from(25))
513            .last_px(Price::from("4.00"))
514            .commission(Money::from("2.00 USD"))
515            .ts_event(UnixNanos::from(7))
516            .ts_init(UnixNanos::from(8))
517            .build();
518
519        assert_eq!(event.last_px(), Some(Price::from("4.00")));
520        assert_eq!(event.price(), None);
521        assert_eq!(event.last_qty(), Some(Quantity::from(25)));
522        assert_eq!(event.quantity(), Some(Quantity::from(25)));
523        assert_eq!(event.commission(), Some(Money::from("2.00 USD")));
524        assert_eq!(event.ts_event(), UnixNanos::from(7));
525        assert_eq!(event.ts_init(), UnixNanos::from(8));
526    }
527
528    #[rstest]
529    fn test_updated_accessors_map_distinct_prices() {
530        let event = OrderUpdatedSpec::builder()
531            .quantity(Quantity::from(50))
532            .price(Price::from("1.00"))
533            .trigger_price(Price::from("2.00"))
534            .protection_price(Price::from("3.00"))
535            .ts_event(UnixNanos::from(7))
536            .ts_init(UnixNanos::from(8))
537            .build();
538
539        assert_eq!(event.price(), Some(Price::from("1.00")));
540        assert_eq!(event.trigger_price(), Some(Price::from("2.00")));
541        assert_eq!(event.protection_price(), Some(Price::from("3.00")));
542        assert_eq!(event.quantity(), Some(Quantity::from(50)));
543        assert_eq!(event.ts_event(), UnixNanos::from(7));
544        assert_eq!(event.ts_init(), UnixNanos::from(8));
545    }
546
547    #[rstest]
548    fn test_type_name_matches_variant() {
549        let expected = [
550            "OrderInitialized",
551            "OrderDenied",
552            "OrderEmulated",
553            "OrderReleased",
554            "OrderSubmitted",
555            "OrderAccepted",
556            "OrderRejected",
557            "OrderCanceled",
558            "OrderExpired",
559            "OrderTriggered",
560            "OrderPendingUpdate",
561            "OrderPendingCancel",
562            "OrderModifyRejected",
563            "OrderCancelRejected",
564            "OrderUpdated",
565            "OrderFilled",
566            "OrderFillVoided",
567        ];
568
569        let names: Vec<&'static str> = fully_populated_events()
570            .into_iter()
571            .map(|(event, _)| event.into_boxed().type_name())
572            .collect();
573
574        assert_eq!(names, expected);
575    }
576}