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, serialization::from_bool_as_u8};
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    #[serde(deserialize_with = "from_bool_as_u8")]
65    pub reconciliation: u8, // TODO: Change to bool once Cython removed
66    /// The venue order ID associated with the event.
67    pub venue_order_id: Option<VenueOrderId>,
68    /// The account ID associated with the event.
69    pub account_id: Option<AccountId>,
70}
71
72impl OrderExpired {
73    /// Creates a new [`OrderExpired`] instance.
74    #[expect(clippy::too_many_arguments)]
75    #[must_use]
76    pub fn new(
77        trader_id: TraderId,
78        strategy_id: StrategyId,
79        instrument_id: InstrumentId,
80        client_order_id: ClientOrderId,
81        event_id: UUID4,
82        ts_event: UnixNanos,
83        ts_init: UnixNanos,
84        reconciliation: bool,
85        venue_order_id: Option<VenueOrderId>,
86        account_id: Option<AccountId>,
87    ) -> Self {
88        Self {
89            trader_id,
90            strategy_id,
91            instrument_id,
92            client_order_id,
93            event_id,
94            ts_event,
95            ts_init,
96            reconciliation: u8::from(reconciliation),
97            venue_order_id,
98            account_id,
99        }
100    }
101}
102
103impl Debug for OrderExpired {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        write!(
106            f,
107            "{}(trader_id={}, strategy_id={}, instrument_id={}, client_order_id={}, venue_order_id={}, account_id={}, event_id={}, ts_event={}, ts_init={})",
108            stringify!(OrderExpired),
109            self.trader_id,
110            self.strategy_id,
111            self.instrument_id,
112            self.client_order_id,
113            self.venue_order_id.map_or_else(
114                || "None".to_string(),
115                |venue_order_id| format!("{venue_order_id}")
116            ),
117            self.account_id
118                .map_or_else(|| "None".to_string(), |account_id| format!("{account_id}")),
119            self.event_id,
120            self.ts_event,
121            self.ts_init
122        )
123    }
124}
125
126impl Display for OrderExpired {
127    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128        write!(
129            f,
130            "{}(instrument_id={}, client_order_id={}, venue_order_id={}, account_id={}, ts_event={})",
131            stringify!(OrderExpired),
132            self.instrument_id,
133            self.client_order_id,
134            self.venue_order_id
135                .map_or("None".to_string(), |venue_order_id| format!(
136                    "{venue_order_id}"
137                )),
138            self.account_id
139                .map_or("None".to_string(), |account_id| format!("{account_id}")),
140            self.ts_event
141        )
142    }
143}
144
145impl OrderEvent for OrderExpired {
146    fn id(&self) -> UUID4 {
147        self.event_id
148    }
149
150    fn type_name(&self) -> &'static str {
151        stringify!(OrderExpired)
152    }
153
154    fn order_type(&self) -> Option<OrderType> {
155        None
156    }
157
158    fn order_side(&self) -> Option<OrderSide> {
159        None
160    }
161
162    fn trader_id(&self) -> TraderId {
163        self.trader_id
164    }
165
166    fn strategy_id(&self) -> StrategyId {
167        self.strategy_id
168    }
169
170    fn instrument_id(&self) -> InstrumentId {
171        self.instrument_id
172    }
173
174    fn trade_id(&self) -> Option<TradeId> {
175        None
176    }
177
178    fn currency(&self) -> Option<Currency> {
179        None
180    }
181
182    fn client_order_id(&self) -> ClientOrderId {
183        self.client_order_id
184    }
185
186    fn reason(&self) -> Option<Ustr> {
187        None
188    }
189
190    fn quantity(&self) -> Option<Quantity> {
191        None
192    }
193
194    fn time_in_force(&self) -> Option<TimeInForce> {
195        None
196    }
197
198    fn liquidity_side(&self) -> Option<LiquiditySide> {
199        None
200    }
201
202    fn post_only(&self) -> Option<bool> {
203        None
204    }
205
206    fn reduce_only(&self) -> Option<bool> {
207        None
208    }
209
210    fn quote_quantity(&self) -> Option<bool> {
211        None
212    }
213
214    fn reconciliation(&self) -> bool {
215        false
216    }
217
218    fn price(&self) -> Option<Price> {
219        None
220    }
221
222    fn last_px(&self) -> Option<Price> {
223        None
224    }
225
226    fn last_qty(&self) -> Option<Quantity> {
227        None
228    }
229
230    fn trigger_price(&self) -> Option<Price> {
231        None
232    }
233
234    fn trigger_type(&self) -> Option<TriggerType> {
235        None
236    }
237
238    fn limit_offset(&self) -> Option<Decimal> {
239        None
240    }
241
242    fn trailing_offset(&self) -> Option<Decimal> {
243        None
244    }
245
246    fn trailing_offset_type(&self) -> Option<TrailingOffsetType> {
247        None
248    }
249
250    fn expire_time(&self) -> Option<UnixNanos> {
251        None
252    }
253
254    fn display_qty(&self) -> Option<Quantity> {
255        None
256    }
257
258    fn emulation_trigger(&self) -> Option<TriggerType> {
259        None
260    }
261
262    fn trigger_instrument_id(&self) -> Option<InstrumentId> {
263        None
264    }
265
266    fn contingency_type(&self) -> Option<ContingencyType> {
267        None
268    }
269
270    fn order_list_id(&self) -> Option<OrderListId> {
271        None
272    }
273
274    fn linked_order_ids(&self) -> Option<Vec<ClientOrderId>> {
275        None
276    }
277
278    fn parent_order_id(&self) -> Option<ClientOrderId> {
279        None
280    }
281
282    fn exec_algorithm_id(&self) -> Option<ExecAlgorithmId> {
283        None
284    }
285
286    fn exec_spawn_id(&self) -> Option<ClientOrderId> {
287        None
288    }
289
290    fn venue_order_id(&self) -> Option<VenueOrderId> {
291        self.venue_order_id
292    }
293
294    fn account_id(&self) -> Option<AccountId> {
295        self.account_id
296    }
297
298    fn position_id(&self) -> Option<PositionId> {
299        None
300    }
301
302    fn commission(&self) -> Option<Money> {
303        None
304    }
305
306    fn ts_event(&self) -> UnixNanos {
307        self.ts_event
308    }
309
310    fn ts_init(&self) -> UnixNanos {
311        self.ts_init
312    }
313}
314
315#[cfg(test)]
316mod tests {
317
318    use rstest::rstest;
319
320    use crate::events::order::{expired::OrderExpired, stubs::*};
321
322    #[rstest]
323    fn test_order_expired_display(order_expired: OrderExpired) {
324        let display = format!("{order_expired}");
325        assert_eq!(
326            display,
327            "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)"
328        );
329    }
330
331    #[rstest]
332    fn test_order_expired_serialization() {
333        let original = OrderExpired::default();
334        let json = serde_json::to_string(&original).unwrap();
335        let deserialized: OrderExpired = serde_json::from_str(&json).unwrap();
336        assert_eq!(original, deserialized);
337    }
338}