Skip to main content

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