Skip to main content

nautilus_model/python/data/
quote.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::QuoteTick,
43    enums::PriceType,
44    identifiers::InstrumentId,
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 QuoteTick {
55    /// Represents a quote tick in a market.
56    #[new]
57    fn py_new(
58        instrument_id: InstrumentId,
59        bid_price: Price,
60        ask_price: Price,
61        bid_size: Quantity,
62        ask_size: Quantity,
63        ts_event: u64,
64        ts_init: u64,
65    ) -> PyResult<Self> {
66        Self::new_checked(
67            instrument_id,
68            bid_price,
69            ask_price,
70            bid_size,
71            ask_size,
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: &str = binding.cast::<PyString>()?.extract()?;
82        let bid_price_raw: PriceRaw = py_tuple.get_item(1)?.cast::<PyInt>()?.extract()?;
83        let ask_price_raw: PriceRaw = py_tuple.get_item(2)?.cast::<PyInt>()?.extract()?;
84        let bid_price_prec: u8 = py_tuple.get_item(3)?.cast::<PyInt>()?.extract()?;
85        let ask_price_prec: u8 = py_tuple.get_item(4)?.cast::<PyInt>()?.extract()?;
86
87        let bid_size_raw: QuantityRaw = py_tuple.get_item(5)?.cast::<PyInt>()?.extract()?;
88        let ask_size_raw: QuantityRaw = py_tuple.get_item(6)?.cast::<PyInt>()?.extract()?;
89        let bid_size_prec: u8 = py_tuple.get_item(7)?.cast::<PyInt>()?.extract()?;
90        let ask_size_prec: u8 = py_tuple.get_item(8)?.cast::<PyInt>()?.extract()?;
91        let ts_event: u64 = py_tuple.get_item(9)?.cast::<PyInt>()?.extract()?;
92        let ts_init: u64 = py_tuple.get_item(10)?.cast::<PyInt>()?.extract()?;
93
94        let instrument_id = InstrumentId::from_str(instrument_id_str).map_err(to_pyvalue_err)?;
95        let bid_price = Price::from_raw_checked(bid_price_raw, bid_price_prec)
96            .map_err(correctness_error_to_pyvalue_err)?;
97        let ask_price = Price::from_raw_checked(ask_price_raw, ask_price_prec)
98            .map_err(correctness_error_to_pyvalue_err)?;
99        let bid_size = Quantity::from_raw_checked(bid_size_raw, bid_size_prec)
100            .map_err(correctness_error_to_pyvalue_err)?;
101        let ask_size = Quantity::from_raw_checked(ask_size_raw, ask_size_prec)
102            .map_err(correctness_error_to_pyvalue_err)?;
103
104        *self = Self {
105            instrument_id,
106            bid_price,
107            ask_price,
108            bid_size,
109            ask_size,
110            ts_event: ts_event.into(),
111            ts_init: ts_init.into(),
112        };
113
114        Ok(())
115    }
116
117    fn __getstate__(&self, py: Python) -> PyResult<Py<PyAny>> {
118        (
119            self.instrument_id.to_string(),
120            self.bid_price.raw(),
121            self.ask_price.raw(),
122            self.bid_price.precision,
123            self.ask_price.precision,
124            self.bid_size.raw(),
125            self.ask_size.raw(),
126            self.bid_size.precision,
127            self.ask_size.precision,
128            self.ts_event.as_u64(),
129            self.ts_init.as_u64(),
130        )
131            .into_py_any(py)
132    }
133
134    fn __reduce__(&self, py: Python) -> PyResult<Py<PyAny>> {
135        let safe_constructor = py.get_type::<Self>().getattr("_safe_constructor")?;
136        let state = self.__getstate__(py)?;
137        (safe_constructor, PyTuple::empty(py), state).into_py_any(py)
138    }
139
140    #[staticmethod]
141    #[pyo3(name = "_safe_constructor")]
142    fn py_safe_constructor() -> PyResult<Self> {
143        Self::new_checked(
144            InstrumentId::from("NULL.NULL"),
145            Price::zero(0),
146            Price::zero(0),
147            Quantity::zero(0),
148            Quantity::zero(0),
149            UnixNanos::default(),
150            UnixNanos::default(),
151        )
152        .map_err(to_pyvalue_err)
153    }
154
155    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
156        match op {
157            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
158            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
159            _ => py.NotImplemented(),
160        }
161    }
162
163    fn __hash__(&self) -> isize {
164        let mut h = DefaultHasher::new();
165        self.hash(&mut h);
166        h.finish() as isize
167    }
168
169    fn __repr__(&self) -> String {
170        format!("{}({})", stringify!(QuoteTick), self)
171    }
172
173    fn __str__(&self) -> String {
174        self.to_string()
175    }
176
177    #[getter]
178    #[pyo3(name = "instrument_id")]
179    fn py_instrument_id(&self) -> InstrumentId {
180        self.instrument_id
181    }
182
183    #[getter]
184    #[pyo3(name = "bid_price")]
185    fn py_bid_price(&self) -> Price {
186        self.bid_price
187    }
188
189    #[getter]
190    #[pyo3(name = "ask_price")]
191    fn py_ask_price(&self) -> Price {
192        self.ask_price
193    }
194
195    #[getter]
196    #[pyo3(name = "bid_size")]
197    fn py_bid_size(&self) -> Quantity {
198        self.bid_size
199    }
200
201    #[getter]
202    #[pyo3(name = "ask_size")]
203    fn py_ask_size(&self) -> Quantity {
204        self.ask_size
205    }
206
207    #[getter]
208    #[pyo3(name = "ts_event")]
209    fn py_ts_event(&self) -> u64 {
210        self.ts_event.as_u64()
211    }
212
213    #[getter]
214    #[pyo3(name = "ts_init")]
215    fn py_ts_init(&self) -> u64 {
216        self.ts_init.as_u64()
217    }
218
219    #[staticmethod]
220    #[pyo3(name = "fully_qualified_name")]
221    fn py_fully_qualified_name() -> String {
222        format!("{}:{}", PY_MODULE_MODEL, stringify!(QuoteTick))
223    }
224
225    /// Returns the metadata for the type, for use with serialization formats.
226    #[staticmethod]
227    #[pyo3(name = "get_metadata")]
228    fn py_get_metadata(
229        instrument_id: &InstrumentId,
230        price_precision: u8,
231        size_precision: u8,
232    ) -> HashMap<String, String> {
233        Self::get_metadata(instrument_id, price_precision, size_precision)
234    }
235
236    /// Returns the field map for the type, for use with Arrow schemas.
237    #[staticmethod]
238    #[pyo3(name = "get_fields")]
239    fn py_get_fields(py: Python<'_>) -> PyResult<Bound<'_, PyDict>> {
240        let py_dict = PyDict::new(py);
241        for (k, v) in Self::get_fields() {
242            py_dict.set_item(k, v)?;
243        }
244
245        Ok(py_dict)
246    }
247
248    #[staticmethod]
249    #[pyo3(name = "from_raw")]
250    #[expect(clippy::too_many_arguments)]
251    fn py_from_raw(
252        instrument_id: InstrumentId,
253        bid_price_raw: PriceRaw,
254        ask_price_raw: PriceRaw,
255        bid_price_prec: u8,
256        ask_price_prec: u8,
257        bid_size_raw: QuantityRaw,
258        ask_size_raw: QuantityRaw,
259        bid_size_prec: u8,
260        ask_size_prec: u8,
261        ts_event: u64,
262        ts_init: u64,
263    ) -> PyResult<Self> {
264        let bid_price = Price::from_raw_checked(bid_price_raw, bid_price_prec)
265            .map_err(correctness_error_to_pyvalue_err)?;
266        let ask_price = Price::from_raw_checked(ask_price_raw, ask_price_prec)
267            .map_err(correctness_error_to_pyvalue_err)?;
268        let bid_size = Quantity::from_raw_checked(bid_size_raw, bid_size_prec)
269            .map_err(correctness_error_to_pyvalue_err)?;
270        let ask_size = Quantity::from_raw_checked(ask_size_raw, ask_size_prec)
271            .map_err(correctness_error_to_pyvalue_err)?;
272
273        Self::new_checked(
274            instrument_id,
275            bid_price,
276            ask_price,
277            bid_size,
278            ask_size,
279            ts_event.into(),
280            ts_init.into(),
281        )
282        .map_err(to_pyvalue_err)
283    }
284
285    /// Returns a new object from the given dictionary representation.
286    #[staticmethod]
287    #[pyo3(name = "from_dict")]
288    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
289        from_dict_pyo3(py, values)
290    }
291
292    /// Returns the `Price` for this quote depending on the given `price_type`.
293    ///
294    /// # Errors
295    ///
296    /// Returns an error if `price_type` is not `Bid`, `Ask`, or `Mid` (a quote has no `Last` price).
297    #[pyo3(name = "extract_price")]
298    fn py_extract_price(&self, price_type: PriceType) -> PyResult<Price> {
299        self.extract_price(price_type).map_err(to_pyvalue_err)
300    }
301
302    /// Returns the `Quantity` for this quote depending on the given `price_type`.
303    ///
304    /// # Errors
305    ///
306    /// Returns an error if `price_type` is not `Bid`, `Ask`, or `Mid` (a quote has no `Last` size).
307    #[pyo3(name = "extract_size")]
308    fn py_extract_size(&self, price_type: PriceType) -> PyResult<Quantity> {
309        self.extract_size(price_type).map_err(to_pyvalue_err)
310    }
311
312    /// Return a dictionary representation of the object.
313    #[pyo3(name = "to_dict")]
314    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
315        to_dict_pyo3(py, self)
316    }
317
318    /// Return JSON encoded bytes representation of the object.
319    #[pyo3(name = "to_json_bytes")]
320    fn py_to_json_bytes(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
321        self.to_json_bytes()
322            .map_err(to_pyvalue_err)?
323            .into_py_any(py)
324    }
325
326    /// Return `MsgPack` encoded bytes representation of the object.
327    #[pyo3(name = "to_msgpack_bytes")]
328    fn py_to_msgpack_bytes(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
329        self.to_msgpack_bytes()
330            .map_err(to_pyvalue_err)?
331            .into_py_any(py)
332    }
333}
334
335#[pymethods]
336impl QuoteTick {
337    #[staticmethod]
338    #[pyo3(name = "from_json")]
339    fn py_from_json(data: &[u8]) -> PyResult<Self> {
340        Self::from_json_bytes(data).map_err(to_pyvalue_err)
341    }
342
343    #[staticmethod]
344    #[pyo3(name = "from_msgpack")]
345    fn py_from_msgpack(data: &[u8]) -> PyResult<Self> {
346        Self::from_msgpack_bytes(data).map_err(to_pyvalue_err)
347    }
348}
349
350#[cfg(test)]
351mod tests {
352    use pyo3::Python;
353    use rstest::rstest;
354
355    use crate::{
356        data::{QuoteTick, stubs::quote_ethusdt_binance},
357        identifiers::InstrumentId,
358        types::{Price, Quantity, fixed::check_fixed_precision},
359    };
360
361    #[rstest]
362    #[case(
363    Price::new(0.010_000, 6),
364    Price::new(0.010_001_0, 7), // Mismatched precision
365    Quantity::new(0.001_000, 6),
366    Quantity::new(0.001_000, 6),
367)]
368    #[case(
369    Price::new(0.010_000, 6),
370    Price::new(0.010_001, 6),
371    Quantity::new(0.001_000, 6),
372    Quantity::new(0.001_000_0, 7), // Mismatched precision
373)]
374    fn test_quote_tick_py_new_invalid_precisions(
375        #[case] bid_price: Price,
376        #[case] ask_price: Price,
377        #[case] bid_size: Quantity,
378        #[case] ask_size: Quantity,
379    ) {
380        let instrument_id = InstrumentId::from("ETH-USDT-SWAP.OKX");
381        let ts_event = 0;
382        let ts_init = 1;
383
384        let result = QuoteTick::py_new(
385            instrument_id,
386            bid_price,
387            ask_price,
388            bid_size,
389            ask_size,
390            ts_event,
391            ts_init,
392        );
393
394        assert!(result.is_err());
395    }
396
397    #[rstest]
398    fn test_py_from_raw_rejects_invalid_precision(quote_ethusdt_binance: QuoteTick) {
399        let quote = quote_ethusdt_binance;
400        let expected = check_fixed_precision(u8::MAX).unwrap_err();
401
402        Python::initialize();
403        Python::attach(|_| {
404            let error = QuoteTick::py_from_raw(
405                quote.instrument_id,
406                quote.bid_price.raw,
407                quote.ask_price.raw,
408                quote.bid_price.precision,
409                quote.ask_price.precision,
410                quote.bid_size.raw,
411                quote.ask_size.raw,
412                u8::MAX,
413                quote.ask_size.precision,
414                quote.ts_event.as_u64(),
415                quote.ts_init.as_u64(),
416            )
417            .unwrap_err();
418
419            assert_eq!(error.to_string(), format!("ValueError: {expected}"));
420        });
421    }
422
423    #[rstest]
424    fn test_to_dict(quote_ethusdt_binance: QuoteTick) {
425        let quote = quote_ethusdt_binance;
426
427        Python::initialize();
428        Python::attach(|py| {
429            let dict_string = quote.py_to_dict(py).unwrap().to_string();
430            let expected_string = "{'type': 'QuoteTick', 'instrument_id': 'ETHUSDT-PERP.BINANCE', 'bid_price': '10000.0000', 'ask_price': '10001.0000', 'bid_size': '1.00000000', 'ask_size': '1.00000000', 'ts_event': 0, 'ts_init': 1}";
431            assert_eq!(dict_string, expected_string);
432        });
433    }
434
435    #[rstest]
436    fn test_from_dict(quote_ethusdt_binance: QuoteTick) {
437        let quote = quote_ethusdt_binance;
438
439        Python::initialize();
440        Python::attach(|py| {
441            let dict = quote.py_to_dict(py).unwrap();
442            let parsed = QuoteTick::py_from_dict(py, dict).unwrap();
443            assert_eq!(parsed, quote);
444        });
445    }
446}