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