Skip to main content

nautilus_model/events/position/
closed.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::{
17    UUID4,
18    nanos::{DurationNanos, UnixNanos},
19};
20use serde::{Deserialize, Serialize};
21
22use crate::{
23    data::InstrumentClose,
24    enums::{OrderSide, PositionSide},
25    events::OrderFilled,
26    identifiers::{AccountId, ClientOrderId, InstrumentId, PositionId, StrategyId, TraderId},
27    position::Position,
28    types::{Currency, Money, Price, Quantity},
29};
30
31/// Represents an event where a position has been closed.
32#[repr(C)]
33#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
34#[cfg_attr(
35    feature = "python",
36    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
37)]
38#[cfg_attr(
39    feature = "python",
40    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
41)]
42pub struct PositionClosed {
43    /// The trader ID associated with the event.
44    pub trader_id: TraderId,
45    /// The strategy ID associated with the event.
46    pub strategy_id: StrategyId,
47    /// The instrument ID associated with the event.
48    pub instrument_id: InstrumentId,
49    /// The position ID associated with the event.
50    pub position_id: PositionId,
51    /// The account ID associated with the position.
52    pub account_id: AccountId,
53    /// The client order ID for the order which opened the position.
54    pub opening_order_id: ClientOrderId,
55    /// The client order ID for the order which closed the position.
56    pub closing_order_id: Option<ClientOrderId>,
57    /// The position entry order side.
58    pub entry: OrderSide,
59    /// The position side.
60    pub side: PositionSide,
61    /// The current signed quantity (positive for position side `LONG`, negative for `SHORT`).
62    pub signed_qty: f64,
63    /// The current open quantity.
64    pub quantity: Quantity,
65    /// The peak directional quantity reached by the position.
66    pub peak_quantity: Quantity,
67    /// The last fill quantity for the position.
68    pub last_qty: Quantity,
69    /// The last fill price for the position.
70    pub last_px: Price,
71    /// The position quote currency.
72    pub currency: Currency,
73    /// The average open price.
74    pub avg_px_open: f64,
75    /// The average closing price.
76    pub avg_px_close: Option<f64>,
77    /// The realized return for the position.
78    pub realized_return: f64,
79    /// The realized PnL for the position (including commissions).
80    pub realized_pnl: Option<Money>,
81    /// The unrealized PnL for the position (including commissions).
82    pub unrealized_pnl: Money,
83    /// The total open duration (nanoseconds).
84    pub duration: DurationNanos,
85    /// The unique identifier for the event.
86    pub event_id: UUID4,
87    /// UNIX timestamp (nanoseconds) when the position was opened.
88    pub ts_opened: UnixNanos,
89    /// UNIX timestamp (nanoseconds) when the position was closed.
90    pub ts_closed: Option<UnixNanos>,
91    /// UNIX timestamp (nanoseconds) when the event occurred.
92    pub ts_event: UnixNanos,
93    /// UNIX timestamp (nanoseconds) when the event was initialized.
94    pub ts_init: UnixNanos,
95}
96
97impl PositionClosed {
98    #[must_use]
99    pub fn create(
100        position: &Position,
101        fill: &OrderFilled,
102        event_id: UUID4,
103        ts_init: UnixNanos,
104    ) -> Self {
105        Self {
106            trader_id: position.trader_id,
107            strategy_id: position.strategy_id,
108            instrument_id: position.instrument_id,
109            position_id: position.id,
110            account_id: position.account_id,
111            opening_order_id: position.opening_order_id,
112            closing_order_id: position.closing_order_id,
113            entry: position.entry,
114            side: position.side,
115            signed_qty: position.signed_qty,
116            quantity: position.quantity,
117            peak_quantity: position.peak_qty,
118            last_qty: fill.last_qty,
119            last_px: fill.last_px,
120            currency: position.quote_currency,
121            avg_px_open: position.avg_px_open,
122            avg_px_close: position.avg_px_close,
123            realized_return: position.realized_return,
124            realized_pnl: position.realized_pnl,
125            unrealized_pnl: Money::zero(position.quote_currency),
126            duration: position.duration_ns,
127            event_id,
128            ts_opened: position.ts_opened,
129            ts_closed: position.ts_closed,
130            ts_event: fill.ts_event,
131            ts_init,
132        }
133    }
134
135    #[must_use]
136    pub fn create_from_instrument_close(
137        position: &Position,
138        close: &InstrumentClose,
139        last_qty: Quantity,
140        event_id: UUID4,
141        ts_init: UnixNanos,
142    ) -> Self {
143        Self {
144            trader_id: position.trader_id,
145            strategy_id: position.strategy_id,
146            instrument_id: position.instrument_id,
147            position_id: position.id,
148            account_id: position.account_id,
149            opening_order_id: position.opening_order_id,
150            closing_order_id: None,
151            entry: position.entry,
152            side: position.side,
153            signed_qty: position.signed_qty,
154            quantity: position.quantity,
155            peak_quantity: position.peak_qty,
156            last_qty,
157            last_px: close.close_price,
158            currency: position.quote_currency,
159            avg_px_open: position.avg_px_open,
160            avg_px_close: position.avg_px_close,
161            realized_return: position.realized_return,
162            realized_pnl: position.realized_pnl,
163            unrealized_pnl: Money::zero(position.quote_currency),
164            duration: position.duration_ns,
165            event_id,
166            ts_opened: position.ts_opened,
167            ts_closed: position.ts_closed,
168            ts_event: close.ts_event,
169            ts_init,
170        }
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use nautilus_core::UnixNanos;
177    use rstest::*;
178
179    use super::*;
180    use crate::{
181        enums::{OrderSide, PositionSide},
182        events::{OrderFilled, order::spec::OrderFilledSpec},
183        identifiers::{
184            AccountId, ClientOrderId, InstrumentId, PositionId, StrategyId, TradeId, TraderId,
185            VenueOrderId,
186        },
187        instruments::{InstrumentAny, stubs::audusd_sim},
188        position::Position,
189        types::{Currency, Money, Price, Quantity},
190    };
191
192    fn create_test_position_closed() -> PositionClosed {
193        PositionClosed {
194            trader_id: TraderId::from("TRADER-001"),
195            strategy_id: StrategyId::from("EMA-CROSS"),
196            instrument_id: InstrumentId::from("EURUSD.SIM"),
197            position_id: PositionId::from("P-001"),
198            account_id: AccountId::from("SIM-001"),
199            opening_order_id: ClientOrderId::from("O-19700101-000000-001-001-1"),
200            closing_order_id: Some(ClientOrderId::from("O-19700101-000000-001-001-2")),
201            entry: OrderSide::Buy,
202            side: PositionSide::Flat,
203            signed_qty: 0.0,
204            quantity: Quantity::from("0"),
205            peak_quantity: Quantity::from("150"),
206            last_qty: Quantity::from("150"),
207            last_px: Price::from("1.0600"),
208            currency: Currency::USD(),
209            avg_px_open: 1.0525,
210            avg_px_close: Some(1.0600),
211            realized_return: 0.0071,
212            realized_pnl: Some(Money::new(112.50, Currency::USD())),
213            unrealized_pnl: Money::new(0.0, Currency::USD()),
214            duration: DurationNanos::from_hours(1),
215            event_id: UUID4::default(),
216            ts_opened: UnixNanos::from(1_000_000_000),
217            ts_closed: Some(UnixNanos::from(4_600_000_000)),
218            ts_event: UnixNanos::from(4_600_000_000),
219            ts_init: UnixNanos::from(5_000_000_000),
220        }
221    }
222
223    fn create_test_order_filled() -> OrderFilled {
224        OrderFilledSpec::builder()
225            .strategy_id(StrategyId::from("EMA-CROSS"))
226            .instrument_id(InstrumentId::from("EURUSD.SIM"))
227            .client_order_id(ClientOrderId::from("O-19700101-000000-001-001-2"))
228            .venue_order_id(VenueOrderId::from("2"))
229            .trade_id(TradeId::from("T-002"))
230            .order_side(OrderSide::Sell)
231            .last_qty(Quantity::from("150"))
232            .last_px(Price::from("1.0600"))
233            .ts_event(UnixNanos::from(4_600_000_000))
234            .ts_init(UnixNanos::from(5_000_000_000))
235            .position_id(PositionId::from("P-001"))
236            .commission(Money::new(2.5, Currency::USD()))
237            .build()
238    }
239
240    #[rstest]
241    fn test_position_closed_create() {
242        let instrument = audusd_sim();
243        let initial_fill = OrderFilledSpec::builder()
244            .strategy_id(StrategyId::from("EMA-CROSS"))
245            .instrument_id(InstrumentId::from("AUD/USD.SIM"))
246            .client_order_id(ClientOrderId::from("O-19700101-000000-001-001-1"))
247            .venue_order_id(VenueOrderId::from("1"))
248            .trade_id(TradeId::from("T-001"))
249            .last_qty(Quantity::from("100"))
250            .last_px(Price::from("0.8000"))
251            .ts_event(UnixNanos::from(1_000_000_000))
252            .ts_init(UnixNanos::from(2_000_000_000))
253            .position_id(PositionId::from("P-001"))
254            .commission(Money::new(2.0, Currency::USD()))
255            .build();
256
257        let position = Position::new(&InstrumentAny::CurrencyPair(instrument), initial_fill);
258        let closing_fill = create_test_order_filled();
259        let event_id = UUID4::default();
260        let ts_init = UnixNanos::from(6_000_000_000);
261
262        let position_closed = PositionClosed::create(&position, &closing_fill, event_id, ts_init);
263
264        assert_eq!(position_closed.trader_id, position.trader_id);
265        assert_eq!(position_closed.strategy_id, position.strategy_id);
266        assert_eq!(position_closed.instrument_id, position.instrument_id);
267        assert_eq!(position_closed.position_id, position.id);
268        assert_eq!(position_closed.account_id, position.account_id);
269        assert_eq!(position_closed.opening_order_id, position.opening_order_id);
270        assert_eq!(position_closed.closing_order_id, position.closing_order_id);
271        assert_eq!(position_closed.entry, position.entry);
272        assert_eq!(position_closed.side, position.side);
273        assert_eq!(position_closed.signed_qty, position.signed_qty);
274        assert_eq!(position_closed.quantity, position.quantity);
275        assert_eq!(position_closed.peak_quantity, position.peak_qty);
276        assert_eq!(position_closed.last_qty, closing_fill.last_qty);
277        assert_eq!(position_closed.last_px, closing_fill.last_px);
278        assert_eq!(position_closed.currency, position.quote_currency);
279        assert_eq!(position_closed.avg_px_open, position.avg_px_open);
280        assert_eq!(position_closed.avg_px_close, position.avg_px_close);
281        assert_eq!(position_closed.realized_return, position.realized_return);
282        assert_eq!(position_closed.realized_pnl, position.realized_pnl);
283        assert_eq!(
284            position_closed.unrealized_pnl,
285            Money::new(0.0, position.quote_currency)
286        );
287        assert_eq!(position_closed.duration, position.duration_ns);
288        assert_eq!(position_closed.event_id, event_id);
289        assert_eq!(position_closed.ts_opened, position.ts_opened);
290        assert_eq!(position_closed.ts_closed, position.ts_closed);
291        assert_eq!(position_closed.ts_event, closing_fill.ts_event);
292        assert_eq!(position_closed.ts_init, ts_init);
293    }
294
295    #[rstest]
296    fn test_position_closed_flat_position() {
297        let position_closed = create_test_position_closed();
298
299        assert_eq!(position_closed.side, PositionSide::Flat);
300        assert_eq!(position_closed.signed_qty, 0.0);
301        assert_eq!(position_closed.quantity, Quantity::from("0"));
302        assert_eq!(
303            position_closed.unrealized_pnl,
304            Money::new(0.0, Currency::USD())
305        );
306    }
307
308    #[rstest]
309    fn test_position_closed_loss_scenario() {
310        let mut position_closed = create_test_position_closed();
311        position_closed.avg_px_close = Some(1.0400); // Sold below open price
312        position_closed.realized_return = -0.0119;
313        position_closed.realized_pnl = Some(Money::new(-187.50, Currency::USD()));
314
315        assert_eq!(position_closed.avg_px_close, Some(1.0400));
316        assert!(position_closed.realized_return < 0.0);
317        assert_eq!(
318            position_closed.realized_pnl,
319            Some(Money::new(-187.50, Currency::USD()))
320        );
321    }
322}