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::{serialization::from_bool_as_u8, UnixNanos, UUID4};
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(|| "None".to_string(), |venue_order_id| format!("{venue_order_id}")),
116            self.account_id.map_or_else(|| "None".to_string(), |account_id| format!("{account_id}")),
117            self.reason,
118            self.event_id,
119            self.ts_event,
120            self.ts_init
121        )
122    }
123}
124
125impl Display for OrderCancelRejected {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        write!(
128            f,
129            "{}(instrument_id={}, client_order_id={}, venue_order_id={}, account_id={}, reason='{}', ts_event={})",
130            stringify!(OrderCancelRejected),
131            self.instrument_id,
132            self.client_order_id,
133            self.venue_order_id.map_or("None".to_string(), |venue_order_id| format!("{venue_order_id}")),
134            self.account_id.map_or("None".to_string(), |account_id| format!("{account_id}")),
135            self.reason,
136            self.ts_event
137        )
138    }
139}
140
141impl OrderEvent for OrderCancelRejected {
142    fn id(&self) -> UUID4 {
143        self.event_id
144    }
145
146    fn kind(&self) -> &str {
147        stringify!(OrderCancelRejected)
148    }
149
150    fn order_type(&self) -> Option<OrderType> {
151        None
152    }
153
154    fn order_side(&self) -> Option<OrderSide> {
155        None
156    }
157
158    fn trader_id(&self) -> TraderId {
159        self.trader_id
160    }
161
162    fn strategy_id(&self) -> StrategyId {
163        self.strategy_id
164    }
165
166    fn instrument_id(&self) -> InstrumentId {
167        self.instrument_id
168    }
169
170    fn trade_id(&self) -> Option<TradeId> {
171        None
172    }
173
174    fn currency(&self) -> Option<Currency> {
175        None
176    }
177
178    fn client_order_id(&self) -> ClientOrderId {
179        self.client_order_id
180    }
181
182    fn reason(&self) -> Option<Ustr> {
183        Some(self.reason)
184    }
185
186    fn quantity(&self) -> Option<Quantity> {
187        None
188    }
189
190    fn time_in_force(&self) -> Option<TimeInForce> {
191        None
192    }
193
194    fn liquidity_side(&self) -> Option<LiquiditySide> {
195        None
196    }
197
198    fn post_only(&self) -> Option<bool> {
199        None
200    }
201
202    fn reduce_only(&self) -> Option<bool> {
203        None
204    }
205
206    fn quote_quantity(&self) -> Option<bool> {
207        None
208    }
209
210    fn reconciliation(&self) -> bool {
211        false
212    }
213
214    fn price(&self) -> Option<Price> {
215        None
216    }
217
218    fn last_px(&self) -> Option<Price> {
219        None
220    }
221
222    fn last_qty(&self) -> Option<Quantity> {
223        None
224    }
225
226    fn trigger_price(&self) -> Option<Price> {
227        None
228    }
229
230    fn trigger_type(&self) -> Option<TriggerType> {
231        None
232    }
233
234    fn limit_offset(&self) -> Option<Decimal> {
235        None
236    }
237
238    fn trailing_offset(&self) -> Option<Decimal> {
239        None
240    }
241
242    fn trailing_offset_type(&self) -> Option<TrailingOffsetType> {
243        None
244    }
245
246    fn expire_time(&self) -> Option<UnixNanos> {
247        None
248    }
249
250    fn display_qty(&self) -> Option<Quantity> {
251        None
252    }
253
254    fn emulation_trigger(&self) -> Option<TriggerType> {
255        None
256    }
257
258    fn trigger_instrument_id(&self) -> Option<InstrumentId> {
259        None
260    }
261
262    fn contingency_type(&self) -> Option<ContingencyType> {
263        None
264    }
265
266    fn order_list_id(&self) -> Option<OrderListId> {
267        None
268    }
269
270    fn linked_order_ids(&self) -> Option<Vec<ClientOrderId>> {
271        None
272    }
273
274    fn parent_order_id(&self) -> Option<ClientOrderId> {
275        None
276    }
277
278    fn exec_algorithm_id(&self) -> Option<ExecAlgorithmId> {
279        None
280    }
281
282    fn exec_spawn_id(&self) -> Option<ClientOrderId> {
283        None
284    }
285
286    fn venue_order_id(&self) -> Option<VenueOrderId> {
287        self.venue_order_id
288    }
289
290    fn account_id(&self) -> Option<AccountId> {
291        self.account_id
292    }
293
294    fn position_id(&self) -> Option<PositionId> {
295        None
296    }
297
298    fn commission(&self) -> Option<Money> {
299        None
300    }
301
302    fn ts_event(&self) -> UnixNanos {
303        self.ts_event
304    }
305
306    fn ts_init(&self) -> UnixNanos {
307        self.ts_init
308    }
309}
310
311////////////////////////////////////////////////////////////////////////////////
312// Tests
313////////////////////////////////////////////////////////////////////////////////
314#[cfg(test)]
315mod tests {
316
317    use rstest::rstest;
318
319    use crate::events::order::{cancel_rejected::OrderCancelRejected, stubs::*};
320
321    #[rstest]
322    fn test_order_cancel_rejected(order_cancel_rejected: OrderCancelRejected) {
323        let display = format!("{order_cancel_rejected}");
324        assert_eq!(
325            display,
326            "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)"
327        );
328    }
329}