Skip to main content

nautilus_model/python/data/
trade.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 std::{
17    collections::{HashMap, hash_map::DefaultHasher},
18    hash::{Hash, Hasher},
19    str::FromStr,
20};
21
22use nautilus_core::{
23    UnixNanos,
24    python::{
25        IntoPyObjectNautilusExt,
26        serialization::{from_dict_pyo3, to_dict_pyo3},
27        to_pyvalue_err,
28    },
29    serialization::{
30        Serializable,
31        msgpack::{FromMsgPack, ToMsgPack},
32    },
33};
34use pyo3::{
35    IntoPyObjectExt,
36    prelude::*,
37    pyclass::CompareOp,
38    types::{PyDict, PyInt, PyString, PyTuple},
39};
40
41use super::data_to_pycapsule;
42use crate::{
43    data::{Data, TradeTick},
44    enums::{AggressorSide, FromU8},
45    identifiers::{InstrumentId, TradeId},
46    python::common::PY_MODULE_MODEL,
47    types::{
48        price::{Price, PriceRaw},
49        quantity::{Quantity, QuantityRaw},
50    },
51};
52
53impl TradeTick {
54    /// Creates a new [`TradeTick`] from a Python object.
55    ///
56    /// # Panics
57    ///
58    /// Panics if converting `aggressor_side_u8` to `AggressorSide` fails.
59    ///
60    /// # Errors
61    ///
62    /// Returns a `PyErr` if attribute extraction or type conversion fails.
63    pub fn from_pyobject(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
64        // Fast path: avoid property getters that trigger enum type deadlocks
65        if let Ok(tick) = obj.cast::<Self>() {
66            return Ok(*tick.borrow());
67        }
68
69        let instrument_id_obj: Bound<'_, PyAny> = obj.getattr("instrument_id")?.extract()?;
70        let instrument_id_str: String = instrument_id_obj.getattr("value")?.extract()?;
71        let instrument_id =
72            InstrumentId::from_str(instrument_id_str.as_str()).map_err(to_pyvalue_err)?;
73
74        let price_py: Bound<'_, PyAny> = obj.getattr("price")?.extract()?;
75        let price_raw: PriceRaw = price_py.getattr("raw")?.extract()?;
76        let price_prec: u8 = price_py.getattr("precision")?.extract()?;
77        let price = Price::from_raw(price_raw, price_prec);
78
79        let size_py: Bound<'_, PyAny> = obj.getattr("size")?.extract()?;
80        let size_raw: QuantityRaw = size_py.getattr("raw")?.extract()?;
81        let size_prec: u8 = size_py.getattr("precision")?.extract()?;
82        let size = Quantity::from_raw(size_raw, size_prec);
83
84        let aggressor_side_obj: Bound<'_, PyAny> = obj.getattr("aggressor_side")?.extract()?;
85        let aggressor_side_u8 = aggressor_side_obj.getattr("value")?.extract()?;
86        let aggressor_side = AggressorSide::from_u8(aggressor_side_u8).unwrap();
87
88        let trade_id_obj: Bound<'_, PyAny> = obj.getattr("trade_id")?.extract()?;
89        let trade_id_str: String = trade_id_obj.getattr("value")?.extract()?;
90        let trade_id = TradeId::from(trade_id_str.as_str());
91
92        let ts_event: u64 = obj.getattr("ts_event")?.extract()?;
93        let ts_init: u64 = obj.getattr("ts_init")?.extract()?;
94
95        Ok(Self::new(
96            instrument_id,
97            price,
98            size,
99            aggressor_side,
100            trade_id,
101            ts_event.into(),
102            ts_init.into(),
103        ))
104    }
105}
106
107#[pymethods]
108impl TradeTick {
109    #[new]
110    fn py_new(
111        instrument_id: InstrumentId,
112        price: Price,
113        size: Quantity,
114        aggressor_side: AggressorSide,
115        trade_id: TradeId,
116        ts_event: u64,
117        ts_init: u64,
118    ) -> PyResult<Self> {
119        Self::new_checked(
120            instrument_id,
121            price,
122            size,
123            aggressor_side,
124            trade_id,
125            ts_event.into(),
126            ts_init.into(),
127        )
128        .map_err(to_pyvalue_err)
129    }
130
131    fn __setstate__(&mut self, state: &Bound<'_, PyAny>) -> PyResult<()> {
132        let py_tuple: &Bound<'_, PyTuple> = state.cast::<PyTuple>()?;
133        let binding = py_tuple.get_item(0)?;
134        let instrument_id_str = binding.cast::<PyString>()?.extract::<&str>()?;
135        let price_raw = py_tuple
136            .get_item(1)?
137            .cast::<PyInt>()?
138            .extract::<PriceRaw>()?;
139        let price_prec = py_tuple.get_item(2)?.cast::<PyInt>()?.extract::<u8>()?;
140        let size_raw = py_tuple
141            .get_item(3)?
142            .cast::<PyInt>()?
143            .extract::<QuantityRaw>()?;
144        let size_prec = py_tuple.get_item(4)?.cast::<PyInt>()?.extract::<u8>()?;
145
146        let aggressor_side_u8 = py_tuple.get_item(5)?.cast::<PyInt>()?.extract::<u8>()?;
147        let binding = py_tuple.get_item(6)?;
148        let trade_id_str = binding.cast::<PyString>()?.extract::<&str>()?;
149        let ts_event = py_tuple.get_item(7)?.cast::<PyInt>()?.extract::<u64>()?;
150        let ts_init = py_tuple.get_item(8)?.cast::<PyInt>()?.extract::<u64>()?;
151
152        self.instrument_id = InstrumentId::from_str(instrument_id_str).map_err(to_pyvalue_err)?;
153        self.price = Price::from_raw(price_raw, price_prec);
154        self.size = Quantity::from_raw(size_raw, size_prec);
155        self.aggressor_side = AggressorSide::from_u8(aggressor_side_u8).unwrap();
156        self.trade_id = TradeId::from(trade_id_str);
157        self.ts_event = ts_event.into();
158        self.ts_init = ts_init.into();
159
160        Ok(())
161    }
162
163    fn __getstate__(&self, py: Python) -> PyResult<Py<PyAny>> {
164        (
165            self.instrument_id.to_string(),
166            self.price.raw,
167            self.price.precision,
168            self.size.raw,
169            self.size.precision,
170            self.aggressor_side as u8,
171            self.trade_id.to_string(),
172            self.ts_event.as_u64(),
173            self.ts_init.as_u64(),
174        )
175            .into_py_any(py)
176    }
177
178    fn __reduce__(&self, py: Python) -> PyResult<Py<PyAny>> {
179        let safe_constructor = py.get_type::<Self>().getattr("_safe_constructor")?;
180        let state = self.__getstate__(py)?;
181        (safe_constructor, PyTuple::empty(py), state).into_py_any(py)
182    }
183
184    #[staticmethod]
185    fn _safe_constructor() -> Self {
186        Self::new(
187            InstrumentId::from("NULL.NULL"),
188            Price::zero(0),
189            Quantity::from(1), // size cannot be zero
190            AggressorSide::NoAggressor,
191            TradeId::from("NULL"),
192            UnixNanos::default(),
193            UnixNanos::default(),
194        )
195    }
196
197    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
198        match op {
199            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
200            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
201            _ => py.NotImplemented(),
202        }
203    }
204
205    fn __hash__(&self) -> isize {
206        let mut h = DefaultHasher::new();
207        self.hash(&mut h);
208        h.finish() as isize
209    }
210
211    fn __repr__(&self) -> String {
212        format!("{}({})", stringify!(TradeTick), self)
213    }
214
215    fn __str__(&self) -> String {
216        self.to_string()
217    }
218
219    #[getter]
220    #[pyo3(name = "instrument_id")]
221    fn py_instrument_id(&self) -> InstrumentId {
222        self.instrument_id
223    }
224
225    #[getter]
226    #[pyo3(name = "price")]
227    fn py_price(&self) -> Price {
228        self.price
229    }
230
231    #[getter]
232    #[pyo3(name = "size")]
233    fn py_size(&self) -> Quantity {
234        self.size
235    }
236
237    #[getter]
238    #[pyo3(name = "aggressor_side")]
239    fn py_aggressor_side(&self) -> AggressorSide {
240        self.aggressor_side
241    }
242
243    #[getter]
244    #[pyo3(name = "trade_id")]
245    fn py_trade_id(&self) -> TradeId {
246        self.trade_id
247    }
248
249    #[getter]
250    #[pyo3(name = "ts_event")]
251    fn py_ts_event(&self) -> u64 {
252        self.ts_event.as_u64()
253    }
254
255    #[getter]
256    #[pyo3(name = "ts_init")]
257    fn py_ts_init(&self) -> u64 {
258        self.ts_init.as_u64()
259    }
260
261    #[staticmethod]
262    #[pyo3(name = "fully_qualified_name")]
263    fn py_fully_qualified_name() -> String {
264        format!("{}:{}", PY_MODULE_MODEL, stringify!(TradeTick))
265    }
266
267    #[staticmethod]
268    #[pyo3(name = "get_metadata")]
269    fn py_get_metadata(
270        instrument_id: &InstrumentId,
271        price_precision: u8,
272        size_precision: u8,
273    ) -> PyResult<HashMap<String, String>> {
274        Ok(Self::get_metadata(
275            instrument_id,
276            price_precision,
277            size_precision,
278        ))
279    }
280
281    #[staticmethod]
282    #[pyo3(name = "get_fields")]
283    fn py_get_fields(py: Python<'_>) -> PyResult<Bound<'_, PyDict>> {
284        let py_dict = PyDict::new(py);
285        for (k, v) in Self::get_fields() {
286            py_dict.set_item(k, v)?;
287        }
288
289        Ok(py_dict)
290    }
291
292    /// Returns a new object from the given dictionary representation.
293    #[staticmethod]
294    #[pyo3(name = "from_dict")]
295    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
296        from_dict_pyo3(py, values)
297    }
298
299    #[staticmethod]
300    #[pyo3(name = "from_json")]
301    fn py_from_json(data: Vec<u8>) -> PyResult<Self> {
302        Self::from_json_bytes(&data).map_err(to_pyvalue_err)
303    }
304
305    #[staticmethod]
306    #[pyo3(name = "from_msgpack")]
307    fn py_from_msgpack(data: Vec<u8>) -> PyResult<Self> {
308        Self::from_msgpack_bytes(&data).map_err(to_pyvalue_err)
309    }
310
311    /// Creates a `PyCapsule` containing a raw pointer to a `Data::Trade` object.
312    ///
313    /// This function takes the current object (assumed to be of a type that can be represented as
314    /// `Data::Trade`), and encapsulates a raw pointer to it within a `PyCapsule`.
315    ///
316    /// # Safety
317    ///
318    /// This function is safe as long as the following conditions are met:
319    /// - The `Data::Trade` object pointed to by the capsule must remain valid for the lifetime of the capsule.
320    /// - The consumer of the capsule must ensure proper handling to avoid dereferencing a dangling pointer.
321    ///
322    /// # Panics
323    ///
324    /// The function will panic if the `PyCapsule` creation fails, which can occur if the
325    /// `Data::Trade` object cannot be converted into a raw pointer.
326    #[pyo3(name = "as_pycapsule")]
327    fn py_as_pycapsule(&self, py: Python<'_>) -> Py<PyAny> {
328        data_to_pycapsule(py, Data::Trade(*self))
329    }
330
331    /// Return a dictionary representation of the object.
332    #[pyo3(name = "to_dict")]
333    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
334        to_dict_pyo3(py, self)
335    }
336
337    /// Return JSON encoded bytes representation of the object.
338    #[pyo3(name = "to_json_bytes")]
339    fn py_to_json_bytes(&self, py: Python<'_>) -> Py<PyAny> {
340        // SAFETY: Unwrap safe when serializing a valid object
341        self.to_json_bytes().unwrap().into_py_any_unwrap(py)
342    }
343
344    /// Return MsgPack encoded bytes representation of the object.
345    #[pyo3(name = "to_msgpack_bytes")]
346    fn py_to_msgpack_bytes(&self, py: Python<'_>) -> Py<PyAny> {
347        // SAFETY: Unwrap safe when serializing a valid object
348        self.to_msgpack_bytes().unwrap().into_py_any_unwrap(py)
349    }
350}
351
352#[cfg(test)]
353mod tests {
354    use nautilus_core::python::IntoPyObjectNautilusExt;
355    use pyo3::Python;
356    use rstest::rstest;
357
358    use crate::{
359        data::{TradeTick, stubs::stub_trade_ethusdt_buyer},
360        enums::AggressorSide,
361        identifiers::{InstrumentId, TradeId},
362        types::{Price, Quantity},
363    };
364
365    #[rstest]
366    fn test_trade_tick_py_new_with_zero_size() {
367        let instrument_id = InstrumentId::from("ETH-USDT-SWAP.OKX");
368        let price = Price::from("10000.00");
369        let zero_size = Quantity::from(0);
370        let aggressor_side = AggressorSide::Buyer;
371        let trade_id = TradeId::from("123456789");
372        let ts_event = 1;
373        let ts_init = 2;
374
375        let result = TradeTick::py_new(
376            instrument_id,
377            price,
378            zero_size,
379            aggressor_side,
380            trade_id,
381            ts_event,
382            ts_init,
383        );
384
385        assert!(result.is_err());
386    }
387
388    #[rstest]
389    fn test_to_dict(stub_trade_ethusdt_buyer: TradeTick) {
390        let trade = stub_trade_ethusdt_buyer;
391
392        Python::initialize();
393        Python::attach(|py| {
394            let dict_string = trade.py_to_dict(py).unwrap().to_string();
395            let expected_string = r"{'type': 'TradeTick', 'instrument_id': 'ETHUSDT-PERP.BINANCE', 'price': '10000.0000', 'size': '1.00000000', 'aggressor_side': 'BUYER', 'trade_id': '123456789', 'ts_event': 0, 'ts_init': 1}";
396            assert_eq!(dict_string, expected_string);
397        });
398    }
399
400    #[rstest]
401    fn test_from_dict(stub_trade_ethusdt_buyer: TradeTick) {
402        let trade = stub_trade_ethusdt_buyer;
403
404        Python::initialize();
405        Python::attach(|py| {
406            let dict = trade.py_to_dict(py).unwrap();
407            let parsed = TradeTick::py_from_dict(py, dict).unwrap();
408            assert_eq!(parsed, trade);
409        });
410    }
411
412    #[rstest]
413    fn test_from_pyobject(stub_trade_ethusdt_buyer: TradeTick) {
414        let trade = stub_trade_ethusdt_buyer;
415
416        Python::initialize();
417        Python::attach(|py| {
418            let tick_pyobject = trade.into_py_any_unwrap(py);
419            let parsed_tick = TradeTick::from_pyobject(tick_pyobject.bind(py)).unwrap();
420            assert_eq!(parsed_tick, trade);
421        });
422    }
423}