Skip to main content

nautilus_model/events/position/
snapshot.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 nautilus_core::{DurationNanos, UnixNanos};
17use rust_decimal::Decimal;
18use serde::{Deserialize, Serialize};
19
20use crate::{
21    enums::{OrderSide, PositionSide},
22    identifiers::{AccountId, ClientOrderId, InstrumentId, PositionId, StrategyId, TraderId},
23    position::Position,
24    types::{Currency, Money, Quantity},
25};
26
27/// Represents a position state snapshot as a certain instant.
28#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
29#[cfg_attr(
30    feature = "python",
31    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
32)]
33#[cfg_attr(
34    feature = "python",
35    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
36)]
37pub struct PositionSnapshot {
38    /// The trader ID associated with the snapshot.
39    pub trader_id: TraderId,
40    /// The strategy ID associated with the snapshot.
41    pub strategy_id: StrategyId,
42    /// The instrument ID associated with the snapshot.
43    pub instrument_id: InstrumentId,
44    /// The position ID associated with the snapshot.
45    pub position_id: PositionId,
46    /// The account ID associated with the position.
47    pub account_id: AccountId,
48    /// The client order ID for the order which opened the position.
49    pub opening_order_id: ClientOrderId,
50    /// The client order ID for the order which closed the position.
51    pub closing_order_id: Option<ClientOrderId>,
52    /// The entry direction from open.
53    pub entry: OrderSide,
54    /// The position side.
55    pub side: PositionSide,
56    /// The position signed quantity (positive for LONG, negative for SHOT).
57    pub signed_qty: Decimal,
58    /// The position open quantity.
59    pub quantity: Quantity,
60    /// The peak directional quantity reached by the position.
61    pub peak_qty: Quantity,
62    /// The position quote currency.
63    pub quote_currency: Currency,
64    /// The position base currency.
65    pub base_currency: Option<Currency>,
66    /// The position settlement currency.
67    pub settlement_currency: Currency,
68    /// The average open price.
69    pub avg_px_open: Decimal,
70    /// The average closing price.
71    pub avg_px_close: Option<Decimal>,
72    /// The realized return for the position.
73    pub realized_return: Option<f64>,
74    /// The realized PnL for the position (including commissions).
75    pub realized_pnl: Option<Money>,
76    /// The unrealized PnL for the position (including commissions).
77    pub unrealized_pnl: Option<Money>,
78    /// The commissions for the position.
79    pub commissions: Vec<Money>,
80    /// The open duration for the position (nanoseconds).
81    pub duration_ns: Option<DurationNanos>,
82    /// UNIX timestamp (nanoseconds) when the position opened.
83    pub ts_opened: UnixNanos,
84    /// UNIX timestamp (nanoseconds) when the position closed.
85    pub ts_closed: Option<UnixNanos>,
86    /// UNIX timestamp (nanoseconds) when the snapshot was initialized.
87    pub ts_init: UnixNanos,
88    /// UNIX timestamp (nanoseconds) when the last position event occurred.
89    pub ts_last: UnixNanos,
90    /// Full replay state when the snapshot is used as a durable correction boundary.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub replay_state: Option<serde_json::Value>,
93}
94
95impl PositionSnapshot {
96    #[must_use]
97    pub fn from(position: &Position, unrealized_pnl: Option<Money>) -> Self {
98        Self {
99            trader_id: position.trader_id,
100            strategy_id: position.strategy_id,
101            instrument_id: position.instrument_id,
102            position_id: position.id,
103            account_id: position.account_id,
104            opening_order_id: position.opening_order_id,
105            closing_order_id: position.closing_order_id,
106            entry: position.entry,
107            side: position.side,
108            signed_qty: position.signed_qty,
109            quantity: position.quantity,
110            peak_qty: position.peak_qty,
111            quote_currency: position.quote_currency,
112            base_currency: position.base_currency,
113            settlement_currency: position.settlement_currency,
114            avg_px_open: position.avg_px_open,
115            avg_px_close: position.avg_px_close,
116            realized_return: Some(position.realized_return), // TODO: Standardize
117            realized_pnl: position.realized_pnl,
118            unrealized_pnl,
119            commissions: position.commissions.values().copied().collect(), // TODO: Optimize
120            duration_ns: Some(position.duration_ns),                       // TODO: Standardize
121            ts_opened: position.ts_opened,
122            ts_closed: position.ts_closed,
123            ts_init: position.ts_init,
124            ts_last: position.ts_last,
125            replay_state: None,
126        }
127    }
128
129    /// Creates a snapshot containing the full state needed to replay a corrected position.
130    #[must_use]
131    pub fn from_replay_state(position: &Position, unrealized_pnl: Option<Money>) -> Self {
132        let mut snapshot = Self::from(position, unrealized_pnl);
133        snapshot.replay_state = serde_json::to_value(position).ok();
134        snapshot
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use nautilus_core::UnixNanos;
141    use rstest::*;
142    use rust_decimal_macros::dec;
143
144    use super::*;
145    use crate::{
146        enums::{OrderSide, PositionSide},
147        events::{OrderFilled, order::spec::OrderFilledSpec},
148        identifiers::{
149            AccountId, ClientOrderId, InstrumentId, PositionId, StrategyId, TradeId, TraderId,
150            VenueOrderId,
151        },
152        instruments::{InstrumentAny, stubs::audusd_sim},
153        position::Position,
154        types::{Currency, Money, Price, Quantity},
155    };
156
157    fn create_test_position_snapshot() -> PositionSnapshot {
158        PositionSnapshot {
159            trader_id: TraderId::from("TRADER-001"),
160            strategy_id: StrategyId::from("EMA-CROSS"),
161            instrument_id: InstrumentId::from("EURUSD.SIM"),
162            position_id: PositionId::from("P-001"),
163            account_id: AccountId::from("SIM-001"),
164            opening_order_id: ClientOrderId::from("O-19700101-000000-001-001-1"),
165            closing_order_id: Some(ClientOrderId::from("O-19700101-000000-001-001-2")),
166            entry: OrderSide::Buy,
167            side: PositionSide::Long,
168            signed_qty: dec!(100.0),
169            quantity: Quantity::from("100"),
170            peak_qty: Quantity::from("100"),
171            quote_currency: Currency::USD(),
172            base_currency: Some(Currency::EUR()),
173            settlement_currency: Currency::USD(),
174            avg_px_open: dec!(1.0500),
175            avg_px_close: Some(dec!(1.0600)),
176            realized_return: Some(0.0095),
177            realized_pnl: Some(Money::new(100.0, Currency::USD())),
178            unrealized_pnl: Some(Money::new(50.0, Currency::USD())),
179            commissions: vec![Money::new(2.0, Currency::USD())],
180            duration_ns: Some(DurationNanos::from_hours(1)),
181            ts_opened: UnixNanos::from(1_000_000_000),
182            ts_closed: Some(UnixNanos::from(4_600_000_000)),
183            ts_init: UnixNanos::from(2_000_000_000),
184            ts_last: UnixNanos::from(4_600_000_000),
185            replay_state: None,
186        }
187    }
188
189    fn create_test_order_filled() -> OrderFilled {
190        OrderFilledSpec::builder()
191            .strategy_id(StrategyId::from("EMA-CROSS"))
192            .instrument_id(InstrumentId::from("AUD/USD.SIM"))
193            .client_order_id(ClientOrderId::from("O-19700101-000000-001-001-1"))
194            .venue_order_id(VenueOrderId::from("1"))
195            .trade_id(TradeId::from("T-001"))
196            .last_qty(Quantity::from("100"))
197            .last_px(Price::from("0.8000"))
198            .ts_event(UnixNanos::from(1_000_000_000))
199            .ts_init(UnixNanos::from(2_000_000_000))
200            .position_id(PositionId::from("P-001"))
201            .commission(Money::new(2.0, Currency::USD()))
202            .build()
203    }
204
205    #[rstest]
206    fn test_position_snapshot_from() {
207        let instrument = audusd_sim();
208        let fill = create_test_order_filled();
209        let position = Position::new(&InstrumentAny::CurrencyPair(instrument), fill);
210        let unrealized_pnl = Some(Money::new(75.0, Currency::USD()));
211
212        let snapshot = PositionSnapshot::from(&position, unrealized_pnl);
213
214        assert_eq!(snapshot.trader_id, position.trader_id);
215        assert_eq!(snapshot.strategy_id, position.strategy_id);
216        assert_eq!(snapshot.instrument_id, position.instrument_id);
217        assert_eq!(snapshot.position_id, position.id);
218        assert_eq!(snapshot.account_id, position.account_id);
219        assert_eq!(snapshot.opening_order_id, position.opening_order_id);
220        assert_eq!(snapshot.closing_order_id, position.closing_order_id);
221        assert_eq!(snapshot.entry, position.entry);
222        assert_eq!(snapshot.side, position.side);
223        assert_eq!(snapshot.signed_qty, position.signed_qty);
224        assert_eq!(snapshot.quantity, position.quantity);
225        assert_eq!(snapshot.peak_qty, position.peak_qty);
226        assert_eq!(snapshot.quote_currency, position.quote_currency);
227        assert_eq!(snapshot.base_currency, position.base_currency);
228        assert_eq!(snapshot.settlement_currency, position.settlement_currency);
229        assert_eq!(snapshot.avg_px_open, position.avg_px_open);
230        assert_eq!(snapshot.avg_px_close, position.avg_px_close);
231        assert_eq!(snapshot.realized_return, Some(position.realized_return));
232        assert_eq!(snapshot.realized_pnl, position.realized_pnl);
233        assert_eq!(snapshot.unrealized_pnl, unrealized_pnl);
234        assert_eq!(snapshot.duration_ns, Some(position.duration_ns));
235        assert_eq!(snapshot.ts_opened, position.ts_opened);
236        assert_eq!(snapshot.ts_closed, position.ts_closed);
237        assert_eq!(snapshot.ts_init, position.ts_init);
238        assert_eq!(snapshot.ts_last, position.ts_last);
239        assert_eq!(snapshot.replay_state, None);
240    }
241
242    #[rstest]
243    fn test_position_snapshot_from_with_no_unrealized_pnl() {
244        let instrument = audusd_sim();
245        let fill = create_test_order_filled();
246        let position = Position::new(&InstrumentAny::CurrencyPair(instrument), fill);
247
248        let snapshot = PositionSnapshot::from(&position, None);
249
250        assert_eq!(snapshot.unrealized_pnl, None);
251    }
252
253    #[rstest]
254    fn test_position_snapshot_from_replay_state() {
255        let instrument = audusd_sim();
256        let fill = create_test_order_filled();
257        let position = Position::new(&InstrumentAny::CurrencyPair(instrument), fill);
258
259        let snapshot = PositionSnapshot::from_replay_state(&position, None);
260        let restored: Position = serde_json::from_value(snapshot.replay_state.unwrap()).unwrap();
261
262        assert_eq!(restored, position);
263    }
264
265    #[rstest]
266    fn test_position_snapshot_serialization() {
267        let original = create_test_position_snapshot();
268
269        // Test JSON serialization
270        let json = serde_json::to_string(&original).unwrap();
271        let deserialized: PositionSnapshot = serde_json::from_str(&json).unwrap();
272
273        assert_eq!(original, deserialized);
274    }
275}