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, correctness_error_to_pyvalue_err,
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 crate::{
42    data::TradeTick,
43    enums::{AggressorSide, FromU8},
44    identifiers::{InstrumentId, TradeId},
45    python::common::PY_MODULE_MODEL,
46    types::{
47        price::{Price, PriceRaw},
48        quantity::{Quantity, QuantityRaw},
49    },
50};
51
52#[pymethods]
53#[pyo3_stub_gen::derive::gen_stub_pymethods]
54impl TradeTick {
55    /// Represents a trade tick in a market.
56    #[new]
57    fn py_new(
58        instrument_id: InstrumentId,
59        price: Price,
60        size: Quantity,
61        aggressor_side: AggressorSide,
62        trade_id: TradeId,
63        ts_event: u64,
64        ts_init: u64,
65    ) -> PyResult<Self> {
66        Self::new_checked(
67            instrument_id,
68            price,
69            size,
70            aggressor_side,
71            trade_id,
72            ts_event.into(),
73            ts_init.into(),
74        )
75        .map_err(to_pyvalue_err)
76    }
77
78    fn __setstate__(&mut self, state: &Bound<'_, PyAny>) -> PyResult<()> {
79        let py_tuple: &Bound<'_, PyTuple> = state.cast::<PyTuple>()?;
80        let binding = py_tuple.get_item(0)?;
81        let instrument_id_str = binding.cast::<PyString>()?.extract::<&str>()?;
82        let price_raw = py_tuple
83            .get_item(1)?
84            .cast::<PyInt>()?
85            .extract::<PriceRaw>()?;
86        let price_prec = py_tuple.get_item(2)?.cast::<PyInt>()?.extract::<u8>()?;
87        let size_raw = py_tuple
88            .get_item(3)?
89            .cast::<PyInt>()?
90            .extract::<QuantityRaw>()?;
91        let size_prec = py_tuple.get_item(4)?.cast::<PyInt>()?.extract::<u8>()?;
92
93        let aggressor_side_u8 = py_tuple.get_item(5)?.cast::<PyInt>()?.extract::<u8>()?;
94        let binding = py_tuple.get_item(6)?;
95        let trade_id_str = binding.cast::<PyString>()?.extract::<&str>()?;
96        let ts_event = py_tuple.get_item(7)?.cast::<PyInt>()?.extract::<u64>()?;
97        let ts_init = py_tuple.get_item(8)?.cast::<PyInt>()?.extract::<u64>()?;
98
99        let instrument_id = InstrumentId::from_str(instrument_id_str).map_err(to_pyvalue_err)?;
100        let price = Price::from_raw_checked(price_raw, price_prec)
101            .map_err(correctness_error_to_pyvalue_err)?;
102        let size = Quantity::from_raw_checked(size_raw, size_prec)
103            .map_err(correctness_error_to_pyvalue_err)?;
104
105        let aggressor_side = AggressorSide::from_u8(aggressor_side_u8).ok_or_else(|| {
106            to_pyvalue_err(format!("Invalid aggressor_side value: {aggressor_side_u8}"))
107        })?;
108
109        let trade_id =
110            TradeId::new_checked(trade_id_str).map_err(correctness_error_to_pyvalue_err)?;
111
112        *self = Self {
113            instrument_id,
114            price,
115            size,
116            aggressor_side,
117            trade_id,
118            ts_event: ts_event.into(),
119            ts_init: ts_init.into(),
120        };
121
122        Ok(())
123    }
124
125    fn __getstate__(&self, py: Python) -> PyResult<Py<PyAny>> {
126        (
127            self.instrument_id.to_string(),
128            self.price.raw(),
129            self.price.precision,
130            self.size.raw(),
131            self.size.precision,
132            self.aggressor_side as u8,
133            self.trade_id.to_string(),
134            self.ts_event.as_u64(),
135            self.ts_init.as_u64(),
136        )
137            .into_py_any(py)
138    }
139
140    fn __reduce__(&self, py: Python) -> PyResult<Py<PyAny>> {
141        let safe_constructor = py.get_type::<Self>().getattr("_safe_constructor")?;
142        let state = self.__getstate__(py)?;
143        (safe_constructor, PyTuple::empty(py), state).into_py_any(py)
144    }
145
146    #[staticmethod]
147    #[pyo3(name = "_safe_constructor")]
148    fn py_safe_constructor() -> Self {
149        Self::new(
150            InstrumentId::from("NULL.NULL"),
151            Price::zero(0),
152            Quantity::from(1), // size cannot be zero
153            AggressorSide::NoAggressor,
154            TradeId::from("NULL"),
155            UnixNanos::default(),
156            UnixNanos::default(),
157        )
158    }
159
160    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
161        match op {
162            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
163            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
164            _ => py.NotImplemented(),
165        }
166    }
167
168    fn __hash__(&self) -> isize {
169        let mut h = DefaultHasher::new();
170        self.hash(&mut h);
171        h.finish() as isize
172    }
173
174    fn __repr__(&self) -> String {
175        format!("{}({})", stringify!(TradeTick), self)
176    }
177
178    fn __str__(&self) -> String {
179        self.to_string()
180    }
181
182    #[getter]
183    #[pyo3(name = "instrument_id")]
184    fn py_instrument_id(&self) -> InstrumentId {
185        self.instrument_id
186    }
187
188    #[getter]
189    #[pyo3(name = "price")]
190    fn py_price(&self) -> Price {
191        self.price
192    }
193
194    #[getter]
195    #[pyo3(name = "size")]
196    fn py_size(&self) -> Quantity {
197        self.size
198    }
199
200    #[getter]
201    #[pyo3(name = "aggressor_side")]
202    fn py_aggressor_side(&self) -> AggressorSide {
203        self.aggressor_side
204    }
205
206    #[getter]
207    #[pyo3(name = "trade_id")]
208    fn py_trade_id(&self) -> TradeId {
209        self.trade_id
210    }
211
212    #[getter]
213    #[pyo3(name = "ts_event")]
214    fn py_ts_event(&self) -> u64 {
215        self.ts_event.as_u64()
216    }
217
218    #[getter]
219    #[pyo3(name = "ts_init")]
220    fn py_ts_init(&self) -> u64 {
221        self.ts_init.as_u64()
222    }
223
224    #[staticmethod]
225    #[pyo3(name = "fully_qualified_name")]
226    fn py_fully_qualified_name() -> String {
227        format!("{}:{}", PY_MODULE_MODEL, stringify!(TradeTick))
228    }
229
230    /// Returns the metadata for the type, for use with serialization formats.
231    #[staticmethod]
232    #[pyo3(name = "get_metadata")]
233    fn py_get_metadata(
234        instrument_id: &InstrumentId,
235        price_precision: u8,
236        size_precision: u8,
237    ) -> HashMap<String, String> {
238        Self::get_metadata(instrument_id, price_precision, size_precision)
239    }
240
241    /// Returns the field map for the type, for use with Arrow schemas.
242    #[staticmethod]
243    #[pyo3(name = "get_fields")]
244    fn py_get_fields(py: Python<'_>) -> PyResult<Bound<'_, PyDict>> {
245        let py_dict = PyDict::new(py);
246        for (k, v) in Self::get_fields() {
247            py_dict.set_item(k, v)?;
248        }
249
250        Ok(py_dict)
251    }
252
253    #[staticmethod]
254    #[pyo3(name = "from_raw")]
255    #[expect(clippy::too_many_arguments)]
256    fn py_from_raw(
257        instrument_id: InstrumentId,
258        price_raw: PriceRaw,
259        price_prec: u8,
260        size_raw: QuantityRaw,
261        size_prec: u8,
262        aggressor_side: AggressorSide,
263        trade_id: TradeId,
264        ts_event: u64,
265        ts_init: u64,
266    ) -> PyResult<Self> {
267        let price = Price::from_raw_checked(price_raw, price_prec)
268            .map_err(correctness_error_to_pyvalue_err)?;
269        let size = Quantity::from_raw_checked(size_raw, size_prec)
270            .map_err(correctness_error_to_pyvalue_err)?;
271
272        Self::new_checked(
273            instrument_id,
274            price,
275            size,
276            aggressor_side,
277            trade_id,
278            ts_event.into(),
279            ts_init.into(),
280        )
281        .map_err(to_pyvalue_err)
282    }
283
284    /// Returns a new object from the given dictionary representation.
285    #[staticmethod]
286    #[pyo3(name = "from_dict")]
287    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
288        from_dict_pyo3(py, values)
289    }
290
291    /// Return a dictionary representation of the object.
292    #[pyo3(name = "to_dict")]
293    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
294        to_dict_pyo3(py, self)
295    }
296
297    /// Return JSON encoded bytes representation of the object.
298    #[pyo3(name = "to_json_bytes")]
299    fn py_to_json_bytes(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
300        self.to_json_bytes()
301            .map_err(to_pyvalue_err)?
302            .into_py_any(py)
303    }
304
305    /// Return `MsgPack` encoded bytes representation of the object.
306    #[pyo3(name = "to_msgpack_bytes")]
307    fn py_to_msgpack_bytes(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
308        self.to_msgpack_bytes()
309            .map_err(to_pyvalue_err)?
310            .into_py_any(py)
311    }
312}
313
314#[pymethods]
315impl TradeTick {
316    #[staticmethod]
317    #[pyo3(name = "from_json")]
318    fn py_from_json(data: &[u8]) -> PyResult<Self> {
319        Self::from_json_bytes(data).map_err(to_pyvalue_err)
320    }
321
322    #[staticmethod]
323    #[pyo3(name = "from_msgpack")]
324    fn py_from_msgpack(data: &[u8]) -> PyResult<Self> {
325        Self::from_msgpack_bytes(data).map_err(to_pyvalue_err)
326    }
327}
328
329#[cfg(test)]
330mod tests {
331    use pyo3::Python;
332    use rstest::rstest;
333
334    use crate::{
335        data::{TradeTick, stubs::stub_trade_ethusdt_buy},
336        enums::AggressorSide,
337        identifiers::{InstrumentId, TradeId},
338        types::{
339            Price, Quantity,
340            price::{PRICE_RAW_MAX, PRICE_RAW_MIN},
341        },
342    };
343
344    #[rstest]
345    fn test_trade_tick_py_new_with_zero_size() {
346        let instrument_id = InstrumentId::from("ETH-USDT-SWAP.OKX");
347        let price = Price::from("10000.00");
348        let zero_size = Quantity::from(0);
349        let aggressor_side = AggressorSide::Buy;
350        let trade_id = TradeId::from("123456789");
351        let ts_event = 1;
352        let ts_init = 2;
353
354        let result = TradeTick::py_new(
355            instrument_id,
356            price,
357            zero_size,
358            aggressor_side,
359            trade_id,
360            ts_event,
361            ts_init,
362        );
363
364        assert!(result.is_err());
365    }
366
367    #[rstest]
368    fn test_py_from_raw_rejects_out_of_range_price(stub_trade_ethusdt_buy: TradeTick) {
369        let trade = stub_trade_ethusdt_buy;
370        let raw = PRICE_RAW_MAX.saturating_add(1);
371
372        Python::initialize();
373        Python::attach(|_| {
374            let error = TradeTick::py_from_raw(
375                trade.instrument_id,
376                raw,
377                trade.price.precision,
378                trade.size.raw,
379                trade.size.precision,
380                trade.aggressor_side,
381                trade.trade_id,
382                trade.ts_event.as_u64(),
383                trade.ts_init.as_u64(),
384            )
385            .unwrap_err();
386
387            assert_eq!(
388                error.to_string(),
389                format!(
390                    "ValueError: raw value {raw} outside valid range [{PRICE_RAW_MIN}, {PRICE_RAW_MAX}]"
391                )
392            );
393        });
394    }
395
396    #[rstest]
397    fn test_to_dict(stub_trade_ethusdt_buy: TradeTick) {
398        let trade = stub_trade_ethusdt_buy;
399
400        Python::initialize();
401        Python::attach(|py| {
402            let dict_string = trade.py_to_dict(py).unwrap().to_string();
403            let expected_string = "{'type': 'TradeTick', 'instrument_id': 'ETHUSDT-PERP.BINANCE', 'price': '10000.0000', 'size': '1.00000000', 'aggressor_side': 'BUY', 'trade_id': '123456789', 'ts_event': 0, 'ts_init': 1}";
404            assert_eq!(dict_string, expected_string);
405        });
406    }
407
408    #[rstest]
409    fn test_from_dict(stub_trade_ethusdt_buy: TradeTick) {
410        let trade = stub_trade_ethusdt_buy;
411
412        Python::initialize();
413        Python::attach(|py| {
414            let dict = trade.py_to_dict(py).unwrap();
415            let parsed = TradeTick::py_from_dict(py, dict).unwrap();
416            assert_eq!(parsed, trade);
417        });
418    }
419}