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.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    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        false
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 trigger_price(&self) -> Option<Price> {
232        None
233    }
234
235    fn trigger_type(&self) -> Option<TriggerType> {
236        None
237    }
238
239    fn limit_offset(&self) -> Option<Decimal> {
240        None
241    }
242
243    fn trailing_offset(&self) -> Option<Decimal> {
244        None
245    }
246
247    fn trailing_offset_type(&self) -> Option<TrailingOffsetType> {
248        None
249    }
250
251    fn expire_time(&self) -> Option<UnixNanos> {
252        None
253    }
254
255    fn display_qty(&self) -> Option<Quantity> {
256        None
257    }
258
259    fn emulation_trigger(&self) -> Option<TriggerType> {
260        None
261    }
262
263    fn trigger_instrument_id(&self) -> Option<InstrumentId> {
264        None
265    }
266
267    fn contingency_type(&self) -> Option<ContingencyType> {
268        None
269    }
270
271    fn order_list_id(&self) -> Option<OrderListId> {
272        None
273    }
274
275    fn linked_order_ids(&self) -> Option<Vec<ClientOrderId>> {
276        None
277    }
278
279    fn parent_order_id(&self) -> Option<ClientOrderId> {
280        None
281    }
282
283    fn exec_algorithm_id(&self) -> Option<ExecAlgorithmId> {
284        None
285    }
286
287    fn exec_spawn_id(&self) -> Option<ClientOrderId> {
288        None
289    }
290
291    fn venue_order_id(&self) -> Option<VenueOrderId> {
292        None
293    }
294
295    fn account_id(&self) -> Option<AccountId> {
296        Some(self.account_id)
297    }
298
299    fn position_id(&self) -> Option<PositionId> {
300        None
301    }
302
303    fn commission(&self) -> Option<Money> {
304        None
305    }
306
307    fn ts_event(&self) -> UnixNanos {
308        self.ts_event
309    }
310
311    fn ts_init(&self) -> UnixNanos {
312        self.ts_init
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use nautilus_core::UnixNanos;
319    use rstest::rstest;
320    use ustr::Ustr;
321
322    use super::*;
323    use crate::events::order::stubs::*;
324
325    fn create_test_order_rejected() -> OrderRejected {
326        OrderRejected::new(
327            TraderId::from("TRADER-001"),
328            StrategyId::from("EMA-CROSS"),
329            InstrumentId::from("EURUSD.SIM"),
330            ClientOrderId::from("O-19700101-000000-001-001-1"),
331            AccountId::from("SIM-001"),
332            Ustr::from("INSUFFICIENT_MARGIN"),
333            UUID4::default(),
334            UnixNanos::from(1_000_000_000),
335            UnixNanos::from(2_000_000_000),
336            false,
337            false,
338        )
339    }
340
341    #[rstest]
342    fn test_order_rejected_display(order_rejected_insufficient_margin: OrderRejected) {
343        let display = format!("{order_rejected_insufficient_margin}");
344        assert_eq!(
345            display,
346            "OrderRejected(instrument_id=BTCUSDT.COINBASE, client_order_id=O-19700101-000000-001-001-1, \
347        account_id=SIM-001, reason='INSUFFICIENT_MARGIN', due_post_only=false, ts_event=0)"
348        );
349    }
350
351    #[rstest]
352    fn test_order_rejected_different_reasons() {
353        let mut insufficient_margin = create_test_order_rejected();
354        insufficient_margin.reason = Ustr::from("INSUFFICIENT_MARGIN");
355
356        let mut invalid_price = create_test_order_rejected();
357        invalid_price.reason = Ustr::from("INVALID_PRICE");
358
359        let mut market_closed = create_test_order_rejected();
360        market_closed.reason = Ustr::from("MARKET_CLOSED");
361
362        assert_ne!(insufficient_margin, invalid_price);
363        assert_ne!(invalid_price, market_closed);
364        assert_eq!(
365            insufficient_margin.reason,
366            Ustr::from("INSUFFICIENT_MARGIN")
367        );
368        assert_eq!(invalid_price.reason, Ustr::from("INVALID_PRICE"));
369        assert_eq!(market_closed.reason, Ustr::from("MARKET_CLOSED"));
370    }
371
372    #[rstest]
373    fn test_order_rejected_serialization() {
374        let original = create_test_order_rejected();
375
376        let json = serde_json::to_string(&original).unwrap();
377        let deserialized: OrderRejected = serde_json::from_str(&json).unwrap();
378
379        assert_eq!(original, deserialized);
380    }
381
382    #[rstest]
383    fn test_order_rejected_with_due_post_only() {
384        let order_rejected = OrderRejected::new(
385            TraderId::from("TRADER-001"),
386            StrategyId::from("EMA-CROSS"),
387            InstrumentId::from("EURUSD.SIM"),
388            ClientOrderId::from("O-19700101-000000-001-001-1"),
389            AccountId::from("SIM-001"),
390            Ustr::from("POST_ONLY_WOULD_EXECUTE"),
391            UUID4::default(),
392            UnixNanos::from(1_000_000_000),
393            UnixNanos::from(2_000_000_000),
394            false,
395            true,
396        );
397
398        assert!(order_rejected.due_post_only);
399        assert_eq!(order_rejected.reason, Ustr::from("POST_ONLY_WOULD_EXECUTE"));
400    }
401}