Skip to main content

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