Skip to main content

nautilus_model/events/order/
cancel_denied.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/// Reports a cancel command that was proven not sent.
37///
38/// This command outcome preserves the existing order and does not close it.
39/// `causation_id` identifies the refused command when available.
40#[repr(C)]
41#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(tag = "type")]
43#[cfg_attr(
44    feature = "python",
45    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
46)]
47#[cfg_attr(
48    feature = "python",
49    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
50)]
51pub struct OrderCancelDenied {
52    /// The trader ID associated with the event.
53    pub trader_id: TraderId,
54    /// The strategy ID associated with the event.
55    pub strategy_id: StrategyId,
56    /// The instrument ID associated with the event.
57    pub instrument_id: InstrumentId,
58    /// The client order ID associated with the event.
59    pub client_order_id: ClientOrderId,
60    /// The reason the cancel command was denied.
61    pub reason: Ustr,
62    /// The unique identifier for the event.
63    pub event_id: UUID4,
64    /// UNIX timestamp (nanoseconds) when the event occurred.
65    pub ts_event: UnixNanos,
66    /// UNIX timestamp (nanoseconds) when the event was initialized.
67    pub ts_init: UnixNanos,
68    /// The venue order ID associated with the command, if known.
69    pub venue_order_id: Option<VenueOrderId>,
70    /// The account ID associated with the command, if known.
71    pub account_id: Option<AccountId>,
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 OrderCancelDenied {
78    /// Creates a new [`OrderCancelDenied`] 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        reason: Ustr,
87        event_id: UUID4,
88        ts_event: UnixNanos,
89        ts_init: UnixNanos,
90        venue_order_id: Option<VenueOrderId>,
91        account_id: Option<AccountId>,
92    ) -> Self {
93        Self {
94            trader_id,
95            strategy_id,
96            instrument_id,
97            client_order_id,
98            reason,
99            event_id,
100            ts_event,
101            ts_init,
102            venue_order_id,
103            account_id,
104            causation_id: None,
105        }
106    }
107}
108
109impl Debug for OrderCancelDenied {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        write!(
112            f,
113            "{}(trader_id={}, strategy_id={}, instrument_id={}, client_order_id={}, reason='{}', event_id={}, ts_init={})",
114            stringify!(OrderCancelDenied),
115            self.trader_id,
116            self.strategy_id,
117            self.instrument_id,
118            self.client_order_id,
119            self.reason,
120            self.event_id,
121            self.ts_init
122        )
123    }
124}
125
126impl Display for OrderCancelDenied {
127    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128        write!(
129            f,
130            "{}(instrument_id={}, client_order_id={}, reason='{}')",
131            stringify!(OrderCancelDenied),
132            self.instrument_id,
133            self.client_order_id,
134            self.reason
135        )
136    }
137}
138
139impl OrderEvent for OrderCancelDenied {
140    fn id(&self) -> UUID4 {
141        self.event_id
142    }
143
144    fn type_name(&self) -> &'static str {
145        stringify!(OrderCancelDenied)
146    }
147
148    fn order_type(&self) -> Option<OrderType> {
149        None
150    }
151
152    fn order_side(&self) -> Option<OrderSide> {
153        None
154    }
155
156    fn trader_id(&self) -> TraderId {
157        self.trader_id
158    }
159
160    fn strategy_id(&self) -> StrategyId {
161        self.strategy_id
162    }
163
164    fn instrument_id(&self) -> InstrumentId {
165        self.instrument_id
166    }
167
168    fn trade_id(&self) -> Option<TradeId> {
169        None
170    }
171
172    fn currency(&self) -> Option<Currency> {
173        None
174    }
175
176    fn client_order_id(&self) -> ClientOrderId {
177        self.client_order_id
178    }
179
180    fn reason(&self) -> Option<Ustr> {
181        Some(self.reason)
182    }
183
184    fn quantity(&self) -> Option<Quantity> {
185        None
186    }
187
188    fn time_in_force(&self) -> Option<TimeInForce> {
189        None
190    }
191
192    fn liquidity_side(&self) -> Option<LiquiditySide> {
193        None
194    }
195
196    fn post_only(&self) -> Option<bool> {
197        None
198    }
199
200    fn reduce_only(&self) -> Option<bool> {
201        None
202    }
203
204    fn quote_quantity(&self) -> Option<bool> {
205        None
206    }
207
208    fn reconciliation(&self) -> bool {
209        false
210    }
211
212    fn price(&self) -> Option<Price> {
213        None
214    }
215
216    fn last_px(&self) -> Option<Price> {
217        None
218    }
219
220    fn last_qty(&self) -> Option<Quantity> {
221        None
222    }
223
224    fn activation_price(&self) -> Option<Price> {
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        self.venue_order_id
290    }
291
292    fn account_id(&self) -> Option<AccountId> {
293        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    fn causation_id(&self) -> Option<UUID4> {
313        self.causation_id
314    }
315}
316
317#[cfg(test)]
318mod tests {
319    use nautilus_core::UUID4;
320    use rstest::rstest;
321
322    use super::*;
323    use crate::events::order::spec::OrderCancelDeniedSpec;
324
325    #[rstest]
326    #[case(None)]
327    #[case(Some(UUID4::new()))]
328    fn test_serialization_preserves_command_outcome(#[case] causation_id: Option<UUID4>) {
329        let original = OrderCancelDeniedSpec::builder()
330            .reason(Ustr::from("COMMAND_NOT_SENT"))
331            .ts_event(UnixNanos::from(123))
332            .ts_init(UnixNanos::from(456))
333            .venue_order_id(VenueOrderId::from("V-DENIED-123"))
334            .account_id(AccountId::from("ACCOUNT-DENIED"))
335            .maybe_causation_id(causation_id)
336            .build();
337
338        let json = serde_json::to_string(&original).unwrap();
339        let restored: OrderCancelDenied = serde_json::from_str(&json).unwrap();
340
341        assert_eq!(restored, original);
342        assert!(!restored.reconciliation());
343    }
344}