Skip to main content

nautilus_model/python/data/
prices.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,
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::{IndexPriceUpdate, MarkPriceUpdate},
43    identifiers::InstrumentId,
44    python::common::PY_MODULE_MODEL,
45    types::price::{Price, PriceRaw},
46};
47
48impl MarkPriceUpdate {
49    /// Creates a new [`MarkPriceUpdate`] from a Python object.
50    ///
51    /// # Errors
52    ///
53    /// Returns a `PyErr` if attribute extraction or type conversion 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 =
58            InstrumentId::from_str(instrument_id_str.as_str()).map_err(to_pyvalue_err)?;
59
60        let value_py: Bound<'_, PyAny> = obj.getattr("value")?.extract()?;
61        let value_raw: PriceRaw = value_py.getattr("raw")?.extract()?;
62        let value_prec: u8 = value_py.getattr("precision")?.extract()?;
63        let value = Price::from_raw(value_raw, value_prec);
64
65        let ts_event: u64 = obj.getattr("ts_event")?.extract()?;
66        let ts_init: u64 = obj.getattr("ts_init")?.extract()?;
67
68        Ok(Self::new(
69            instrument_id,
70            value,
71            ts_event.into(),
72            ts_init.into(),
73        ))
74    }
75}
76
77#[pymethods]
78#[pyo3_stub_gen::derive::gen_stub_pymethods]
79impl MarkPriceUpdate {
80    /// Represents a mark price update.
81    #[new]
82    fn py_new(instrument_id: InstrumentId, value: Price, ts_event: u64, ts_init: u64) -> Self {
83        Self::new(instrument_id, value, ts_event.into(), ts_init.into())
84    }
85
86    fn __setstate__(&mut self, state: &Bound<'_, PyAny>) -> PyResult<()> {
87        let py_tuple: &Bound<'_, PyTuple> = state.cast::<PyTuple>()?;
88        let binding = py_tuple.get_item(0)?;
89        let instrument_id_str = binding.cast::<PyString>()?.extract::<&str>()?;
90        let value_raw = py_tuple
91            .get_item(1)?
92            .cast::<PyInt>()?
93            .extract::<PriceRaw>()?;
94        let value_prec = py_tuple.get_item(2)?.cast::<PyInt>()?.extract::<u8>()?;
95
96        let ts_event = py_tuple.get_item(3)?.cast::<PyInt>()?.extract::<u64>()?;
97        let ts_init = py_tuple.get_item(4)?.cast::<PyInt>()?.extract::<u64>()?;
98
99        self.instrument_id = InstrumentId::from_str(instrument_id_str).map_err(to_pyvalue_err)?;
100        self.value = Price::from_raw(value_raw, value_prec);
101        self.ts_event = ts_event.into();
102        self.ts_init = ts_init.into();
103
104        Ok(())
105    }
106
107    fn __getstate__(&self, py: Python) -> PyResult<Py<PyAny>> {
108        (
109            self.instrument_id.to_string(),
110            self.value.raw,
111            self.value.precision,
112            self.ts_event.as_u64(),
113            self.ts_init.as_u64(),
114        )
115            .into_py_any(py)
116    }
117
118    fn __reduce__(&self, py: Python) -> PyResult<Py<PyAny>> {
119        let safe_constructor = py.get_type::<Self>().getattr("_safe_constructor")?;
120        let state = self.__getstate__(py)?;
121        (safe_constructor, PyTuple::empty(py), state).into_py_any(py)
122    }
123
124    #[staticmethod]
125    fn _safe_constructor() -> Self {
126        Self::new(
127            InstrumentId::from("NULL.NULL"),
128            Price::zero(0),
129            UnixNanos::default(),
130            UnixNanos::default(),
131        )
132    }
133
134    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
135        match op {
136            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
137            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
138            _ => py.NotImplemented(),
139        }
140    }
141
142    fn __hash__(&self) -> isize {
143        let mut h = DefaultHasher::new();
144        self.hash(&mut h);
145        h.finish() as isize
146    }
147
148    fn __repr__(&self) -> String {
149        format!("{}({})", stringify!(MarkPriceUpdate), self)
150    }
151
152    fn __str__(&self) -> String {
153        self.to_string()
154    }
155
156    #[getter]
157    #[pyo3(name = "instrument_id")]
158    fn py_instrument_id(&self) -> InstrumentId {
159        self.instrument_id
160    }
161
162    #[getter]
163    #[pyo3(name = "value")]
164    fn py_value(&self) -> Price {
165        self.value
166    }
167
168    #[getter]
169    #[pyo3(name = "ts_event")]
170    fn py_ts_event(&self) -> u64 {
171        self.ts_event.as_u64()
172    }
173
174    #[getter]
175    #[pyo3(name = "ts_init")]
176    fn py_ts_init(&self) -> u64 {
177        self.ts_init.as_u64()
178    }
179
180    #[staticmethod]
181    #[pyo3(name = "fully_qualified_name")]
182    fn py_fully_qualified_name() -> String {
183        format!("{}:{}", PY_MODULE_MODEL, stringify!(MarkPriceUpdate))
184    }
185
186    /// Returns the metadata for the type, for use with serialization formats.
187    #[staticmethod]
188    #[pyo3(name = "get_metadata")]
189    fn py_get_metadata(
190        instrument_id: &InstrumentId,
191        price_precision: u8,
192    ) -> HashMap<String, String> {
193        Self::get_metadata(instrument_id, price_precision)
194    }
195
196    /// Returns the field map for the type, for use with Arrow schemas.
197    #[staticmethod]
198    #[pyo3(name = "get_fields")]
199    fn py_get_fields(py: Python<'_>) -> PyResult<Bound<'_, PyDict>> {
200        let py_dict = PyDict::new(py);
201        for (k, v) in Self::get_fields() {
202            py_dict.set_item(k, v)?;
203        }
204
205        Ok(py_dict)
206    }
207
208    /// Returns a new object from the given dictionary representation.
209    #[staticmethod]
210    #[pyo3(name = "from_dict")]
211    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
212        from_dict_pyo3(py, values)
213    }
214
215    /// Return a dictionary representation of the object.
216    #[pyo3(name = "to_dict")]
217    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
218        to_dict_pyo3(py, self)
219    }
220
221    /// Return JSON encoded bytes representation of the object.
222    #[pyo3(name = "to_json_bytes")]
223    fn py_to_json_bytes(&self, py: Python<'_>) -> Py<PyAny> {
224        self.to_json_bytes().unwrap().into_py_any_unwrap(py)
225    }
226
227    /// Return MsgPack encoded bytes representation of the object.
228    #[pyo3(name = "to_msgpack_bytes")]
229    fn py_to_msgpack_bytes(&self, py: Python<'_>) -> Py<PyAny> {
230        self.to_msgpack_bytes().unwrap().into_py_any_unwrap(py)
231    }
232}
233
234#[pymethods]
235impl MarkPriceUpdate {
236    #[staticmethod]
237    #[pyo3(name = "from_json")]
238    fn py_from_json(data: &[u8]) -> PyResult<Self> {
239        Self::from_json_bytes(data).map_err(to_pyvalue_err)
240    }
241
242    #[staticmethod]
243    #[pyo3(name = "from_msgpack")]
244    fn py_from_msgpack(data: &[u8]) -> PyResult<Self> {
245        Self::from_msgpack_bytes(data).map_err(to_pyvalue_err)
246    }
247}
248
249impl IndexPriceUpdate {
250    /// Creates a new [`IndexPriceUpdate`] from a Python object.
251    ///
252    /// # Errors
253    ///
254    /// Returns a `PyErr` if attribute extraction or type conversion fails.
255    pub fn from_pyobject(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
256        let instrument_id_obj: Bound<'_, PyAny> = obj.getattr("instrument_id")?.extract()?;
257        let instrument_id_str: String = instrument_id_obj.getattr("value")?.extract()?;
258        let instrument_id =
259            InstrumentId::from_str(instrument_id_str.as_str()).map_err(to_pyvalue_err)?;
260
261        let value_py: Bound<'_, PyAny> = obj.getattr("value")?.extract()?;
262        let value_raw: PriceRaw = value_py.getattr("raw")?.extract()?;
263        let value_prec: u8 = value_py.getattr("precision")?.extract()?;
264        let value = Price::from_raw(value_raw, value_prec);
265
266        let ts_event: u64 = obj.getattr("ts_event")?.extract()?;
267        let ts_init: u64 = obj.getattr("ts_init")?.extract()?;
268
269        Ok(Self::new(
270            instrument_id,
271            value,
272            ts_event.into(),
273            ts_init.into(),
274        ))
275    }
276}
277
278#[pymethods]
279#[pyo3_stub_gen::derive::gen_stub_pymethods]
280impl IndexPriceUpdate {
281    /// Represents an index price update.
282    #[new]
283    fn py_new(instrument_id: InstrumentId, value: Price, ts_event: u64, ts_init: u64) -> Self {
284        Self::new(instrument_id, value, ts_event.into(), ts_init.into())
285    }
286
287    fn __setstate__(&mut self, state: &Bound<'_, PyAny>) -> PyResult<()> {
288        let py_tuple: &Bound<'_, PyTuple> = state.cast::<PyTuple>()?;
289        let binding = py_tuple.get_item(0)?;
290        let instrument_id_str = binding.cast::<PyString>()?.extract::<&str>()?;
291        let value_raw = py_tuple
292            .get_item(1)?
293            .cast::<PyInt>()?
294            .extract::<PriceRaw>()?;
295        let value_prec = py_tuple.get_item(2)?.cast::<PyInt>()?.extract::<u8>()?;
296
297        let ts_event = py_tuple.get_item(3)?.cast::<PyInt>()?.extract::<u64>()?;
298        let ts_init = py_tuple.get_item(4)?.cast::<PyInt>()?.extract::<u64>()?;
299
300        self.instrument_id = InstrumentId::from_str(instrument_id_str).map_err(to_pyvalue_err)?;
301        self.value = Price::from_raw(value_raw, value_prec);
302        self.ts_event = ts_event.into();
303        self.ts_init = ts_init.into();
304
305        Ok(())
306    }
307
308    fn __getstate__(&self, py: Python) -> PyResult<Py<PyAny>> {
309        (
310            self.instrument_id.to_string(),
311            self.value.raw,
312            self.value.precision,
313            self.ts_event.as_u64(),
314            self.ts_init.as_u64(),
315        )
316            .into_py_any(py)
317    }
318
319    fn __reduce__(&self, py: Python) -> PyResult<Py<PyAny>> {
320        let safe_constructor = py.get_type::<Self>().getattr("_safe_constructor")?;
321        let state = self.__getstate__(py)?;
322        (safe_constructor, PyTuple::empty(py), state).into_py_any(py)
323    }
324
325    #[staticmethod]
326    fn _safe_constructor() -> Self {
327        Self::new(
328            InstrumentId::from("NULL.NULL"),
329            Price::zero(0),
330            UnixNanos::default(),
331            UnixNanos::default(),
332        )
333    }
334
335    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
336        match op {
337            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
338            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
339            _ => py.NotImplemented(),
340        }
341    }
342
343    fn __hash__(&self) -> isize {
344        let mut h = DefaultHasher::new();
345        self.hash(&mut h);
346        h.finish() as isize
347    }
348
349    fn __repr__(&self) -> String {
350        format!("{}({})", stringify!(IndexPriceUpdate), self)
351    }
352
353    fn __str__(&self) -> String {
354        self.to_string()
355    }
356
357    #[getter]
358    #[pyo3(name = "instrument_id")]
359    fn py_instrument_id(&self) -> InstrumentId {
360        self.instrument_id
361    }
362
363    #[getter]
364    #[pyo3(name = "value")]
365    fn py_value(&self) -> Price {
366        self.value
367    }
368
369    #[getter]
370    #[pyo3(name = "ts_event")]
371    fn py_ts_event(&self) -> u64 {
372        self.ts_event.as_u64()
373    }
374
375    #[getter]
376    #[pyo3(name = "ts_init")]
377    fn py_ts_init(&self) -> u64 {
378        self.ts_init.as_u64()
379    }
380
381    #[staticmethod]
382    #[pyo3(name = "fully_qualified_name")]
383    fn py_fully_qualified_name() -> String {
384        format!("{}:{}", PY_MODULE_MODEL, stringify!(IndexPriceUpdate))
385    }
386
387    /// Returns the metadata for the type, for use with serialization formats.
388    #[staticmethod]
389    #[pyo3(name = "get_metadata")]
390    fn py_get_metadata(
391        instrument_id: &InstrumentId,
392        price_precision: u8,
393    ) -> HashMap<String, String> {
394        Self::get_metadata(instrument_id, price_precision)
395    }
396
397    /// Returns the field map for the type, for use with Arrow schemas.
398    #[staticmethod]
399    #[pyo3(name = "get_fields")]
400    fn py_get_fields(py: Python<'_>) -> PyResult<Bound<'_, PyDict>> {
401        let py_dict = PyDict::new(py);
402        for (k, v) in Self::get_fields() {
403            py_dict.set_item(k, v)?;
404        }
405
406        Ok(py_dict)
407    }
408
409    /// Returns a new object from the given dictionary representation.
410    #[staticmethod]
411    #[pyo3(name = "from_dict")]
412    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
413        from_dict_pyo3(py, values)
414    }
415
416    /// Return a dictionary representation of the object.
417    #[pyo3(name = "to_dict")]
418    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
419        to_dict_pyo3(py, self)
420    }
421
422    /// Return JSON encoded bytes representation of the object.
423    #[pyo3(name = "to_json_bytes")]
424    fn py_to_json_bytes(&self, py: Python<'_>) -> Py<PyAny> {
425        self.to_json_bytes().unwrap().into_py_any_unwrap(py)
426    }
427
428    /// Return MsgPack encoded bytes representation of the object.
429    #[pyo3(name = "to_msgpack_bytes")]
430    fn py_to_msgpack_bytes(&self, py: Python<'_>) -> Py<PyAny> {
431        self.to_msgpack_bytes().unwrap().into_py_any_unwrap(py)
432    }
433}
434
435#[pymethods]
436impl IndexPriceUpdate {
437    #[staticmethod]
438    #[pyo3(name = "from_json")]
439    fn py_from_json(data: &[u8]) -> PyResult<Self> {
440        Self::from_json_bytes(data).map_err(to_pyvalue_err)
441    }
442
443    #[staticmethod]
444    #[pyo3(name = "from_msgpack")]
445    fn py_from_msgpack(data: &[u8]) -> PyResult<Self> {
446        Self::from_msgpack_bytes(data).map_err(to_pyvalue_err)
447    }
448}
449
450#[cfg(test)]
451mod tests {
452    use nautilus_core::python::IntoPyObjectNautilusExt;
453    use pyo3::Python;
454    use rstest::{fixture, rstest};
455
456    use super::*;
457    use crate::{identifiers::InstrumentId, types::Price};
458
459    #[fixture]
460    fn mark_price() -> MarkPriceUpdate {
461        MarkPriceUpdate::new(
462            InstrumentId::from("BTC-USDT.OKX"),
463            Price::from("100_000.00"),
464            UnixNanos::from(1),
465            UnixNanos::from(2),
466        )
467    }
468
469    #[fixture]
470    fn index_price() -> IndexPriceUpdate {
471        IndexPriceUpdate::new(
472            InstrumentId::from("BTC-USDT.OKX"),
473            Price::from("100_000.00"),
474            UnixNanos::from(1),
475            UnixNanos::from(2),
476        )
477    }
478
479    #[rstest]
480    fn test_mark_price_to_dict(mark_price: MarkPriceUpdate) {
481        Python::initialize();
482        Python::attach(|py| {
483            let dict_string = mark_price.py_to_dict(py).unwrap().to_string();
484            let expected_string = "{'type': 'MarkPriceUpdate', 'instrument_id': 'BTC-USDT.OKX', 'value': '100000.00', 'ts_event': 1, 'ts_init': 2}";
485            assert_eq!(dict_string, expected_string);
486        });
487    }
488
489    #[rstest]
490    fn test_mark_price_from_dict(mark_price: MarkPriceUpdate) {
491        Python::initialize();
492        Python::attach(|py| {
493            let dict = mark_price.py_to_dict(py).unwrap();
494            let parsed = MarkPriceUpdate::py_from_dict(py, dict).unwrap();
495            assert_eq!(parsed, mark_price);
496        });
497    }
498
499    #[rstest]
500    fn test_mark_price_from_pyobject(mark_price: MarkPriceUpdate) {
501        Python::initialize();
502        Python::attach(|py| {
503            let tick_pyobject = mark_price.into_py_any_unwrap(py);
504            let parsed_tick = MarkPriceUpdate::from_pyobject(tick_pyobject.bind(py)).unwrap();
505            assert_eq!(parsed_tick, mark_price);
506        });
507    }
508
509    #[rstest]
510    fn test_index_price_to_dict(index_price: IndexPriceUpdate) {
511        Python::initialize();
512        Python::attach(|py| {
513            let dict_string = index_price.py_to_dict(py).unwrap().to_string();
514            let expected_string = "{'type': 'IndexPriceUpdate', 'instrument_id': 'BTC-USDT.OKX', 'value': '100000.00', 'ts_event': 1, 'ts_init': 2}";
515            assert_eq!(dict_string, expected_string);
516        });
517    }
518
519    #[rstest]
520    fn test_index_price_from_dict(index_price: IndexPriceUpdate) {
521        Python::initialize();
522        Python::attach(|py| {
523            let dict = index_price.py_to_dict(py).unwrap();
524            let parsed = IndexPriceUpdate::py_from_dict(py, dict).unwrap();
525            assert_eq!(parsed, index_price);
526        });
527    }
528
529    #[rstest]
530    fn test_index_price_from_pyobject(index_price: IndexPriceUpdate) {
531        Python::initialize();
532        Python::attach(|py| {
533            let tick_pyobject = index_price.into_py_any_unwrap(py);
534            let parsed_tick = IndexPriceUpdate::from_pyobject(tick_pyobject.bind(py)).unwrap();
535            assert_eq!(parsed_tick, index_price);
536        });
537    }
538}