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