nautilus_model/events/order/
cancel_rejected.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 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 derive_builder::Builder;
19use nautilus_core::{UUID4, UnixNanos, serialization::from_bool_as_u8};
20use rust_decimal::Decimal;
21use serde::{Deserialize, Serialize};
22use ustr::Ustr;
23
24use crate::{
25    enums::{
26        ContingencyType, LiquiditySide, OrderSide, OrderType, TimeInForce, TrailingOffsetType,
27        TriggerType,
28    },
29    events::OrderEvent,
30    identifiers::{
31        AccountId, ClientOrderId, ExecAlgorithmId, InstrumentId, OrderListId, PositionId,
32        StrategyId, TradeId, TraderId, VenueOrderId,
33    },
34    types::{Currency, Money, Price, Quantity},
35};
36
37/// Represents an event where a `CancelOrder` command has been rejected by the
38/// trading venue.
39#[repr(C)]
40#[derive(Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, Builder)]
41#[builder(default)]
42#[serde(tag = "type")]
43#[cfg_attr(
44    feature = "python",
45    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model")
46)]
47pub struct OrderCancelRejected {
48    /// The trader ID associated with the event.
49    pub trader_id: TraderId,
50    /// The strategy ID associated with the event.
51    pub strategy_id: StrategyId,
52    /// The instrument ID associated with the event.
53    pub instrument_id: InstrumentId,
54    /// The client order ID associated with the event.
55    pub client_order_id: ClientOrderId,
56    /// The reason the order cancel was rejected.
57    pub reason: Ustr,
58    /// The unique identifier for the event.
59    pub event_id: UUID4,
60    /// UNIX timestamp (nanoseconds) when the event occurred.
61    pub ts_event: UnixNanos,
62    /// UNIX timestamp (nanoseconds) when the event was initialized.
63    pub ts_init: UnixNanos,
64    /// If the event was generated during reconciliation.
65    #[serde(deserialize_with = "from_bool_as_u8")]
66    pub reconciliation: u8, // TODO: Change to bool once Cython removed
67    /// The venue order ID associated with the event.
68    pub venue_order_id: Option<VenueOrderId>,
69    /// The account ID associated with the event.
70    pub account_id: Option<AccountId>,
71}
72
73impl OrderCancelRejected {
74    /// Creates a new [`OrderCancelRejected`] instance.
75    #[allow(clippy::too_many_arguments)]
76    pub fn new(
77        trader_id: TraderId,
78        strategy_id: StrategyId,
79        instrument_id: InstrumentId,
80        client_order_id: ClientOrderId,
81        reason: Ustr,
82        event_id: UUID4,
83        ts_event: UnixNanos,
84        ts_init: UnixNanos,
85        reconciliation: bool,
86        venue_order_id: Option<VenueOrderId>,
87        account_id: Option<AccountId>,
88    ) -> Self {
89        Self {
90            trader_id,
91            strategy_id,
92            instrument_id,
93            client_order_id,
94            reason,
95            event_id,
96            ts_event,
97            ts_init,
98            reconciliation: u8::from(reconciliation),
99            venue_order_id,
100            account_id,
101        }
102    }
103}
104
105impl Debug for OrderCancelRejected {
106    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107        write!(
108            f,
109            "{}(trader_id={}, strategy_id={}, instrument_id={}, client_order_id={}, venue_order_id={}, account_id={}, reason='{}', event_id={}, ts_event={}, ts_init={})",
110            stringify!(OrderCancelRejected),
111            self.trader_id,
112            self.strategy_id,
113            self.instrument_id,
114            self.client_order_id,
115            self.venue_order_id.map_or_else(
116                || "None".to_string(),
117                |venue_order_id| format!("{venue_order_id}")
118            ),
119            self.account_id
120                .map_or_else(|| "None".to_string(), |account_id| format!("{account_id}")),
121            self.reason,
122            self.event_id,
123            self.ts_event,
124            self.ts_init
125        )
126    }
127}
128
129impl Display for OrderCancelRejected {
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={}, reason='{}', ts_event={})",
134            stringify!(OrderCancelRejected),
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.reason,
144            self.ts_event
145        )
146    }
147}
148
149impl OrderEvent for OrderCancelRejected {
150    fn id(&self) -> UUID4 {
151        self.event_id
152    }
153
154    fn kind(&self) -> &str {
155        stringify!(OrderCancelRejected)
156    }
157
158    fn order_type(&self) -> Option<OrderType> {
159        None
160    }
161
162    fn order_side(&self) -> Option<OrderSide> {
163        None
164    }
165
166    fn trader_id(&self) -> TraderId {
167        self.trader_id
168    }
169
170    fn strategy_id(&self) -> StrategyId {
171        self.strategy_id
172    }
173
174    fn instrument_id(&self) -> InstrumentId {
175        self.instrument_id
176    }
177
178    fn trade_id(&self) -> Option<TradeId> {
179        None
180    }
181
182    fn currency(&self) -> Option<Currency> {
183        None
184    }
185
186    fn client_order_id(&self) -> ClientOrderId {
187        self.client_order_id
188    }
189
190    fn reason(&self) -> Option<Ustr> {
191        Some(self.reason)
192    }
193
194    fn quantity(&self) -> Option<Quantity> {
195        None
196    }
197
198    fn time_in_force(&self) -> Option<TimeInForce> {
199        None
200    }
201
202    fn liquidity_side(&self) -> Option<LiquiditySide> {
203        None
204    }
205
206    fn post_only(&self) -> Option<bool> {
207        None
208    }
209
210    fn reduce_only(&self) -> Option<bool> {
211        None
212    }
213
214    fn quote_quantity(&self) -> Option<bool> {
215        None
216    }
217
218    fn reconciliation(&self) -> bool {
219        false
220    }
221
222    fn price(&self) -> Option<Price> {
223        None
224    }
225
226    fn last_px(&self) -> Option<Price> {
227        None
228    }
229
230    fn last_qty(&self) -> Option<Quantity> {
231        None
232    }
233
234    fn trigger_price(&self) -> Option<Price> {
235        None
236    }
237
238    fn trigger_type(&self) -> Option<TriggerType> {
239        None
240    }
241
242    fn limit_offset(&self) -> Option<Decimal> {
243        None
244    }
245
246    fn trailing_offset(&self) -> Option<Decimal> {
247        None
248    }
249
250    fn trailing_offset_type(&self) -> Option<TrailingOffsetType> {
251        None
252    }
253
254    fn expire_time(&self) -> Option<UnixNanos> {
255        None
256    }
257
258    fn display_qty(&self) -> Option<Quantity> {
259        None
260    }
261
262    fn emulation_trigger(&self) -> Option<TriggerType> {
263        None
264    }
265
266    fn trigger_instrument_id(&self) -> Option<InstrumentId> {
267        None
268    }
269
270    fn contingency_type(&self) -> Option<ContingencyType> {
271        None
272    }
273
274    fn order_list_id(&self) -> Option<OrderListId> {
275        None
276    }
277
278    fn linked_order_ids(&self) -> Option<Vec<ClientOrderId>> {
279        None
280    }
281
282    fn parent_order_id(&self) -> Option<ClientOrderId> {
283        None
284    }
285
286    fn exec_algorithm_id(&self) -> Option<ExecAlgorithmId> {
287        None
288    }
289
290    fn exec_spawn_id(&self) -> Option<ClientOrderId> {
291        None
292    }
293
294    fn venue_order_id(&self) -> Option<VenueOrderId> {
295        self.venue_order_id
296    }
297
298    fn account_id(&self) -> Option<AccountId> {
299        self.account_id
300    }
301
302    fn position_id(&self) -> Option<PositionId> {
303        None
304    }
305
306    fn commission(&self) -> Option<Money> {
307        None
308    }
309
310    fn ts_event(&self) -> UnixNanos {
311        self.ts_event
312    }
313
314    fn ts_init(&self) -> UnixNanos {
315        self.ts_init
316    }
317}
318
319////////////////////////////////////////////////////////////////////////////////
320// Tests
321////////////////////////////////////////////////////////////////////////////////
322#[cfg(test)]
323mod tests {
324
325    use rstest::rstest;
326
327    use crate::events::order::{cancel_rejected::OrderCancelRejected, stubs::*};
328
329    #[rstest]
330    fn test_order_cancel_rejected(order_cancel_rejected: OrderCancelRejected) {
331        let display = format!("{order_cancel_rejected}");
332        assert_eq!(
333            display,
334            "OrderCancelRejected(instrument_id=BTCUSDT.COINBASE, client_order_id=O-19700101-000000-001-001-1, venue_order_id=001, account_id=SIM-001, reason='ORDER_DOES_NOT_EXIST', ts_event=0)"
335        );
336    }
337}