nautilus_model/python/data/
order.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};
20
21use nautilus_core::{
22    python::{
23        IntoPyObjectNautilusExt,
24        serialization::{from_dict_pyo3, to_dict_pyo3},
25        to_pyvalue_err,
26    },
27    serialization::{
28        Serializable,
29        msgpack::{FromMsgPack, ToMsgPack},
30    },
31};
32use pyo3::{prelude::*, pyclass::CompareOp, types::PyDict};
33
34use crate::{
35    data::order::{BookOrder, OrderId},
36    enums::OrderSide,
37    python::common::PY_MODULE_MODEL,
38    types::{Price, Quantity},
39};
40
41#[pymethods]
42impl BookOrder {
43    #[new]
44    fn py_new(side: OrderSide, price: Price, size: Quantity, order_id: OrderId) -> Self {
45        Self::new(side, price, size, order_id)
46    }
47
48    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
49        match op {
50            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
51            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
52            _ => py.NotImplemented(),
53        }
54    }
55
56    fn __hash__(&self) -> isize {
57        let mut h = DefaultHasher::new();
58        self.hash(&mut h);
59        h.finish() as isize
60    }
61
62    fn __repr__(&self) -> String {
63        format!("{self:?}")
64    }
65
66    fn __str__(&self) -> String {
67        self.to_string()
68    }
69
70    #[getter]
71    #[pyo3(name = "side")]
72    fn py_side(&self) -> OrderSide {
73        self.side
74    }
75
76    #[getter]
77    #[pyo3(name = "price")]
78    fn py_price(&self) -> Price {
79        self.price
80    }
81
82    #[getter]
83    #[pyo3(name = "size")]
84    fn py_size(&self) -> Quantity {
85        self.size
86    }
87
88    #[getter]
89    #[pyo3(name = "order_id")]
90    fn py_order_id(&self) -> u64 {
91        self.order_id
92    }
93
94    #[staticmethod]
95    #[pyo3(name = "fully_qualified_name")]
96    fn py_fully_qualified_name() -> String {
97        format!("{}:{}", PY_MODULE_MODEL, stringify!(BookOrder))
98    }
99
100    #[pyo3(name = "exposure")]
101    fn py_exposure(&self) -> f64 {
102        self.exposure()
103    }
104
105    #[pyo3(name = "signed_size")]
106    fn py_signed_size(&self) -> f64 {
107        self.signed_size()
108    }
109
110    /// Constructs a `BookOrder` from its dictionary representation.
111    ///
112    /// # Errors
113    ///
114    /// Returns a `PyErr` if deserialization from the Python dict fails.
115    #[staticmethod]
116    #[pyo3(name = "from_dict")]
117    pub fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
118        from_dict_pyo3(py, values)
119    }
120
121    #[staticmethod]
122    #[pyo3(name = "from_json")]
123    fn py_from_json(data: Vec<u8>) -> PyResult<Self> {
124        Self::from_json_bytes(&data).map_err(to_pyvalue_err)
125    }
126
127    #[staticmethod]
128    #[pyo3(name = "from_msgpack")]
129    fn py_from_msgpack(data: Vec<u8>) -> PyResult<Self> {
130        Self::from_msgpack_bytes(&data).map_err(to_pyvalue_err)
131    }
132
133    /// Converts the `BookOrder` into a Python dict representation.
134    ///
135    /// # Errors
136    ///
137    /// Returns a `PyErr` if serialization into a Python dict fails.
138    #[pyo3(name = "to_dict")]
139    pub fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
140        to_dict_pyo3(py, self)
141    }
142
143    /// Return JSON encoded bytes representation of the object.
144    #[pyo3(name = "to_json_bytes")]
145    fn py_to_json_bytes(&self, py: Python<'_>) -> Py<PyAny> {
146        // SAFETY: Unwrap safe when serializing a valid object
147        self.to_json_bytes().unwrap().into_py_any_unwrap(py)
148    }
149
150    /// Return MsgPack encoded bytes representation of the object.
151    #[pyo3(name = "to_msgpack_bytes")]
152    fn py_to_msgpack_bytes(&self, py: Python<'_>) -> Py<PyAny> {
153        // SAFETY: Unwrap safe when serializing a valid object
154        self.to_msgpack_bytes().unwrap().into_py_any_unwrap(py)
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use rstest::rstest;
161
162    use super::*;
163    use crate::data::stubs::stub_book_order;
164
165    #[rstest]
166    fn test_to_dict(stub_book_order: BookOrder) {
167        let book_order = stub_book_order;
168
169        Python::initialize();
170        Python::attach(|py| {
171            let dict_string = book_order.py_to_dict(py).unwrap().to_string();
172            let expected_string =
173                r"{'side': 'BUY', 'price': '100.00', 'size': '10', 'order_id': 123456}";
174            assert_eq!(dict_string, expected_string);
175        });
176    }
177
178    #[rstest]
179    fn test_from_dict(stub_book_order: BookOrder) {
180        let book_order = stub_book_order;
181
182        Python::initialize();
183        Python::attach(|py| {
184            let dict = book_order.py_to_dict(py).unwrap();
185            let parsed = BookOrder::py_from_dict(py, dict).unwrap();
186            assert_eq!(parsed, book_order);
187        });
188    }
189}