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