Skip to main content

nautilus_model/events/order/
expired.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::fmt::{Debug, Display};
17
18use nautilus_core::{UUID4, UnixNanos};
19use rust_decimal::Decimal;
20use serde::{Deserialize, Serialize};
21use ustr::Ustr;
22
23use crate::{
24    enums::{
25        ContingencyType, LiquiditySide, OrderSide, OrderType, TimeInForce, TrailingOffsetType,
26        TriggerType,
27    },
28    events::OrderEvent,
29    identifiers::{
30        AccountId, ClientOrderId, ExecAlgorithmId, InstrumentId, OrderListId, PositionId,
31        StrategyId, TradeId, TraderId, VenueOrderId,
32    },
33    types::{Currency, Money, Price, Quantity},
34};
35
36/// Represents an event where an order has expired at the trading venue.
37#[repr(C)]
38#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(tag = "type")]
40#[cfg_attr(
41    feature = "python",
42    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model", from_py_object)
43)]
44#[cfg_attr(
45    feature = "python",
46    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
47)]
48pub struct OrderExpired {
49    /// The trader ID associated with the event.
50    pub trader_id: TraderId,
51    /// The strategy ID associated with the event.
52    pub strategy_id: StrategyId,
53    /// The instrument ID associated with the event.
54    pub instrument_id: InstrumentId,
55    /// The client order ID associated with the event.
56    pub client_order_id: ClientOrderId,
57    /// The unique identifier for the event.
58    pub event_id: UUID4,
59    /// UNIX timestamp (nanoseconds) when the event occurred.
60    pub ts_event: UnixNanos,
61    /// UNIX timestamp (nanoseconds) when the event was initialized.
62    pub ts_init: UnixNanos,
63    /// If the event was generated during reconciliation.
64    pub reconciliation: bool,
65    /// The venue order ID associated with the event.
66    pub venue_order_id: Option<VenueOrderId>,
67    /// The account ID associated with the event.
68    pub account_id: Option<AccountId>,
69    /// The causation ID associated with the event.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub causation_id: Option<UUID4>,
72}
73
74impl OrderExpired {
75    /// Creates a new [`OrderExpired`] instance.
76    #[expect(clippy::too_many_arguments)]
77    #[must_use]
78    pub fn new(
79        trader_id: TraderId,
80        strategy_id: StrategyId,
81        instrument_id: InstrumentId,
82        client_order_id: ClientOrderId,
83        event_id: UUID4,
84        ts_event: UnixNanos,
85        ts_init: UnixNanos,
86        reconciliation: bool,
87        venue_order_id: Option<VenueOrderId>,
88        account_id: Option<AccountId>,
89    ) -> Self {
90        Self {
91            trader_id,
92            strategy_id,
93            instrument_id,
94            client_order_id,
95            event_id,
96            ts_event,
97            ts_init,
98            reconciliation,
99            venue_order_id,
100            account_id,
101            causation_id: None,
102        }
103    }
104}
105
106impl Debug for OrderExpired {
107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        write!(
109            f,
110            "{}(trader_id={}, strategy_id={}, instrument_id={}, client_order_id={}, venue_order_id={}, account_id={}, event_id={}, ts_event={}, ts_init={})",
111            stringify!(OrderExpired),
112            self.trader_id,
113            self.strategy_id,
114            self.instrument_id,
115            self.client_order_id,
116            self.venue_order_id.map_or_else(
117                || "None".to_string(),
118                |venue_order_id| format!("{venue_order_id}")
119            ),
120            self.account_id
121                .map_or_else(|| "None".to_string(), |account_id| format!("{account_id}")),
122            self.event_id,
123            self.ts_event,
124            self.ts_init
125        )
126    }
127}
128
129impl Display for OrderExpired {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        write!(
132            f,
133            "{}(instrument_id={}, client_order_id={}, venue_order_id={}, account_id={}, ts_event={})",
134            stringify!(OrderExpired),
135            self.instrument_id,
136            self.client_order_id,
137            self.venue_order_id
138                .map_or("None".to_string(), |venue_order_id| format!(
139                    "{venue_order_id}"
140                )),
141            self.account_id
142                .map_or("None".to_string(), |account_id| format!("{account_id}")),
143            self.ts_event
144        )
145    }
146}
147
148impl OrderEvent for OrderExpired {
149    fn id(&self) -> UUID4 {
150        self.event_id
151    }
152
153    fn type_name(&self) -> &'static str {
154        stringify!(OrderExpired)
155    }
156
157    fn order_type(&self) -> Option<OrderType> {
158        None
159    }
160
161    fn order_side(&self) -> Option<OrderSide> {
162        None
163    }
164
165    fn trader_id(&self) -> TraderId {
166        self.trader_id
167    }
168
169    fn strategy_id(&self) -> StrategyId {
170        self.strategy_id
171    }
172
173    fn instrument_id(&self) -> InstrumentId {
174        self.instrument_id
175    }
176
177    fn trade_id(&self) -> Option<TradeId> {
178        None
179    }
180
181    fn currency(&self) -> Option<Currency> {
182        None
183    }
184
185    fn client_order_id(&self) -> ClientOrderId {
186        self.client_order_id
187    }
188
189    fn reason(&self) -> Option<Ustr> {
190        None
191    }
192
193    fn quantity(&self) -> Option<Quantity> {
194        None
195    }
196
197    fn time_in_force(&self) -> Option<TimeInForce> {
198        None
199    }
200
201    fn liquidity_side(&self) -> Option<LiquiditySide> {
202        None
203    }
204
205    fn post_only(&self) -> Option<bool> {
206        None
207    }
208
209    fn reduce_only(&self) -> Option<bool> {
210        None
211    }
212
213    fn quote_quantity(&self) -> Option<bool> {
214        None
215    }
216
217    fn reconciliation(&self) -> bool {
218        false
219    }
220
221    fn price(&self) -> Option<Price> {
222        None
223    }
224
225    fn last_px(&self) -> Option<Price> {
226        None
227    }
228
229    fn last_qty(&self) -> Option<Quantity> {
230        None
231    }
232
233    fn trigger_price(&self) -> Option<Price> {
234        None
235    }
236
237    fn trigger_type(&self) -> Option<TriggerType> {
238        None
239    }
240
241    fn limit_offset(&self) -> Option<Decimal> {
242        None
243    }
244
245    fn trailing_offset(&self) -> Option<Decimal> {
246        None
247    }
248
249    fn trailing_offset_type(&self) -> Option<TrailingOffsetType> {
250        None
251    }
252
253    fn expire_time(&self) -> Option<UnixNanos> {
254        None
255    }
256
257    fn display_qty(&self) -> Option<Quantity> {
258        None
259    }
260
261    fn emulation_trigger(&self) -> Option<TriggerType> {
262        None
263    }
264
265    fn trigger_instrument_id(&self) -> Option<InstrumentId> {
266        None
267    }
268
269    fn contingency_type(&self) -> Option<ContingencyType> {
270        None
271    }
272
273    fn order_list_id(&self) -> Option<OrderListId> {
274        None
275    }
276
277    fn linked_order_ids(&self) -> Option<Vec<ClientOrderId>> {
278        None
279    }
280
281    fn parent_order_id(&self) -> Option<ClientOrderId> {
282        None
283    }
284
285    fn exec_algorithm_id(&self) -> Option<ExecAlgorithmId> {
286        None
287    }
288
289    fn exec_spawn_id(&self) -> Option<ClientOrderId> {
290        None
291    }
292
293    fn venue_order_id(&self) -> Option<VenueOrderId> {
294        self.venue_order_id
295    }
296
297    fn account_id(&self) -> Option<AccountId> {
298        self.account_id
299    }
300
301    fn position_id(&self) -> Option<PositionId> {
302        None
303    }
304
305    fn commission(&self) -> Option<Money> {
306        None
307    }
308
309    fn ts_event(&self) -> UnixNanos {
310        self.ts_event
311    }
312
313    fn ts_init(&self) -> UnixNanos {
314        self.ts_init
315    }
316}
317
318#[cfg(test)]
319mod tests {
320
321    use rstest::rstest;
322
323    use crate::events::order::{expired::OrderExpired, stubs::*};
324
325    #[rstest]
326    fn test_order_expired_display(order_expired: OrderExpired) {
327        let display = format!("{order_expired}");
328        assert_eq!(
329            display,
330            "OrderExpired(instrument_id=BTCUSDT.COINBASE, client_order_id=O-19700101-000000-001-001-1, venue_order_id=001, account_id=SIM-001, ts_event=0)"
331        );
332    }
333
334    #[rstest]
335    fn test_order_expired_serialization() {
336        let original = OrderExpired::default();
337        let json = serde_json::to_string(&original).unwrap();
338        let deserialized: OrderExpired = serde_json::from_str(&json).unwrap();
339        assert_eq!(original, deserialized);
340    }
341}