Skip to main content

nautilus_model/events/order/
accepted.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, serialization::from_bool_as_u8};
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 accepted by the trading venue.
37///
38/// This event often corresponds to a `NEW` `OrdStatus` <39> field in FIX execution reports.
39#[repr(C)]
40#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(tag = "type")]
42#[cfg_attr(
43    feature = "python",
44    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model", from_py_object)
45)]
46#[cfg_attr(
47    feature = "python",
48    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
49)]
50pub struct OrderAccepted {
51    /// The trader ID associated with the event.
52    pub trader_id: TraderId,
53    /// The strategy ID associated with the event.
54    pub strategy_id: StrategyId,
55    /// The instrument ID associated with the event.
56    pub instrument_id: InstrumentId,
57    /// The client order ID associated with the event.
58    pub client_order_id: ClientOrderId,
59    /// The venue order ID associated with the event.
60    pub venue_order_id: VenueOrderId,
61    /// The account ID associated with the event.
62    pub account_id: AccountId,
63    /// The unique identifier for the event.
64    pub event_id: UUID4,
65    /// UNIX timestamp (nanoseconds) when the event occurred.
66    pub ts_event: UnixNanos,
67    /// UNIX timestamp (nanoseconds) when the event was initialized.
68    pub ts_init: UnixNanos,
69    /// If the event was generated during reconciliation.
70    #[serde(deserialize_with = "from_bool_as_u8")]
71    pub reconciliation: u8, // TODO: Change to bool once Cython removed
72}
73
74impl OrderAccepted {
75    /// Creates a new [`OrderAccepted`] instance.
76    #[expect(clippy::too_many_arguments)]
77    #[must_use]
78    pub fn new(
79        trader_id: TraderId,
80        strategy_id: StrategyId,
81        instrument_id: InstrumentId,
82        client_order_id: ClientOrderId,
83        venue_order_id: VenueOrderId,
84        account_id: AccountId,
85        event_id: UUID4,
86        ts_event: UnixNanos,
87        ts_init: UnixNanos,
88        reconciliation: bool,
89    ) -> Self {
90        Self {
91            trader_id,
92            strategy_id,
93            instrument_id,
94            client_order_id,
95            venue_order_id,
96            account_id,
97            event_id,
98            ts_event,
99            ts_init,
100            reconciliation: u8::from(reconciliation),
101        }
102    }
103}
104
105impl Debug for OrderAccepted {
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={}, event_id={}, ts_event={}, ts_init={})",
110            stringify!(OrderAccepted),
111            self.trader_id,
112            self.strategy_id,
113            self.instrument_id,
114            self.client_order_id,
115            self.venue_order_id,
116            self.account_id,
117            self.event_id,
118            self.ts_event,
119            self.ts_init
120        )
121    }
122}
123
124impl Display for OrderAccepted {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        write!(
127            f,
128            "{}(instrument_id={}, client_order_id={}, venue_order_id={}, account_id={}, ts_event={})",
129            stringify!(OrderAccepted),
130            self.instrument_id,
131            self.client_order_id,
132            self.venue_order_id,
133            self.account_id,
134            self.ts_event
135        )
136    }
137}
138
139impl OrderEvent for OrderAccepted {
140    fn id(&self) -> UUID4 {
141        self.event_id
142    }
143
144    fn type_name(&self) -> &'static str {
145        stringify!(OrderAccepted)
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        None
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 trigger_price(&self) -> Option<Price> {
225        None
226    }
227
228    fn trigger_type(&self) -> Option<TriggerType> {
229        None
230    }
231
232    fn limit_offset(&self) -> Option<Decimal> {
233        None
234    }
235
236    fn trailing_offset(&self) -> Option<Decimal> {
237        None
238    }
239
240    fn trailing_offset_type(&self) -> Option<TrailingOffsetType> {
241        None
242    }
243
244    fn expire_time(&self) -> Option<UnixNanos> {
245        None
246    }
247
248    fn display_qty(&self) -> Option<Quantity> {
249        None
250    }
251
252    fn emulation_trigger(&self) -> Option<TriggerType> {
253        None
254    }
255
256    fn trigger_instrument_id(&self) -> Option<InstrumentId> {
257        None
258    }
259
260    fn contingency_type(&self) -> Option<ContingencyType> {
261        None
262    }
263
264    fn order_list_id(&self) -> Option<OrderListId> {
265        None
266    }
267
268    fn linked_order_ids(&self) -> Option<Vec<ClientOrderId>> {
269        None
270    }
271
272    fn parent_order_id(&self) -> Option<ClientOrderId> {
273        None
274    }
275
276    fn exec_algorithm_id(&self) -> Option<ExecAlgorithmId> {
277        None
278    }
279
280    fn exec_spawn_id(&self) -> Option<ClientOrderId> {
281        None
282    }
283
284    fn venue_order_id(&self) -> Option<VenueOrderId> {
285        Some(self.venue_order_id)
286    }
287
288    fn account_id(&self) -> Option<AccountId> {
289        Some(self.account_id)
290    }
291
292    fn position_id(&self) -> Option<PositionId> {
293        None
294    }
295
296    fn commission(&self) -> Option<Money> {
297        None
298    }
299
300    fn ts_event(&self) -> UnixNanos {
301        self.ts_event
302    }
303
304    fn ts_init(&self) -> UnixNanos {
305        self.ts_init
306    }
307}
308
309#[cfg(test)]
310mod tests {
311    use nautilus_core::UnixNanos;
312    use rstest::rstest;
313
314    use super::*;
315    use crate::events::order::stubs::*;
316
317    fn create_test_order_accepted() -> OrderAccepted {
318        OrderAccepted::new(
319            TraderId::from("TRADER-001"),
320            StrategyId::from("EMA-CROSS"),
321            InstrumentId::from("EURUSD.SIM"),
322            ClientOrderId::from("O-19700101-000000-001-001-1"),
323            VenueOrderId::from("V-001"),
324            AccountId::from("SIM-001"),
325            UUID4::default(),
326            UnixNanos::from(1_000_000_000),
327            UnixNanos::from(2_000_000_000),
328            false,
329        )
330    }
331
332    #[rstest]
333    fn test_order_accepted_display(order_accepted: OrderAccepted) {
334        let display = format!("{order_accepted}");
335        assert_eq!(
336            display,
337            "OrderAccepted(instrument_id=BTCUSDT.COINBASE, client_order_id=O-19700101-000000-001-001-1, venue_order_id=001, account_id=SIM-001, ts_event=0)"
338        );
339    }
340
341    // TODO: Remove once reconciliation field is converted back to bool (post-Cython)
342    #[rstest]
343    fn test_reconciliation_bool_to_u8() {
344        let mut event = create_test_order_accepted();
345        event = OrderAccepted::new(
346            event.trader_id,
347            event.strategy_id,
348            event.instrument_id,
349            event.client_order_id,
350            event.venue_order_id,
351            event.account_id,
352            event.event_id,
353            event.ts_event,
354            event.ts_init,
355            true,
356        );
357        assert_eq!(event.reconciliation, 1);
358    }
359
360    #[rstest]
361    fn test_order_accepted_serialization() {
362        let original = create_test_order_accepted();
363
364        let json = serde_json::to_string(&original).unwrap();
365        let deserialized: OrderAccepted = serde_json::from_str(&json).unwrap();
366
367        assert_eq!(original, deserialized);
368    }
369}