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