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::{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/// 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!(f,
105            "{}(trader_id={}, strategy_id={}, instrument_id={}, client_order_id={}, venue_order_id={}, account_id={}, event_id={}, ts_event={}, ts_init={})",
106            stringify!(OrderTriggered),
107            self.trader_id,
108            self.strategy_id,
109            self.instrument_id,
110            self.client_order_id,
111            self.venue_order_id.map_or("None".to_string(), |venue_order_id| format!("{venue_order_id}")),
112            self.account_id.map_or("None".to_string(), |account_id| format!("{account_id}")),
113            self.event_id,
114            self.ts_event,
115            self.ts_init
116        )
117    }
118}
119
120impl Display for OrderTriggered {
121    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122        write!(
123            f,
124            "{}(instrument_id={}, client_order_id={}, venue_order_id={}, account_id={}, ts_event={})",
125            stringify!(OrderTriggered),
126            self.instrument_id,
127            self.client_order_id,
128            self.venue_order_id
129                .map_or("None".to_string(), |venue_order_id| format!(
130                    "{venue_order_id}"
131                )),
132            self.account_id
133                .map_or("None".to_string(), |account_id| format!("{account_id}")),
134            self.ts_event,
135        )
136    }
137}
138
139impl OrderEvent for OrderTriggered {
140    fn id(&self) -> UUID4 {
141        self.event_id
142    }
143
144    fn kind(&self) -> &str {
145        stringify!(OrderTriggered)
146    }
147
148    fn order_type(&self) -> Option<OrderType> {
149        None
150    }
151
152    fn order_side(&self) -> Option<OrderSide> {
153        None
154    }
155
156    fn trader_id(&self) -> TraderId {
157        self.trader_id
158    }
159
160    fn strategy_id(&self) -> StrategyId {
161        self.strategy_id
162    }
163
164    fn instrument_id(&self) -> InstrumentId {
165        self.instrument_id
166    }
167
168    fn trade_id(&self) -> Option<TradeId> {
169        None
170    }
171
172    fn currency(&self) -> Option<Currency> {
173        None
174    }
175
176    fn client_order_id(&self) -> ClientOrderId {
177        self.client_order_id
178    }
179
180    fn reason(&self) -> Option<Ustr> {
181        None
182    }
183
184    fn quantity(&self) -> Option<Quantity> {
185        None
186    }
187
188    fn time_in_force(&self) -> Option<TimeInForce> {
189        None
190    }
191
192    fn liquidity_side(&self) -> Option<LiquiditySide> {
193        None
194    }
195
196    fn post_only(&self) -> Option<bool> {
197        None
198    }
199
200    fn reduce_only(&self) -> Option<bool> {
201        None
202    }
203
204    fn quote_quantity(&self) -> Option<bool> {
205        None
206    }
207
208    fn reconciliation(&self) -> bool {
209        false
210    }
211
212    fn price(&self) -> Option<Price> {
213        None
214    }
215
216    fn last_px(&self) -> Option<Price> {
217        None
218    }
219
220    fn last_qty(&self) -> Option<Quantity> {
221        None
222    }
223
224    fn trigger_price(&self) -> Option<Price> {
225        None
226    }
227
228    fn trigger_type(&self) -> Option<TriggerType> {
229        None
230    }
231
232    fn limit_offset(&self) -> Option<Decimal> {
233        None
234    }
235
236    fn trailing_offset(&self) -> Option<Decimal> {
237        None
238    }
239
240    fn trailing_offset_type(&self) -> Option<TrailingOffsetType> {
241        None
242    }
243
244    fn expire_time(&self) -> Option<UnixNanos> {
245        None
246    }
247
248    fn display_qty(&self) -> Option<Quantity> {
249        None
250    }
251
252    fn emulation_trigger(&self) -> Option<TriggerType> {
253        None
254    }
255
256    fn trigger_instrument_id(&self) -> Option<InstrumentId> {
257        None
258    }
259
260    fn contingency_type(&self) -> Option<ContingencyType> {
261        None
262    }
263
264    fn order_list_id(&self) -> Option<OrderListId> {
265        None
266    }
267
268    fn linked_order_ids(&self) -> Option<Vec<ClientOrderId>> {
269        None
270    }
271
272    fn parent_order_id(&self) -> Option<ClientOrderId> {
273        None
274    }
275
276    fn exec_algorithm_id(&self) -> Option<ExecAlgorithmId> {
277        None
278    }
279
280    fn exec_spawn_id(&self) -> Option<ClientOrderId> {
281        None
282    }
283
284    fn venue_order_id(&self) -> Option<VenueOrderId> {
285        self.venue_order_id
286    }
287
288    fn account_id(&self) -> Option<AccountId> {
289        self.account_id
290    }
291
292    fn position_id(&self) -> Option<PositionId> {
293        None
294    }
295
296    fn commission(&self) -> Option<Money> {
297        None
298    }
299
300    fn ts_event(&self) -> UnixNanos {
301        self.ts_event
302    }
303
304    fn ts_init(&self) -> UnixNanos {
305        self.ts_init
306    }
307}
308
309////////////////////////////////////////////////////////////////////////////////
310// Tests
311////////////////////////////////////////////////////////////////////////////////
312#[cfg(test)]
313mod tests {
314    use rstest::rstest;
315
316    use crate::events::order::{stubs::*, triggered::OrderTriggered};
317
318    #[rstest]
319    fn test_order_triggered_display(order_triggered: OrderTriggered) {
320        let display = format!("{order_triggered}");
321        assert_eq!(display, "OrderTriggered(instrument_id=BTCUSDT.COINBASE, client_order_id=O-19700101-000000-001-001-1, \
322        venue_order_id=001, account_id=SIM-001, ts_event=0)");
323    }
324}