Skip to main content

nautilus_model/events/order/
rejected.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 been rejected by 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 OrderRejected {
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 account ID associated with the event.
58    pub account_id: AccountId,
59    /// The reason the order was rejected.
60    pub reason: Ustr,
61    /// The unique identifier for the event.
62    pub event_id: UUID4,
63    /// UNIX timestamp (nanoseconds) when the event occurred.
64    pub ts_event: UnixNanos,
65    /// UNIX timestamp (nanoseconds) when the event was initialized.
66    pub ts_init: UnixNanos,
67    /// If the event was generated during reconciliation.
68    #[serde(deserialize_with = "from_bool_as_u8")]
69    pub reconciliation: u8, // TODO: Change to bool once Cython removed
70    /// If the order was rejected because it was post-only and would execute immediately as a taker.
71    #[serde(default, deserialize_with = "from_bool_as_u8")]
72    pub due_post_only: u8, // TODO: Change to bool once Cython removed
73}
74
75impl OrderRejected {
76    /// Creates a new [`OrderRejected`] instance.
77    #[expect(clippy::too_many_arguments)]
78    #[must_use]
79    pub fn new(
80        trader_id: TraderId,
81        strategy_id: StrategyId,
82        instrument_id: InstrumentId,
83        client_order_id: ClientOrderId,
84        account_id: AccountId,
85        reason: Ustr,
86        event_id: UUID4,
87        ts_event: UnixNanos,
88        ts_init: UnixNanos,
89        reconciliation: bool,
90        due_post_only: bool,
91    ) -> Self {
92        Self {
93            trader_id,
94            strategy_id,
95            instrument_id,
96            client_order_id,
97            account_id,
98            reason,
99            event_id,
100            ts_event,
101            ts_init,
102            reconciliation: u8::from(reconciliation),
103            due_post_only: u8::from(due_post_only),
104        }
105    }
106}
107
108impl Debug for OrderRejected {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        write!(
111            f,
112            "{}(trader_id={}, strategy_id={}, instrument_id={}, client_order_id={}, account_id={}, reason='{}', event_id={}, ts_event={}, ts_init={})",
113            stringify!(OrderRejected),
114            self.trader_id,
115            self.strategy_id,
116            self.instrument_id,
117            self.client_order_id,
118            self.account_id,
119            self.reason,
120            self.event_id,
121            self.ts_event,
122            self.ts_init
123        )
124    }
125}
126
127impl Display for OrderRejected {
128    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129        write!(
130            f,
131            "{}(instrument_id={}, client_order_id={}, account_id={}, reason='{}', due_post_only={}, ts_event={})",
132            stringify!(OrderRejected),
133            self.instrument_id,
134            self.client_order_id,
135            self.account_id,
136            self.reason,
137            self.due_post_only != 0,
138            self.ts_event
139        )
140    }
141}
142
143impl OrderEvent for OrderRejected {
144    fn id(&self) -> UUID4 {
145        self.event_id
146    }
147
148    fn type_name(&self) -> &'static str {
149        stringify!(OrderRejected)
150    }
151
152    fn order_type(&self) -> Option<OrderType> {
153        None
154    }
155
156    fn order_side(&self) -> Option<OrderSide> {
157        None
158    }
159
160    fn trader_id(&self) -> TraderId {
161        self.trader_id
162    }
163
164    fn strategy_id(&self) -> StrategyId {
165        self.strategy_id
166    }
167
168    fn instrument_id(&self) -> InstrumentId {
169        self.instrument_id
170    }
171
172    fn trade_id(&self) -> Option<TradeId> {
173        None
174    }
175
176    fn currency(&self) -> Option<Currency> {
177        None
178    }
179
180    fn client_order_id(&self) -> ClientOrderId {
181        self.client_order_id
182    }
183
184    fn reason(&self) -> Option<Ustr> {
185        Some(self.reason)
186    }
187
188    fn quantity(&self) -> Option<Quantity> {
189        None
190    }
191
192    fn time_in_force(&self) -> Option<TimeInForce> {
193        None
194    }
195
196    fn liquidity_side(&self) -> Option<LiquiditySide> {
197        None
198    }
199
200    fn post_only(&self) -> Option<bool> {
201        None
202    }
203
204    fn reduce_only(&self) -> Option<bool> {
205        None
206    }
207
208    fn quote_quantity(&self) -> Option<bool> {
209        None
210    }
211
212    fn reconciliation(&self) -> bool {
213        false
214    }
215
216    fn price(&self) -> Option<Price> {
217        None
218    }
219
220    fn last_px(&self) -> Option<Price> {
221        None
222    }
223
224    fn last_qty(&self) -> Option<Quantity> {
225        None
226    }
227
228    fn trigger_price(&self) -> Option<Price> {
229        None
230    }
231
232    fn trigger_type(&self) -> Option<TriggerType> {
233        None
234    }
235
236    fn limit_offset(&self) -> Option<Decimal> {
237        None
238    }
239
240    fn trailing_offset(&self) -> Option<Decimal> {
241        None
242    }
243
244    fn trailing_offset_type(&self) -> Option<TrailingOffsetType> {
245        None
246    }
247
248    fn expire_time(&self) -> Option<UnixNanos> {
249        None
250    }
251
252    fn display_qty(&self) -> Option<Quantity> {
253        None
254    }
255
256    fn emulation_trigger(&self) -> Option<TriggerType> {
257        None
258    }
259
260    fn trigger_instrument_id(&self) -> Option<InstrumentId> {
261        None
262    }
263
264    fn contingency_type(&self) -> Option<ContingencyType> {
265        None
266    }
267
268    fn order_list_id(&self) -> Option<OrderListId> {
269        None
270    }
271
272    fn linked_order_ids(&self) -> Option<Vec<ClientOrderId>> {
273        None
274    }
275
276    fn parent_order_id(&self) -> Option<ClientOrderId> {
277        None
278    }
279
280    fn exec_algorithm_id(&self) -> Option<ExecAlgorithmId> {
281        None
282    }
283
284    fn exec_spawn_id(&self) -> Option<ClientOrderId> {
285        None
286    }
287
288    fn venue_order_id(&self) -> Option<VenueOrderId> {
289        None
290    }
291
292    fn account_id(&self) -> Option<AccountId> {
293        Some(self.account_id)
294    }
295
296    fn position_id(&self) -> Option<PositionId> {
297        None
298    }
299
300    fn commission(&self) -> Option<Money> {
301        None
302    }
303
304    fn ts_event(&self) -> UnixNanos {
305        self.ts_event
306    }
307
308    fn ts_init(&self) -> UnixNanos {
309        self.ts_init
310    }
311}
312
313#[cfg(test)]
314mod tests {
315    use nautilus_core::UnixNanos;
316    use rstest::rstest;
317    use ustr::Ustr;
318
319    use super::*;
320    use crate::events::order::stubs::*;
321
322    fn create_test_order_rejected() -> OrderRejected {
323        OrderRejected::new(
324            TraderId::from("TRADER-001"),
325            StrategyId::from("EMA-CROSS"),
326            InstrumentId::from("EURUSD.SIM"),
327            ClientOrderId::from("O-19700101-000000-001-001-1"),
328            AccountId::from("SIM-001"),
329            Ustr::from("INSUFFICIENT_MARGIN"),
330            UUID4::default(),
331            UnixNanos::from(1_000_000_000),
332            UnixNanos::from(2_000_000_000),
333            false,
334            false,
335        )
336    }
337
338    #[rstest]
339    fn test_order_rejected_display(order_rejected_insufficient_margin: OrderRejected) {
340        let display = format!("{order_rejected_insufficient_margin}");
341        assert_eq!(
342            display,
343            "OrderRejected(instrument_id=BTCUSDT.COINBASE, client_order_id=O-19700101-000000-001-001-1, \
344        account_id=SIM-001, reason='INSUFFICIENT_MARGIN', due_post_only=false, ts_event=0)"
345        );
346    }
347
348    #[rstest]
349    fn test_order_rejected_different_reasons() {
350        let mut insufficient_margin = create_test_order_rejected();
351        insufficient_margin.reason = Ustr::from("INSUFFICIENT_MARGIN");
352
353        let mut invalid_price = create_test_order_rejected();
354        invalid_price.reason = Ustr::from("INVALID_PRICE");
355
356        let mut market_closed = create_test_order_rejected();
357        market_closed.reason = Ustr::from("MARKET_CLOSED");
358
359        assert_ne!(insufficient_margin, invalid_price);
360        assert_ne!(invalid_price, market_closed);
361        assert_eq!(
362            insufficient_margin.reason,
363            Ustr::from("INSUFFICIENT_MARGIN")
364        );
365        assert_eq!(invalid_price.reason, Ustr::from("INVALID_PRICE"));
366        assert_eq!(market_closed.reason, Ustr::from("MARKET_CLOSED"));
367    }
368
369    // TODO: Remove once reconciliation field is converted back to bool (post-Cython)
370    #[rstest]
371    fn test_reconciliation_bool_to_u8() {
372        let event = OrderRejected::new(
373            TraderId::from("TRADER-001"),
374            StrategyId::from("EMA-CROSS"),
375            InstrumentId::from("EURUSD.SIM"),
376            ClientOrderId::from("O-19700101-000000-001-001-1"),
377            AccountId::from("SIM-001"),
378            Ustr::from("INSUFFICIENT_MARGIN"),
379            UUID4::default(),
380            UnixNanos::from(1_000_000_000),
381            UnixNanos::from(2_000_000_000),
382            true,
383            false,
384        );
385        assert_eq!(event.reconciliation, 1);
386    }
387
388    #[rstest]
389    fn test_order_rejected_serialization() {
390        let original = create_test_order_rejected();
391
392        let json = serde_json::to_string(&original).unwrap();
393        let deserialized: OrderRejected = serde_json::from_str(&json).unwrap();
394
395        assert_eq!(original, deserialized);
396    }
397
398    #[rstest]
399    fn test_order_rejected_with_due_post_only() {
400        let order_rejected = OrderRejected::new(
401            TraderId::from("TRADER-001"),
402            StrategyId::from("EMA-CROSS"),
403            InstrumentId::from("EURUSD.SIM"),
404            ClientOrderId::from("O-19700101-000000-001-001-1"),
405            AccountId::from("SIM-001"),
406            Ustr::from("POST_ONLY_WOULD_EXECUTE"),
407            UUID4::default(),
408            UnixNanos::from(1_000_000_000),
409            UnixNanos::from(2_000_000_000),
410            false,
411            true,
412        );
413
414        assert_eq!(order_rejected.due_post_only, 1);
415        assert_eq!(order_rejected.reason, Ustr::from("POST_ONLY_WOULD_EXECUTE"));
416    }
417}