nautilus_model/python/data/
delta.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.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    python::{
24        IntoPyObjectPoseiExt,
25        serialization::{from_dict_pyo3, to_dict_pyo3},
26        to_pyvalue_err,
27    },
28    serialization::Serializable,
29};
30use pyo3::{basic::CompareOp, prelude::*, types::PyDict};
31
32use super::data_to_pycapsule;
33use crate::{
34    data::{BookOrder, Data, NULL_ORDER, OrderBookDelta, order::OrderId},
35    enums::{BookAction, FromU8, OrderSide},
36    identifiers::InstrumentId,
37    python::common::PY_MODULE_MODEL,
38    types::{
39        price::{Price, PriceRaw},
40        quantity::{Quantity, QuantityRaw},
41    },
42};
43
44impl OrderBookDelta {
45    /// Creates a new [`OrderBookDelta`] from a Python object.
46    ///
47    /// # Panics
48    ///
49    /// Panics if converting `instrument_id` from string or `action` from u8 fails.
50    ///
51    /// # Errors
52    ///
53    /// Returns a `PyErr` if extracting any attribute or converting types fails.
54    pub fn from_pyobject(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
55        let instrument_id_obj: Bound<'_, PyAny> = obj.getattr("instrument_id")?.extract()?;
56        let instrument_id_str: String = instrument_id_obj.getattr("value")?.extract()?;
57        let instrument_id = InstrumentId::from_str(instrument_id_str.as_str())
58            .map_err(to_pyvalue_err)
59            .unwrap();
60
61        let action_obj: Bound<'_, PyAny> = obj.getattr("action")?.extract()?;
62        let action_u8 = action_obj.getattr("value")?.extract()?;
63        let action = BookAction::from_u8(action_u8).unwrap();
64
65        let flags: u8 = obj.getattr("flags")?.extract()?;
66        let sequence: u64 = obj.getattr("sequence")?.extract()?;
67        let ts_event: u64 = obj.getattr("ts_event")?.extract()?;
68        let ts_init: u64 = obj.getattr("ts_init")?.extract()?;
69
70        let order_pyobject = obj.getattr("order")?;
71        let order: BookOrder = if order_pyobject.is_none() {
72            NULL_ORDER
73        } else {
74            let side_obj: Bound<'_, PyAny> = order_pyobject.getattr("side")?.extract()?;
75            let side_u8 = side_obj.getattr("value")?.extract()?;
76            let side = OrderSide::from_u8(side_u8).unwrap();
77
78            let price_py: Bound<'_, PyAny> = order_pyobject.getattr("price")?;
79            let price_raw: PriceRaw = price_py.getattr("raw")?.extract()?;
80            let price_prec: u8 = price_py.getattr("precision")?.extract()?;
81            let price = Price::from_raw(price_raw, price_prec);
82
83            let size_py: Bound<'_, PyAny> = order_pyobject.getattr("size")?;
84            let size_raw: QuantityRaw = size_py.getattr("raw")?.extract()?;
85            let size_prec: u8 = size_py.getattr("precision")?.extract()?;
86            let size = Quantity::from_raw(size_raw, size_prec);
87
88            let order_id: OrderId = order_pyobject.getattr("order_id")?.extract()?;
89            BookOrder {
90                side,
91                price,
92                size,
93                order_id,
94            }
95        };
96
97        Ok(Self::new(
98            instrument_id,
99            action,
100            order,
101            flags,
102            sequence,
103            ts_event.into(),
104            ts_init.into(),
105        ))
106    }
107}
108
109#[pymethods]
110impl OrderBookDelta {
111    #[new]
112    fn py_new(
113        instrument_id: InstrumentId,
114        action: BookAction,
115        order: BookOrder,
116        flags: u8,
117        sequence: u64,
118        ts_event: u64,
119        ts_init: u64,
120    ) -> PyResult<Self> {
121        Self::new_checked(
122            instrument_id,
123            action,
124            order,
125            flags,
126            sequence,
127            ts_event.into(),
128            ts_init.into(),
129        )
130        .map_err(to_pyvalue_err)
131    }
132
133    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
134        match op {
135            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
136            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
137            _ => py.NotImplemented(),
138        }
139    }
140
141    fn __hash__(&self) -> isize {
142        let mut h = DefaultHasher::new();
143        self.hash(&mut h);
144        h.finish() as isize
145    }
146
147    fn __repr__(&self) -> String {
148        format!("{self:?}")
149    }
150
151    fn __str__(&self) -> String {
152        self.to_string()
153    }
154
155    #[getter]
156    #[pyo3(name = "instrument_id")]
157    fn py_instrument_id(&self) -> InstrumentId {
158        self.instrument_id
159    }
160
161    #[getter]
162    #[pyo3(name = "action")]
163    fn py_action(&self) -> BookAction {
164        self.action
165    }
166
167    #[getter]
168    #[pyo3(name = "order")]
169    fn py_order(&self) -> BookOrder {
170        self.order
171    }
172
173    #[getter]
174    #[pyo3(name = "flags")]
175    fn py_flags(&self) -> u8 {
176        self.flags
177    }
178
179    #[getter]
180    #[pyo3(name = "sequence")]
181    fn py_sequence(&self) -> u64 {
182        self.sequence
183    }
184
185    #[getter]
186    #[pyo3(name = "ts_event")]
187    fn py_ts_event(&self) -> u64 {
188        self.ts_event.as_u64()
189    }
190
191    #[getter]
192    #[pyo3(name = "ts_init")]
193    fn py_ts_init(&self) -> u64 {
194        self.ts_init.as_u64()
195    }
196
197    #[staticmethod]
198    #[pyo3(name = "fully_qualified_name")]
199    fn py_fully_qualified_name() -> String {
200        format!("{}:{}", PY_MODULE_MODEL, stringify!(OrderBookDelta))
201    }
202
203    #[staticmethod]
204    #[pyo3(name = "get_metadata")]
205    fn py_get_metadata(
206        instrument_id: &InstrumentId,
207        price_precision: u8,
208        size_precision: u8,
209    ) -> PyResult<HashMap<String, String>> {
210        Ok(Self::get_metadata(
211            instrument_id,
212            price_precision,
213            size_precision,
214        ))
215    }
216
217    #[staticmethod]
218    #[pyo3(name = "get_fields")]
219    fn py_get_fields(py: Python<'_>) -> PyResult<Bound<'_, PyDict>> {
220        let py_dict = PyDict::new(py);
221        for (k, v) in Self::get_fields() {
222            py_dict.set_item(k, v)?;
223        }
224
225        Ok(py_dict)
226    }
227
228    /// Returns a new object from the given dictionary representation.
229    #[staticmethod]
230    #[pyo3(name = "from_dict")]
231    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
232        from_dict_pyo3(py, values)
233    }
234
235    #[staticmethod]
236    #[pyo3(name = "from_json")]
237    fn py_from_json(data: Vec<u8>) -> PyResult<Self> {
238        Self::from_json_bytes(&data).map_err(to_pyvalue_err)
239    }
240
241    #[staticmethod]
242    #[pyo3(name = "from_msgpack")]
243    fn py_from_msgpack(data: Vec<u8>) -> PyResult<Self> {
244        Self::from_msgpack_bytes(&data).map_err(to_pyvalue_err)
245    }
246
247    /// Creates a `PyCapsule` containing a raw pointer to a `Data::Delta` object.
248    ///
249    /// This function takes the current object (assumed to be of a type that can be represented as
250    /// `Data::Delta`), and encapsulates a raw pointer to it within a `PyCapsule`.
251    ///
252    /// # Safety
253    ///
254    /// This function is safe as long as the following conditions are met:
255    /// - The `Data::Delta` object pointed to by the capsule must remain valid for the lifetime of the capsule.
256    /// - The consumer of the capsule must ensure proper handling to avoid dereferencing a dangling pointer.
257    ///
258    /// # Panics
259    ///
260    /// The function will panic if the `PyCapsule` creation fails, which can occur if the
261    /// `Data::Delta` object cannot be converted into a raw pointer.
262    #[pyo3(name = "as_pycapsule")]
263    fn py_as_pycapsule(&self, py: Python<'_>) -> PyObject {
264        data_to_pycapsule(py, Data::Delta(*self))
265    }
266
267    /// Return a dictionary representation of the object.
268    #[pyo3(name = "to_dict")]
269    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
270        to_dict_pyo3(py, self)
271    }
272
273    /// Return JSON encoded bytes representation of the object.
274    #[pyo3(name = "to_json_bytes")]
275    fn py_to_json_bytes(&self, py: Python<'_>) -> Py<PyAny> {
276        // SAFETY: Unwrap safe when serializing a valid object
277        self.to_json_bytes().unwrap().into_py_any_unwrap(py)
278    }
279
280    /// Return MsgPack encoded bytes representation of the object.
281    #[pyo3(name = "to_msgpack_bytes")]
282    fn py_to_msgpack_bytes(&self, py: Python<'_>) -> Py<PyAny> {
283        // SAFETY: Unwrap safe when serializing a valid object
284        self.to_msgpack_bytes().unwrap().into_py_any_unwrap(py)
285    }
286}
287
288////////////////////////////////////////////////////////////////////////////////
289// Tests
290////////////////////////////////////////////////////////////////////////////////
291#[cfg(test)]
292mod tests {
293    use rstest::rstest;
294
295    use super::*;
296    use crate::data::stubs::*;
297
298    #[rstest]
299    fn test_order_book_delta_py_new_with_zero_size_returns_error() {
300        pyo3::prepare_freethreaded_python();
301
302        Python::with_gil(|_py| {
303            let instrument_id = InstrumentId::from("AAPL.XNAS");
304            let action = BookAction::Add;
305            let zero_size = Quantity::from(0);
306            let price = Price::from("100.00");
307            let side = OrderSide::Buy;
308            let order_id = 123_456;
309            let flags = 0;
310            let sequence = 1;
311            let ts_event = 1;
312            let ts_init = 2;
313
314            let order = BookOrder::new(side, price, zero_size, order_id);
315
316            let result = OrderBookDelta::py_new(
317                instrument_id,
318                action,
319                order,
320                flags,
321                sequence,
322                ts_event,
323                ts_init,
324            );
325            assert!(result.is_err());
326        });
327    }
328
329    #[rstest]
330    fn test_to_dict(stub_delta: OrderBookDelta) {
331        pyo3::prepare_freethreaded_python();
332        let delta = stub_delta;
333
334        Python::with_gil(|py| {
335            let dict_string = delta.py_to_dict(py).unwrap().to_string();
336            let expected_string = r"{'type': 'OrderBookDelta', 'instrument_id': 'AAPL.XNAS', 'action': 'ADD', 'order': {'side': 'BUY', 'price': '100.00', 'size': '10', 'order_id': 123456}, 'flags': 0, 'sequence': 1, 'ts_event': 1, 'ts_init': 2}";
337            assert_eq!(dict_string, expected_string);
338        });
339    }
340
341    #[rstest]
342    fn test_from_dict(stub_delta: OrderBookDelta) {
343        pyo3::prepare_freethreaded_python();
344        let delta = stub_delta;
345
346        Python::with_gil(|py| {
347            let dict = delta.py_to_dict(py).unwrap();
348            let parsed = OrderBookDelta::py_from_dict(py, dict).unwrap();
349            assert_eq!(parsed, delta);
350        });
351    }
352
353    #[rstest]
354    fn test_from_pyobject(stub_delta: OrderBookDelta) {
355        pyo3::prepare_freethreaded_python();
356        let delta = stub_delta;
357
358        Python::with_gil(|py| {
359            let delta_pyobject = delta.into_py_any_unwrap(py);
360            let parsed_delta = OrderBookDelta::from_pyobject(delta_pyobject.bind(py)).unwrap();
361            assert_eq!(parsed_delta, delta);
362        });
363    }
364}