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