nautilus_model/python/data/
deltas.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-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 std::{
17    collections::hash_map::DefaultHasher,
18    hash::{Hash, Hasher},
19    ops::Deref,
20};
21
22use nautilus_core::python::to_pyvalue_err;
23use pyo3::{prelude::*, pyclass::CompareOp, types::PyCapsule};
24
25use super::data_to_pycapsule;
26use crate::{
27    data::{Data, OrderBookDelta, OrderBookDeltas, OrderBookDeltas_API},
28    identifiers::InstrumentId,
29    python::common::PY_MODULE_MODEL,
30};
31
32#[pymethods]
33impl OrderBookDeltas {
34    #[new]
35    fn py_new(instrument_id: InstrumentId, deltas: Vec<OrderBookDelta>) -> PyResult<Self> {
36        Self::new_checked(instrument_id, deltas).map_err(to_pyvalue_err)
37    }
38
39    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
40        match op {
41            CompareOp::Eq => self.eq(other).into_py(py),
42            CompareOp::Ne => self.ne(other).into_py(py),
43            _ => py.NotImplemented(),
44        }
45    }
46
47    fn __hash__(&self) -> isize {
48        let mut h = DefaultHasher::new();
49        self.hash(&mut h);
50        h.finish() as isize
51    }
52
53    fn __repr__(&self) -> String {
54        format!("{self:?}")
55    }
56
57    fn __str__(&self) -> String {
58        self.to_string()
59    }
60
61    #[getter]
62    #[pyo3(name = "instrument_id")]
63    fn py_instrument_id(&self) -> InstrumentId {
64        self.instrument_id
65    }
66
67    #[getter]
68    #[pyo3(name = "deltas")]
69    fn py_deltas(&self) -> Vec<OrderBookDelta> {
70        // `OrderBookDelta` is `Copy`
71        self.deltas.clone()
72    }
73
74    #[getter]
75    #[pyo3(name = "flags")]
76    fn py_flags(&self) -> u8 {
77        self.flags
78    }
79
80    #[getter]
81    #[pyo3(name = "sequence")]
82    fn py_sequence(&self) -> u64 {
83        self.sequence
84    }
85
86    #[getter]
87    #[pyo3(name = "ts_event")]
88    fn py_ts_event(&self) -> u64 {
89        self.ts_event.as_u64()
90    }
91
92    #[getter]
93    #[pyo3(name = "ts_init")]
94    fn py_ts_init(&self) -> u64 {
95        self.ts_init.as_u64()
96    }
97
98    #[staticmethod]
99    #[pyo3(name = "fully_qualified_name")]
100    fn py_fully_qualified_name() -> String {
101        format!("{}:{}", PY_MODULE_MODEL, stringify!(OrderBookDeltas))
102    }
103
104    #[staticmethod]
105    #[pyo3(name = "from_pycapsule")]
106    pub fn py_from_pycapsule(capsule: Bound<'_, PyAny>) -> Self {
107        let capsule: &Bound<'_, PyCapsule> = capsule
108            .downcast::<PyCapsule>()
109            .expect("Error on downcast to `&PyCapsule`");
110        let data: &OrderBookDeltas_API =
111            unsafe { &*(capsule.pointer() as *const OrderBookDeltas_API) };
112        data.deref().clone()
113    }
114
115    /// Creates a `PyCapsule` containing a raw pointer to a [`Data::Deltas`] object.
116    ///
117    /// This function takes the current object (assumed to be of a type that can be represented as
118    /// `Data::Deltas`), and encapsulates a raw pointer to it within a `PyCapsule`.
119    ///
120    /// # Safety
121    ///
122    /// This function is safe as long as the following conditions are met:
123    /// - The `Data::Deltas` object pointed to by the capsule must remain valid for the lifetime of the capsule.
124    /// - The consumer of the capsule must ensure proper handling to avoid dereferencing a dangling pointer.
125    ///
126    /// # Panics
127    ///
128    /// The function will panic if the `PyCapsule` creation fails, which can occur if the
129    /// [`Data::Deltas`] object cannot be converted into a raw pointer.
130    #[pyo3(name = "as_pycapsule")]
131    fn py_as_pycapsule(&self, py: Python<'_>) -> PyObject {
132        let deltas = OrderBookDeltas_API::new(self.clone());
133        data_to_pycapsule(py, Data::Deltas(deltas))
134    }
135
136    // TODO: Implement `Serializable` and the other methods can be added
137}