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