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