nautilus_model/python/events/position/
adjusted.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2025-2025 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    python::{IntoPyObjectNautilusExt, serialization::from_dict_pyo3},
19};
20use pyo3::{basic::CompareOp, prelude::*, types::PyDict};
21use rust_decimal::Decimal;
22
23use crate::{
24    enums::PositionAdjustmentType,
25    events::PositionAdjusted,
26    identifiers::{AccountId, InstrumentId, PositionId, StrategyId, TraderId},
27    types::Money,
28};
29
30#[pymethods]
31impl PositionAdjusted {
32    #[allow(clippy::too_many_arguments)]
33    #[new]
34    #[pyo3(signature = (trader_id, strategy_id, instrument_id, position_id, account_id, adjustment_type, quantity_change, pnl_change, reason, event_id, ts_event, ts_init))]
35    fn py_new(
36        trader_id: TraderId,
37        strategy_id: StrategyId,
38        instrument_id: InstrumentId,
39        position_id: PositionId,
40        account_id: AccountId,
41        adjustment_type: PositionAdjustmentType,
42        quantity_change: Option<Decimal>,
43        pnl_change: Option<Money>,
44        reason: Option<String>,
45        event_id: UUID4,
46        ts_event: u64,
47        ts_init: u64,
48    ) -> Self {
49        Self::new(
50            trader_id,
51            strategy_id,
52            instrument_id,
53            position_id,
54            account_id,
55            adjustment_type,
56            quantity_change,
57            pnl_change,
58            reason.map(|s| s.as_str().into()),
59            event_id,
60            ts_event.into(),
61            ts_init.into(),
62        )
63    }
64
65    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
66        match op {
67            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
68            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
69            _ => py.NotImplemented(),
70        }
71    }
72
73    fn __repr__(&self) -> String {
74        format!("{self:?}")
75    }
76
77    #[getter]
78    #[pyo3(name = "trader_id")]
79    fn py_trader_id(&self) -> TraderId {
80        self.trader_id
81    }
82
83    #[getter]
84    #[pyo3(name = "strategy_id")]
85    fn py_strategy_id(&self) -> StrategyId {
86        self.strategy_id
87    }
88
89    #[getter]
90    #[pyo3(name = "instrument_id")]
91    fn py_instrument_id(&self) -> InstrumentId {
92        self.instrument_id
93    }
94
95    #[getter]
96    #[pyo3(name = "position_id")]
97    fn py_position_id(&self) -> PositionId {
98        self.position_id
99    }
100
101    #[getter]
102    #[pyo3(name = "account_id")]
103    fn py_account_id(&self) -> AccountId {
104        self.account_id
105    }
106
107    #[getter]
108    #[pyo3(name = "adjustment_type")]
109    fn py_adjustment_type(&self) -> PositionAdjustmentType {
110        self.adjustment_type
111    }
112
113    #[getter]
114    #[pyo3(name = "quantity_change")]
115    fn py_quantity_change(&self) -> Option<Decimal> {
116        self.quantity_change
117    }
118
119    #[getter]
120    #[pyo3(name = "pnl_change")]
121    fn py_pnl_change(&self) -> Option<Money> {
122        self.pnl_change
123    }
124
125    #[getter]
126    #[pyo3(name = "reason")]
127    fn py_reason(&self) -> Option<String> {
128        self.reason.map(|r| r.to_string())
129    }
130
131    #[getter]
132    #[pyo3(name = "event_id")]
133    fn py_event_id(&self) -> UUID4 {
134        self.event_id
135    }
136
137    #[getter]
138    #[pyo3(name = "ts_event")]
139    fn py_ts_event(&self) -> u64 {
140        self.ts_event.as_u64()
141    }
142
143    #[getter]
144    #[pyo3(name = "ts_init")]
145    fn py_ts_init(&self) -> u64 {
146        self.ts_init.as_u64()
147    }
148
149    /// Constructs a [`PositionAdjusted`] from a Python dict.
150    ///
151    /// # Errors
152    ///
153    /// Returns a `PyErr` if deserialization from the Python dict fails.
154    #[staticmethod]
155    #[pyo3(name = "from_dict")]
156    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
157        from_dict_pyo3(py, values)
158    }
159
160    /// Converts this [`PositionAdjusted`] into a Python dict.
161    ///
162    /// # Errors
163    ///
164    /// Returns a `PyErr` if serialization into a Python dict fails.
165    #[pyo3(name = "to_dict")]
166    pub fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
167        let dict = PyDict::new(py);
168        dict.set_item("type", stringify!(PositionAdjusted))?;
169        dict.set_item("trader_id", self.trader_id.to_string())?;
170        dict.set_item("strategy_id", self.strategy_id.to_string())?;
171        dict.set_item("instrument_id", self.instrument_id.to_string())?;
172        dict.set_item("position_id", self.position_id.to_string())?;
173        dict.set_item("account_id", self.account_id.to_string())?;
174        dict.set_item("adjustment_type", self.adjustment_type.to_string())?;
175        match self.quantity_change {
176            Some(quantity_change) => {
177                dict.set_item("quantity_change", quantity_change.to_string())?;
178            }
179            None => dict.set_item("quantity_change", py.None())?,
180        }
181        match self.pnl_change {
182            Some(pnl_change) => dict.set_item("pnl_change", pnl_change.to_string())?,
183            None => dict.set_item("pnl_change", py.None())?,
184        }
185        match self.reason {
186            Some(reason) => dict.set_item("reason", reason.to_string())?,
187            None => dict.set_item("reason", py.None())?,
188        }
189        dict.set_item("event_id", self.event_id.to_string())?;
190        dict.set_item("ts_event", self.ts_event.as_u64())?;
191        dict.set_item("ts_init", self.ts_init.as_u64())?;
192        Ok(dict.into())
193    }
194}