nautilus_model/events/position/
opened.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 nautilus_core::{UUID4, UnixNanos};
17
18use crate::{
19    enums::{OrderSide, PositionSide},
20    events::OrderFilled,
21    identifiers::{AccountId, ClientOrderId, InstrumentId, PositionId, StrategyId, TraderId},
22    position::Position,
23    types::{Currency, Price, Quantity},
24};
25
26/// Represents an event where a position has been opened.
27#[repr(C)]
28#[derive(Clone, PartialEq, Debug)]
29pub struct PositionOpened {
30    /// The trader ID associated with the event.
31    pub trader_id: TraderId,
32    /// The strategy ID associated with the event.
33    pub strategy_id: StrategyId,
34    /// The instrument ID associated with the event.
35    pub instrument_id: InstrumentId,
36    /// The position ID associated with the event.
37    pub position_id: PositionId,
38    /// The account ID associated with the position.
39    pub account_id: AccountId,
40    /// The client order ID for the order which opened the position.
41    pub opening_order_id: ClientOrderId,
42    /// The position entry order side.
43    pub entry: OrderSide,
44    /// The position side.
45    pub side: PositionSide,
46    /// The current signed quantity (positive for position side `LONG`, negative for `SHORT`).
47    pub signed_qty: f64,
48    /// The current open quantity.
49    pub quantity: Quantity,
50    /// The last fill quantity for the position.
51    pub last_qty: Quantity,
52    /// The last fill price for the position.
53    pub last_px: Price,
54    /// The position quote currency.
55    pub currency: Currency,
56    /// The average open price.
57    pub avg_px_open: f64,
58    /// The unique identifier for the event.
59    pub event_id: UUID4,
60    /// UNIX timestamp (nanoseconds) when the event occurred.
61    pub ts_event: UnixNanos,
62    /// UNIX timestamp (nanoseconds) when the event was initialized.
63    pub ts_init: UnixNanos,
64}
65
66impl PositionOpened {
67    pub fn create(
68        position: &Position,
69        fill: &OrderFilled,
70        event_id: UUID4,
71        ts_init: UnixNanos,
72    ) -> Self {
73        Self {
74            trader_id: position.trader_id,
75            strategy_id: position.strategy_id,
76            instrument_id: position.instrument_id,
77            position_id: position.id,
78            account_id: position.account_id,
79            opening_order_id: position.opening_order_id,
80            entry: position.entry,
81            side: position.side,
82            signed_qty: position.signed_qty,
83            quantity: position.quantity,
84            last_qty: fill.last_qty,
85            last_px: fill.last_px,
86            currency: position.quote_currency,
87            avg_px_open: position.avg_px_open,
88            event_id,
89            ts_event: fill.ts_event,
90            ts_init,
91        }
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use nautilus_core::UnixNanos;
98    use rstest::*;
99
100    use super::*;
101    use crate::{
102        enums::{LiquiditySide, OrderSide, OrderType, PositionSide},
103        events::OrderFilled,
104        identifiers::{
105            AccountId, ClientOrderId, InstrumentId, PositionId, StrategyId, TradeId, TraderId,
106            VenueOrderId,
107        },
108        instruments::{InstrumentAny, stubs::audusd_sim},
109        position::Position,
110        types::{Currency, Money, Price, Quantity},
111    };
112
113    fn create_test_position_opened() -> PositionOpened {
114        PositionOpened {
115            trader_id: TraderId::from("TRADER-001"),
116            strategy_id: StrategyId::from("EMA-CROSS"),
117            instrument_id: InstrumentId::from("EURUSD.SIM"),
118            position_id: PositionId::from("P-001"),
119            account_id: AccountId::from("SIM-001"),
120            opening_order_id: ClientOrderId::from("O-19700101-000000-001-001-1"),
121            entry: OrderSide::Buy,
122            side: PositionSide::Long,
123            signed_qty: 100.0,
124            quantity: Quantity::from("100"),
125            last_qty: Quantity::from("100"),
126            last_px: Price::from("1.0500"),
127            currency: Currency::USD(),
128            avg_px_open: 1.0500,
129            event_id: Default::default(),
130            ts_event: UnixNanos::from(1_000_000_000),
131            ts_init: UnixNanos::from(2_000_000_000),
132        }
133    }
134
135    fn create_test_order_filled() -> OrderFilled {
136        OrderFilled::new(
137            TraderId::from("TRADER-001"),
138            StrategyId::from("EMA-CROSS"),
139            InstrumentId::from("AUD/USD.SIM"),
140            ClientOrderId::from("O-19700101-000000-001-001-1"),
141            VenueOrderId::from("1"),
142            AccountId::from("SIM-001"),
143            TradeId::from("T-001"),
144            OrderSide::Buy,
145            OrderType::Market,
146            Quantity::from("100"),
147            Price::from("0.8000"),
148            Currency::USD(),
149            LiquiditySide::Taker,
150            Default::default(),
151            UnixNanos::from(1_000_000_000),
152            UnixNanos::from(2_000_000_000),
153            false,
154            Some(PositionId::from("P-001")),
155            Some(Money::new(2.0, Currency::USD())),
156        )
157    }
158
159    #[rstest]
160    fn test_position_opened_new() {
161        let position_opened = create_test_position_opened();
162
163        assert_eq!(position_opened.trader_id, TraderId::from("TRADER-001"));
164        assert_eq!(position_opened.strategy_id, StrategyId::from("EMA-CROSS"));
165        assert_eq!(
166            position_opened.instrument_id,
167            InstrumentId::from("EURUSD.SIM")
168        );
169        assert_eq!(position_opened.position_id, PositionId::from("P-001"));
170        assert_eq!(position_opened.account_id, AccountId::from("SIM-001"));
171        assert_eq!(
172            position_opened.opening_order_id,
173            ClientOrderId::from("O-19700101-000000-001-001-1")
174        );
175        assert_eq!(position_opened.entry, OrderSide::Buy);
176        assert_eq!(position_opened.side, PositionSide::Long);
177        assert_eq!(position_opened.signed_qty, 100.0);
178        assert_eq!(position_opened.quantity, Quantity::from("100"));
179        assert_eq!(position_opened.last_qty, Quantity::from("100"));
180        assert_eq!(position_opened.last_px, Price::from("1.0500"));
181        assert_eq!(position_opened.currency, Currency::USD());
182        assert_eq!(position_opened.avg_px_open, 1.0500);
183        assert_eq!(position_opened.ts_event, UnixNanos::from(1_000_000_000));
184        assert_eq!(position_opened.ts_init, UnixNanos::from(2_000_000_000));
185    }
186
187    #[rstest]
188    fn test_position_opened_create() {
189        let instrument = audusd_sim();
190        let fill = create_test_order_filled();
191        let position = Position::new(&InstrumentAny::CurrencyPair(instrument), fill);
192        let event_id = Default::default();
193        let ts_init = UnixNanos::from(3_000_000_000);
194
195        let position_opened = PositionOpened::create(&position, &fill, event_id, ts_init);
196
197        assert_eq!(position_opened.trader_id, position.trader_id);
198        assert_eq!(position_opened.strategy_id, position.strategy_id);
199        assert_eq!(position_opened.instrument_id, position.instrument_id);
200        assert_eq!(position_opened.position_id, position.id);
201        assert_eq!(position_opened.account_id, position.account_id);
202        assert_eq!(position_opened.opening_order_id, position.opening_order_id);
203        assert_eq!(position_opened.entry, position.entry);
204        assert_eq!(position_opened.side, position.side);
205        assert_eq!(position_opened.signed_qty, position.signed_qty);
206        assert_eq!(position_opened.quantity, position.quantity);
207        assert_eq!(position_opened.last_qty, fill.last_qty);
208        assert_eq!(position_opened.last_px, fill.last_px);
209        assert_eq!(position_opened.currency, position.quote_currency);
210        assert_eq!(position_opened.avg_px_open, position.avg_px_open);
211        assert_eq!(position_opened.event_id, event_id);
212        assert_eq!(position_opened.ts_event, fill.ts_event);
213        assert_eq!(position_opened.ts_init, ts_init);
214    }
215
216    #[rstest]
217    fn test_position_opened_clone() {
218        let position_opened1 = create_test_position_opened();
219        let position_opened2 = position_opened1.clone();
220
221        assert_eq!(position_opened1, position_opened2);
222    }
223
224    #[rstest]
225    fn test_position_opened_debug() {
226        let position_opened = create_test_position_opened();
227        let debug_str = format!("{position_opened:?}");
228
229        assert!(debug_str.contains("PositionOpened"));
230        assert!(debug_str.contains("TRADER-001"));
231        assert!(debug_str.contains("EMA-CROSS"));
232        assert!(debug_str.contains("EURUSD.SIM"));
233        assert!(debug_str.contains("P-001"));
234    }
235
236    #[rstest]
237    fn test_position_opened_partial_eq() {
238        let mut position_opened1 = create_test_position_opened();
239        let mut position_opened2 = create_test_position_opened();
240        let event_id = Default::default();
241        position_opened1.event_id = event_id;
242        position_opened2.event_id = event_id;
243
244        let mut position_opened3 = create_test_position_opened();
245        position_opened3.event_id = event_id;
246        position_opened3.quantity = Quantity::from("200");
247
248        assert_eq!(position_opened1, position_opened2);
249        assert_ne!(position_opened1, position_opened3);
250    }
251
252    #[rstest]
253    fn test_position_opened_with_different_sides() {
254        let mut long_position = create_test_position_opened();
255        long_position.side = PositionSide::Long;
256        long_position.entry = OrderSide::Buy;
257        long_position.signed_qty = 100.0;
258
259        let mut short_position = create_test_position_opened();
260        short_position.side = PositionSide::Short;
261        short_position.entry = OrderSide::Sell;
262        short_position.signed_qty = -100.0;
263
264        assert_eq!(long_position.side, PositionSide::Long);
265        assert_eq!(long_position.entry, OrderSide::Buy);
266        assert_eq!(long_position.signed_qty, 100.0);
267
268        assert_eq!(short_position.side, PositionSide::Short);
269        assert_eq!(short_position.entry, OrderSide::Sell);
270        assert_eq!(short_position.signed_qty, -100.0);
271    }
272
273    #[rstest]
274    fn test_position_opened_different_currencies() {
275        let mut usd_position = create_test_position_opened();
276        usd_position.currency = Currency::USD();
277
278        let mut eur_position = create_test_position_opened();
279        eur_position.currency = Currency::EUR();
280
281        assert_eq!(usd_position.currency, Currency::USD());
282        assert_eq!(eur_position.currency, Currency::EUR());
283        assert_ne!(usd_position, eur_position);
284    }
285
286    #[rstest]
287    fn test_position_opened_timestamps() {
288        let position_opened = create_test_position_opened();
289
290        assert_eq!(position_opened.ts_event, UnixNanos::from(1_000_000_000));
291        assert_eq!(position_opened.ts_init, UnixNanos::from(2_000_000_000));
292        assert!(position_opened.ts_event < position_opened.ts_init);
293    }
294
295    #[rstest]
296    fn test_position_opened_quantities() {
297        let mut position_opened = create_test_position_opened();
298        position_opened.quantity = Quantity::from("500");
299        position_opened.last_qty = Quantity::from("250");
300
301        assert_eq!(position_opened.quantity, Quantity::from("500"));
302        assert_eq!(position_opened.last_qty, Quantity::from("250"));
303    }
304
305    #[rstest]
306    fn test_position_opened_prices() {
307        let mut position_opened = create_test_position_opened();
308        position_opened.last_px = Price::from("1.2345");
309        position_opened.avg_px_open = 1.2345;
310
311        assert_eq!(position_opened.last_px, Price::from("1.2345"));
312        assert_eq!(position_opened.avg_px_open, 1.2345);
313    }
314}