Skip to main content

nautilus_model/events/order/
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/// Represents an event where an order has been denied by the Nautilus system.
37///
38/// This could be due an unsupported feature, a risk limit exceedance, or for
39/// any other reason that an otherwise valid order is not able to be submitted.
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.core.nautilus_pyo3.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 OrderDenied {
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 order 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 causation ID associated with the event.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub causation_id: Option<UUID4>,
71}
72
73impl OrderDenied {
74    /// Creates a new [`OrderDenied`] instance.
75    #[expect(clippy::too_many_arguments)]
76    #[must_use]
77    pub fn new(
78        trader_id: TraderId,
79        strategy_id: StrategyId,
80        instrument_id: InstrumentId,
81        client_order_id: ClientOrderId,
82        reason: Ustr,
83        event_id: UUID4,
84        ts_event: UnixNanos,
85        ts_init: UnixNanos,
86    ) -> Self {
87        Self {
88            trader_id,
89            strategy_id,
90            instrument_id,
91            client_order_id,
92            reason,
93            event_id,
94            ts_event,
95            ts_init,
96            causation_id: None,
97        }
98    }
99}
100
101impl Debug for OrderDenied {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        write!(
104            f,
105            "{}(trader_id={}, strategy_id={}, instrument_id={}, client_order_id={}, reason='{}', event_id={}, ts_init={})",
106            stringify!(OrderDenied),
107            self.trader_id,
108            self.strategy_id,
109            self.instrument_id,
110            self.client_order_id,
111            self.reason,
112            self.event_id,
113            self.ts_init
114        )
115    }
116}
117
118impl Display for OrderDenied {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        write!(
121            f,
122            "{}(instrument_id={}, client_order_id={}, reason='{}')",
123            stringify!(OrderDenied),
124            self.instrument_id,
125            self.client_order_id,
126            self.reason
127        )
128    }
129}
130
131impl OrderEvent for OrderDenied {
132    fn id(&self) -> UUID4 {
133        self.event_id
134    }
135
136    fn type_name(&self) -> &'static str {
137        stringify!(OrderDenied)
138    }
139
140    fn order_type(&self) -> Option<OrderType> {
141        None
142    }
143
144    fn order_side(&self) -> Option<OrderSide> {
145        None
146    }
147
148    fn trader_id(&self) -> TraderId {
149        self.trader_id
150    }
151
152    fn strategy_id(&self) -> StrategyId {
153        self.strategy_id
154    }
155
156    fn instrument_id(&self) -> InstrumentId {
157        self.instrument_id
158    }
159
160    fn trade_id(&self) -> Option<TradeId> {
161        None
162    }
163
164    fn currency(&self) -> Option<Currency> {
165        None
166    }
167
168    fn client_order_id(&self) -> ClientOrderId {
169        self.client_order_id
170    }
171
172    fn reason(&self) -> Option<Ustr> {
173        Some(self.reason)
174    }
175
176    fn quantity(&self) -> Option<Quantity> {
177        None
178    }
179
180    fn time_in_force(&self) -> Option<TimeInForce> {
181        None
182    }
183
184    fn liquidity_side(&self) -> Option<LiquiditySide> {
185        None
186    }
187
188    fn post_only(&self) -> Option<bool> {
189        None
190    }
191
192    fn reduce_only(&self) -> Option<bool> {
193        None
194    }
195
196    fn quote_quantity(&self) -> Option<bool> {
197        None
198    }
199
200    fn reconciliation(&self) -> bool {
201        false
202    }
203
204    fn price(&self) -> Option<Price> {
205        None
206    }
207
208    fn last_px(&self) -> Option<Price> {
209        None
210    }
211
212    fn last_qty(&self) -> Option<Quantity> {
213        None
214    }
215
216    fn trigger_price(&self) -> Option<Price> {
217        None
218    }
219
220    fn trigger_type(&self) -> Option<TriggerType> {
221        None
222    }
223
224    fn limit_offset(&self) -> Option<Decimal> {
225        None
226    }
227
228    fn trailing_offset(&self) -> Option<Decimal> {
229        None
230    }
231
232    fn trailing_offset_type(&self) -> Option<TrailingOffsetType> {
233        None
234    }
235
236    fn expire_time(&self) -> Option<UnixNanos> {
237        None
238    }
239
240    fn display_qty(&self) -> Option<Quantity> {
241        None
242    }
243
244    fn emulation_trigger(&self) -> Option<TriggerType> {
245        None
246    }
247
248    fn trigger_instrument_id(&self) -> Option<InstrumentId> {
249        None
250    }
251
252    fn contingency_type(&self) -> Option<ContingencyType> {
253        None
254    }
255
256    fn order_list_id(&self) -> Option<OrderListId> {
257        None
258    }
259
260    fn linked_order_ids(&self) -> Option<Vec<ClientOrderId>> {
261        None
262    }
263
264    fn parent_order_id(&self) -> Option<ClientOrderId> {
265        None
266    }
267
268    fn exec_algorithm_id(&self) -> Option<ExecAlgorithmId> {
269        None
270    }
271
272    fn exec_spawn_id(&self) -> Option<ClientOrderId> {
273        None
274    }
275
276    fn venue_order_id(&self) -> Option<VenueOrderId> {
277        None
278    }
279
280    fn account_id(&self) -> Option<AccountId> {
281        None
282    }
283
284    fn position_id(&self) -> Option<PositionId> {
285        None
286    }
287
288    fn commission(&self) -> Option<Money> {
289        None
290    }
291
292    fn ts_event(&self) -> UnixNanos {
293        self.ts_event
294    }
295
296    fn ts_init(&self) -> UnixNanos {
297        self.ts_init
298    }
299}
300
301#[cfg(test)]
302mod tests {
303    use rstest::rstest;
304
305    use super::*;
306    use crate::events::order::stubs::*;
307
308    #[rstest]
309    fn test_order_denied_display(order_denied_max_submitted_rate: OrderDenied) {
310        let display = format!("{order_denied_max_submitted_rate}");
311        assert_eq!(
312            display,
313            "OrderDenied(instrument_id=BTCUSDT.COINBASE, client_order_id=O-19700101-000000-001-001-1, reason='RATE_LIMIT_EXCEEDED')"
314        );
315    }
316
317    #[rstest]
318    fn test_order_denied_serialization() {
319        let original = OrderDenied::default();
320        let json = serde_json::to_string(&original).unwrap();
321        let deserialized: OrderDenied = serde_json::from_str(&json).unwrap();
322        assert_eq!(original, deserialized);
323    }
324
325    #[rstest]
326    fn test_order_denied_serialization_with_causation_id() {
327        let causation_id = UUID4::new();
328        let original = OrderDenied {
329            causation_id: Some(causation_id),
330            ..OrderDenied::default()
331        };
332
333        let json = serde_json::to_string(&original).unwrap();
334        let deserialized: OrderDenied = serde_json::from_str(&json).unwrap();
335
336        assert!(json.contains("\"causation_id\""));
337        assert_eq!(deserialized.causation_id, Some(causation_id));
338        assert_eq!(original, deserialized);
339    }
340}