Skip to main content

nautilus_model/events/position/
mod.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 serde::{Deserialize, Serialize};
17
18use crate::{
19    events::{PositionAdjusted, PositionChanged, PositionClosed, PositionOpened},
20    identifiers::{AccountId, InstrumentId},
21};
22pub mod adjusted;
23pub mod changed;
24pub mod closed;
25pub mod opened;
26pub mod snapshot;
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub enum PositionEvent {
30    PositionOpened(PositionOpened),
31    PositionChanged(PositionChanged),
32    PositionClosed(PositionClosed),
33    PositionAdjusted(PositionAdjusted),
34}
35
36impl PositionEvent {
37    #[must_use]
38    pub fn instrument_id(&self) -> InstrumentId {
39        match self {
40            Self::PositionOpened(position) => position.instrument_id,
41            Self::PositionChanged(position) => position.instrument_id,
42            Self::PositionClosed(position) => position.instrument_id,
43            Self::PositionAdjusted(adjustment) => adjustment.instrument_id,
44        }
45    }
46
47    #[must_use]
48    pub fn account_id(&self) -> AccountId {
49        match self {
50            Self::PositionOpened(position) => position.account_id,
51            Self::PositionChanged(position) => position.account_id,
52            Self::PositionClosed(position) => position.account_id,
53            Self::PositionAdjusted(adjustment) => adjustment.account_id,
54        }
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use nautilus_core::{DurationNanos, UUID4, UnixNanos};
61    use rstest::*;
62    use rust_decimal_macros::dec;
63
64    use super::*;
65    use crate::{
66        enums::{OrderSide, PositionSide},
67        events::{PositionChanged, PositionClosed, PositionOpened},
68        identifiers::{AccountId, ClientOrderId, InstrumentId, PositionId, StrategyId, TraderId},
69        types::{Currency, Money, Price, Quantity},
70    };
71
72    fn create_test_position_opened() -> PositionOpened {
73        PositionOpened {
74            trader_id: TraderId::from("TRADER-001"),
75            strategy_id: StrategyId::from("EMA-CROSS"),
76            instrument_id: InstrumentId::from("EURUSD.SIM"),
77            position_id: PositionId::from("P-001"),
78            account_id: AccountId::from("SIM-001"),
79            opening_order_id: ClientOrderId::from("O-19700101-000000-001-001-1"),
80            entry: OrderSide::Buy,
81            side: PositionSide::Long,
82            signed_qty: dec!(100.0),
83            quantity: Quantity::from("100"),
84            last_qty: Quantity::from("100"),
85            last_px: Price::from("1.0500"),
86            currency: Currency::USD(),
87            avg_px_open: dec!(1.0500),
88            realized_pnl: Some(Money::new(-2.0, Currency::USD())),
89            event_id: UUID4::default(),
90            ts_event: UnixNanos::from(1_000_000_000),
91            ts_init: UnixNanos::from(2_000_000_000),
92        }
93    }
94
95    fn create_test_position_changed() -> PositionChanged {
96        PositionChanged {
97            trader_id: TraderId::from("TRADER-001"),
98            strategy_id: StrategyId::from("EMA-CROSS"),
99            instrument_id: InstrumentId::from("EURUSD.SIM"),
100            position_id: PositionId::from("P-001"),
101            account_id: AccountId::from("SIM-001"),
102            opening_order_id: ClientOrderId::from("O-19700101-000000-001-001-1"),
103            entry: OrderSide::Buy,
104            side: PositionSide::Long,
105            signed_qty: dec!(150.0),
106            quantity: Quantity::from("150"),
107            peak_quantity: Quantity::from("150"),
108            last_qty: Quantity::from("50"),
109            last_px: Price::from("1.0550"),
110            currency: Currency::USD(),
111            avg_px_open: dec!(1.0525),
112            avg_px_close: None,
113            realized_return: 0.0,
114            realized_pnl: None,
115            unrealized_pnl: Money::new(75.0, Currency::USD()),
116            event_id: UUID4::default(),
117            ts_opened: UnixNanos::from(1_000_000_000),
118            ts_event: UnixNanos::from(1_500_000_000),
119            ts_init: UnixNanos::from(2_500_000_000),
120        }
121    }
122
123    fn create_test_position_closed() -> PositionClosed {
124        PositionClosed {
125            trader_id: TraderId::from("TRADER-001"),
126            strategy_id: StrategyId::from("EMA-CROSS"),
127            instrument_id: InstrumentId::from("EURUSD.SIM"),
128            position_id: PositionId::from("P-001"),
129            account_id: AccountId::from("SIM-001"),
130            opening_order_id: ClientOrderId::from("O-19700101-000000-001-001-1"),
131            closing_order_id: Some(ClientOrderId::from("O-19700101-000000-001-001-2")),
132            entry: OrderSide::Buy,
133            side: PositionSide::Flat,
134            signed_qty: dec!(0.0),
135            quantity: Quantity::from("0"),
136            peak_quantity: Quantity::from("150"),
137            last_qty: Quantity::from("150"),
138            last_px: Price::from("1.0600"),
139            currency: Currency::USD(),
140            avg_px_open: dec!(1.0525),
141            avg_px_close: Some(dec!(1.0600)),
142            realized_return: 0.0071,
143            realized_pnl: Some(Money::new(112.50, Currency::USD())),
144            unrealized_pnl: Money::new(0.0, Currency::USD()),
145            duration: DurationNanos::from_hours(1),
146            event_id: UUID4::default(),
147            ts_opened: UnixNanos::from(1_000_000_000),
148            ts_closed: Some(UnixNanos::from(4_600_000_000)),
149            ts_event: UnixNanos::from(4_600_000_000),
150            ts_init: UnixNanos::from(5_000_000_000),
151        }
152    }
153
154    #[rstest]
155    fn test_position_event_opened_instrument_id() {
156        let opened = create_test_position_opened();
157        let event = PositionEvent::PositionOpened(opened);
158
159        assert_eq!(event.instrument_id(), InstrumentId::from("EURUSD.SIM"));
160    }
161
162    #[rstest]
163    fn test_position_event_changed_instrument_id() {
164        let changed = create_test_position_changed();
165        let event = PositionEvent::PositionChanged(changed);
166
167        assert_eq!(event.instrument_id(), InstrumentId::from("EURUSD.SIM"));
168    }
169
170    #[rstest]
171    fn test_position_event_closed_instrument_id() {
172        let closed = create_test_position_closed();
173        let event = PositionEvent::PositionClosed(closed);
174
175        assert_eq!(event.instrument_id(), InstrumentId::from("EURUSD.SIM"));
176    }
177
178    #[rstest]
179    fn test_position_event_opened_account_id() {
180        let opened = create_test_position_opened();
181        let event = PositionEvent::PositionOpened(opened);
182
183        assert_eq!(event.account_id(), AccountId::from("SIM-001"));
184    }
185
186    #[rstest]
187    fn test_position_event_changed_account_id() {
188        let changed = create_test_position_changed();
189        let event = PositionEvent::PositionChanged(changed);
190
191        assert_eq!(event.account_id(), AccountId::from("SIM-001"));
192    }
193
194    #[rstest]
195    fn test_position_event_closed_account_id() {
196        let closed = create_test_position_closed();
197        let event = PositionEvent::PositionClosed(closed);
198
199        assert_eq!(event.account_id(), AccountId::from("SIM-001"));
200    }
201
202    #[rstest]
203    fn test_position_event_enum_variants() {
204        let opened = create_test_position_opened();
205        let changed = create_test_position_changed();
206        let closed = create_test_position_closed();
207
208        let event_opened = PositionEvent::PositionOpened(opened);
209        let event_changed = PositionEvent::PositionChanged(changed);
210        let event_closed = PositionEvent::PositionClosed(closed);
211
212        match event_opened {
213            PositionEvent::PositionOpened(_) => {}
214            _ => panic!("Expected PositionOpened variant"),
215        }
216
217        match event_changed {
218            PositionEvent::PositionChanged(_) => {}
219            _ => panic!("Expected PositionChanged variant"),
220        }
221
222        match event_closed {
223            PositionEvent::PositionClosed(_) => {}
224            _ => panic!("Expected PositionClosed variant"),
225        }
226    }
227}