nautilus_model/python/data/
depth.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, HashMap},
18    hash::{Hash, Hasher},
19};
20
21use nautilus_core::{
22    python::{
23        serialization::{from_dict_pyo3, to_dict_pyo3},
24        to_pyvalue_err,
25    },
26    serialization::Serializable,
27};
28use pyo3::{prelude::*, pyclass::CompareOp, types::PyDict};
29
30use super::data_to_pycapsule;
31use crate::{
32    data::{
33        depth::{OrderBookDepth10, DEPTH10_LEN},
34        order::BookOrder,
35        Data,
36    },
37    enums::OrderSide,
38    identifiers::InstrumentId,
39    python::common::PY_MODULE_MODEL,
40    types::{Price, Quantity},
41};
42
43#[pymethods]
44impl OrderBookDepth10 {
45    #[allow(clippy::too_many_arguments)]
46    #[new]
47    fn py_new(
48        instrument_id: InstrumentId,
49        bids: [BookOrder; DEPTH10_LEN],
50        asks: [BookOrder; DEPTH10_LEN],
51        bid_counts: [u32; DEPTH10_LEN],
52        ask_counts: [u32; DEPTH10_LEN],
53        flags: u8,
54        sequence: u64,
55        ts_event: u64,
56        ts_init: u64,
57    ) -> Self {
58        Self::new(
59            instrument_id,
60            bids,
61            asks,
62            bid_counts,
63            ask_counts,
64            flags,
65            sequence,
66            ts_event.into(),
67            ts_init.into(),
68        )
69    }
70
71    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
72        match op {
73            CompareOp::Eq => self.eq(other).into_py(py),
74            CompareOp::Ne => self.ne(other).into_py(py),
75            _ => py.NotImplemented(),
76        }
77    }
78
79    fn __hash__(&self) -> isize {
80        let mut h = DefaultHasher::new();
81        self.hash(&mut h);
82        h.finish() as isize
83    }
84
85    fn __repr__(&self) -> String {
86        format!("{self:?}")
87    }
88
89    fn __str__(&self) -> String {
90        self.to_string()
91    }
92
93    #[getter]
94    #[pyo3(name = "instrument_id")]
95    fn py_instrument_id(&self) -> InstrumentId {
96        self.instrument_id
97    }
98
99    #[getter]
100    #[pyo3(name = "bids")]
101    fn py_bids(&self) -> [BookOrder; DEPTH10_LEN] {
102        self.bids
103    }
104
105    #[getter]
106    #[pyo3(name = "asks")]
107    fn py_asks(&self) -> [BookOrder; DEPTH10_LEN] {
108        self.asks
109    }
110
111    #[getter]
112    #[pyo3(name = "bid_counts")]
113    fn py_bid_counts(&self) -> [u32; DEPTH10_LEN] {
114        self.bid_counts
115    }
116
117    #[getter]
118    #[pyo3(name = "ask_counts")]
119    fn py_ask_counts(&self) -> [u32; DEPTH10_LEN] {
120        self.ask_counts
121    }
122
123    #[getter]
124    #[pyo3(name = "flags")]
125    fn py_flags(&self) -> u8 {
126        self.flags
127    }
128
129    #[getter]
130    #[pyo3(name = "sequence")]
131    fn py_sequence(&self) -> u64 {
132        self.sequence
133    }
134
135    #[getter]
136    #[pyo3(name = "ts_event")]
137    fn py_ts_event(&self) -> u64 {
138        self.ts_event.as_u64()
139    }
140
141    #[getter]
142    #[pyo3(name = "ts_init")]
143    fn py_ts_init(&self) -> u64 {
144        self.ts_init.as_u64()
145    }
146
147    #[staticmethod]
148    #[pyo3(name = "fully_qualified_name")]
149    fn py_fully_qualified_name() -> String {
150        format!("{}:{}", PY_MODULE_MODEL, stringify!(OrderBookDepth10))
151    }
152
153    #[staticmethod]
154    #[pyo3(name = "get_metadata")]
155    fn py_get_metadata(
156        instrument_id: &InstrumentId,
157        price_precision: u8,
158        size_precision: u8,
159    ) -> PyResult<HashMap<String, String>> {
160        Ok(Self::get_metadata(
161            instrument_id,
162            price_precision,
163            size_precision,
164        ))
165    }
166
167    #[staticmethod]
168    #[pyo3(name = "get_fields")]
169    fn py_get_fields(py: Python<'_>) -> PyResult<Bound<'_, PyDict>> {
170        let py_dict = PyDict::new(py);
171        for (k, v) in Self::get_fields() {
172            py_dict.set_item(k, v)?;
173        }
174
175        Ok(py_dict)
176    }
177
178    // TODO: Expose this properly from a test stub provider
179    #[staticmethod]
180    #[pyo3(name = "get_stub")]
181    fn py_get_stub() -> Self {
182        let instrument_id = InstrumentId::from("AAPL.XNAS");
183        let flags = 0;
184        let sequence = 0;
185        let ts_event = 1;
186        let ts_init = 2;
187
188        let mut bids: [BookOrder; DEPTH10_LEN] = [BookOrder::default(); DEPTH10_LEN];
189        let mut asks: [BookOrder; DEPTH10_LEN] = [BookOrder::default(); DEPTH10_LEN];
190
191        // Create bids
192        let mut price = 99.00;
193        let mut quantity = 100.0;
194        let mut order_id = 1;
195
196        for order in bids.iter_mut().take(DEPTH10_LEN) {
197            *order = BookOrder::new(
198                OrderSide::Buy,
199                Price::new(price, 2),
200                Quantity::new(quantity, 0),
201                order_id,
202            );
203
204            price -= 1.0;
205            quantity += 100.0;
206            order_id += 1;
207        }
208
209        // Create asks
210        let mut price = 100.00;
211        let mut quantity = 100.0;
212        let mut order_id = 11;
213
214        for order in asks.iter_mut().take(DEPTH10_LEN) {
215            *order = BookOrder::new(
216                OrderSide::Sell,
217                Price::new(price, 2),
218                Quantity::new(quantity, 0),
219                order_id,
220            );
221
222            price += 1.0;
223            quantity += 100.0;
224            order_id += 1;
225        }
226
227        let bid_counts: [u32; 10] = [1; 10];
228        let ask_counts: [u32; 10] = [1; 10];
229
230        Self::new(
231            instrument_id,
232            bids,
233            asks,
234            bid_counts,
235            ask_counts,
236            flags,
237            sequence,
238            ts_event.into(),
239            ts_init.into(),
240        )
241    }
242
243    /// Returns a new object from the given dictionary representation.
244    #[staticmethod]
245    #[pyo3(name = "from_dict")]
246    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
247        from_dict_pyo3(py, values)
248    }
249
250    #[staticmethod]
251    #[pyo3(name = "from_json")]
252    fn py_from_json(data: Vec<u8>) -> PyResult<Self> {
253        Self::from_json_bytes(&data).map_err(to_pyvalue_err)
254    }
255
256    #[staticmethod]
257    #[pyo3(name = "from_msgpack")]
258    fn py_from_msgpack(data: Vec<u8>) -> PyResult<Self> {
259        Self::from_msgpack_bytes(&data).map_err(to_pyvalue_err)
260    }
261
262    /// Creates a `PyCapsule` containing a raw pointer to a `Data::Depth10` object.
263    ///
264    /// This function takes the current object (assumed to be of a type that can be represented as
265    /// `Data::Depth10`), and encapsulates a raw pointer to it within a `PyCapsule`.
266    ///
267    /// # Safety
268    ///
269    /// This function is safe as long as the following conditions are met:
270    /// - The `Data::Depth10` object pointed to by the capsule must remain valid for the lifetime of the capsule.
271    /// - The consumer of the capsule must ensure proper handling to avoid dereferencing a dangling pointer.
272    ///
273    /// # Panics
274    ///
275    /// The function will panic if the `PyCapsule` creation fails, which can occur if the
276    /// `Data::Depth10` object cannot be converted into a raw pointer.
277    #[pyo3(name = "as_pycapsule")]
278    fn py_as_pycapsule(&self, py: Python<'_>) -> PyObject {
279        data_to_pycapsule(py, Data::Depth10(*self))
280    }
281
282    /// Return a dictionary representation of the object.
283    #[pyo3(name = "as_dict")]
284    fn py_as_dict(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
285        to_dict_pyo3(py, self)
286    }
287
288    /// Return JSON encoded bytes representation of the object.
289    #[pyo3(name = "as_json")]
290    fn py_as_json(&self, py: Python<'_>) -> Py<PyAny> {
291        // Unwrapping is safe when serializing a valid object
292        self.as_json_bytes().unwrap().into_py(py)
293    }
294
295    /// Return MsgPack encoded bytes representation of the object.
296    #[pyo3(name = "as_msgpack")]
297    fn py_as_msgpack(&self, py: Python<'_>) -> Py<PyAny> {
298        // Unwrapping is safe when serializing a valid object
299        self.as_msgpack_bytes().unwrap().into_py(py)
300    }
301}