1use 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#[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 pub trader_id: TraderId,
39 pub strategy_id: StrategyId,
41 pub instrument_id: InstrumentId,
43 pub position_id: PositionId,
45 pub account_id: AccountId,
47 pub opening_order_id: ClientOrderId,
49 pub closing_order_id: Option<ClientOrderId>,
51 pub entry: OrderSide,
53 pub side: PositionSide,
55 pub signed_qty: f64,
57 pub quantity: Quantity,
59 pub peak_qty: Quantity,
61 pub quote_currency: Currency,
63 pub base_currency: Option<Currency>,
65 pub settlement_currency: Currency,
67 pub avg_px_open: f64,
69 pub avg_px_close: Option<f64>,
71 pub realized_return: Option<f64>,
73 pub realized_pnl: Option<Money>,
75 pub unrealized_pnl: Option<Money>,
77 pub commissions: Vec<Money>,
79 pub duration_ns: Option<u64>,
81 pub ts_opened: UnixNanos,
83 pub ts_closed: Option<UnixNanos>,
85 pub ts_init: UnixNanos,
87 pub ts_last: UnixNanos,
89 #[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), realized_pnl: position.realized_pnl,
117 unrealized_pnl,
118 commissions: position.commissions.values().copied().collect(), duration_ns: Some(position.duration_ns), 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 #[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), 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 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}