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, 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 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    #[serde(deserialize_with = "from_bool_as_u8")]
67    pub reconciliation: u8, // TODO: Change to bool once Cython removed
68    /// The venue order ID associated with the event.
69    pub venue_order_id: Option<VenueOrderId>,
70    /// The account ID associated with the event.
71    pub account_id: Option<AccountId>,
72}
73
74impl OrderTriggered {
75    /// Creates a new [`OrderTriggered`] 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        event_id: UUID4,
84        ts_event: UnixNanos,
85        ts_init: UnixNanos,
86        reconciliation: bool,
87        venue_order_id: Option<VenueOrderId>,
88        account_id: Option<AccountId>,
89    ) -> Self {
90        Self {
91            trader_id,
92            strategy_id,
93            instrument_id,
94            client_order_id,
95            event_id,
96            ts_event,
97            ts_init,
98            reconciliation: u8::from(reconciliation),
99            venue_order_id,
100            account_id,
101        }
102    }
103}
104
105impl Debug for OrderTriggered {
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!(OrderTriggered),
111            self.trader_id,
112            self.strategy_id,
113            self.instrument_id,
114            self.client_order_id,
115            self.venue_order_id
116                .map_or("None".to_string(), |venue_order_id| format!(
117                    "{venue_order_id}"
118                )),
119            self.account_id
120                .map_or("None".to_string(), |account_id| format!("{account_id}")),
121            self.event_id,
122            self.ts_event,
123            self.ts_init
124        )
125    }
126}
127
128impl Display for OrderTriggered {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        write!(
131            f,
132            "{}(instrument_id={}, client_order_id={}, venue_order_id={}, account_id={}, ts_event={})",
133            stringify!(OrderTriggered),
134            self.instrument_id,
135            self.client_order_id,
136            self.venue_order_id
137                .map_or("None".to_string(), |venue_order_id| format!(
138                    "{venue_order_id}"
139                )),
140            self.account_id
141                .map_or("None".to_string(), |account_id| format!("{account_id}")),
142            self.ts_event,
143        )
144    }
145}
146
147impl OrderEvent for OrderTriggered {
148    fn id(&self) -> UUID4 {
149        self.event_id
150    }
151
152    fn type_name(&self) -> &'static str {
153        stringify!(OrderTriggered)
154    }
155
156    fn order_type(&self) -> Option<OrderType> {
157        None
158    }
159
160    fn order_side(&self) -> Option<OrderSide> {
161        None
162    }
163
164    fn trader_id(&self) -> TraderId {
165        self.trader_id
166    }
167
168    fn strategy_id(&self) -> StrategyId {
169        self.strategy_id
170    }
171
172    fn instrument_id(&self) -> InstrumentId {
173        self.instrument_id
174    }
175
176    fn trade_id(&self) -> Option<TradeId> {
177        None
178    }
179
180    fn currency(&self) -> Option<Currency> {
181        None
182    }
183
184    fn client_order_id(&self) -> ClientOrderId {
185        self.client_order_id
186    }
187
188    fn reason(&self) -> Option<Ustr> {
189        None
190    }
191
192    fn quantity(&self) -> Option<Quantity> {
193        None
194    }
195
196    fn time_in_force(&self) -> Option<TimeInForce> {
197        None
198    }
199
200    fn liquidity_side(&self) -> Option<LiquiditySide> {
201        None
202    }
203
204    fn post_only(&self) -> Option<bool> {
205        None
206    }
207
208    fn reduce_only(&self) -> Option<bool> {
209        None
210    }
211
212    fn quote_quantity(&self) -> Option<bool> {
213        None
214    }
215
216    fn reconciliation(&self) -> bool {
217        false
218    }
219
220    fn price(&self) -> Option<Price> {
221        None
222    }
223
224    fn last_px(&self) -> Option<Price> {
225        None
226    }
227
228    fn last_qty(&self) -> Option<Quantity> {
229        None
230    }
231
232    fn trigger_price(&self) -> Option<Price> {
233        None
234    }
235
236    fn trigger_type(&self) -> Option<TriggerType> {
237        None
238    }
239
240    fn limit_offset(&self) -> Option<Decimal> {
241        None
242    }
243
244    fn trailing_offset(&self) -> Option<Decimal> {
245        None
246    }
247
248    fn trailing_offset_type(&self) -> Option<TrailingOffsetType> {
249        None
250    }
251
252    fn expire_time(&self) -> Option<UnixNanos> {
253        None
254    }
255
256    fn display_qty(&self) -> Option<Quantity> {
257        None
258    }
259
260    fn emulation_trigger(&self) -> Option<TriggerType> {
261        None
262    }
263
264    fn trigger_instrument_id(&self) -> Option<InstrumentId> {
265        None
266    }
267
268    fn contingency_type(&self) -> Option<ContingencyType> {
269        None
270    }
271
272    fn order_list_id(&self) -> Option<OrderListId> {
273        None
274    }
275
276    fn linked_order_ids(&self) -> Option<Vec<ClientOrderId>> {
277        None
278    }
279
280    fn parent_order_id(&self) -> Option<ClientOrderId> {
281        None
282    }
283
284    fn exec_algorithm_id(&self) -> Option<ExecAlgorithmId> {
285        None
286    }
287
288    fn exec_spawn_id(&self) -> Option<ClientOrderId> {
289        None
290    }
291
292    fn venue_order_id(&self) -> Option<VenueOrderId> {
293        self.venue_order_id
294    }
295
296    fn account_id(&self) -> Option<AccountId> {
297        self.account_id
298    }
299
300    fn position_id(&self) -> Option<PositionId> {
301        None
302    }
303
304    fn commission(&self) -> Option<Money> {
305        None
306    }
307
308    fn ts_event(&self) -> UnixNanos {
309        self.ts_event
310    }
311
312    fn ts_init(&self) -> UnixNanos {
313        self.ts_init
314    }
315}
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
333    #[rstest]
334    fn test_order_triggered_serialization() {
335        let original = OrderTriggered::default();
336        let json = serde_json::to_string(&original).unwrap();
337        let deserialized: OrderTriggered = serde_json::from_str(&json).unwrap();
338        assert_eq!(original, deserialized);
339    }
340}