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