nautilus_model/python/data/
order.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.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        IntoPyObjectPoseiExt,
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    /// Constructs a `BookOrder` from its dictionary representation.
108    ///
109    /// # Errors
110    ///
111    /// Returns a `PyErr` if deserialization from the Python dict fails.
112    #[staticmethod]
113    #[pyo3(name = "from_dict")]
114    pub fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
115        from_dict_pyo3(py, values)
116    }
117
118    #[staticmethod]
119    #[pyo3(name = "from_json")]
120    fn py_from_json(data: Vec<u8>) -> PyResult<Self> {
121        Self::from_json_bytes(&data).map_err(to_pyvalue_err)
122    }
123
124    #[staticmethod]
125    #[pyo3(name = "from_msgpack")]
126    fn py_from_msgpack(data: Vec<u8>) -> PyResult<Self> {
127        Self::from_msgpack_bytes(&data).map_err(to_pyvalue_err)
128    }
129
130    /// Converts the `BookOrder` into a Python dict representation.
131    ///
132    /// # Errors
133    ///
134    /// Returns a `PyErr` if serialization into a Python dict fails.
135    #[pyo3(name = "to_dict")]
136    pub fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
137        to_dict_pyo3(py, self)
138    }
139
140    /// Return JSON encoded bytes representation of the object.
141    #[pyo3(name = "to_json_bytes")]
142    fn py_to_json_bytes(&self, py: Python<'_>) -> Py<PyAny> {
143        // SAFETY: Unwrap safe when serializing a valid object
144        self.to_json_bytes().unwrap().into_py_any_unwrap(py)
145    }
146
147    /// Return MsgPack encoded bytes representation of the object.
148    #[pyo3(name = "to_msgpack_bytes")]
149    fn py_to_msgpack_bytes(&self, py: Python<'_>) -> Py<PyAny> {
150        // SAFETY: Unwrap safe when serializing a valid object
151        self.to_msgpack_bytes().unwrap().into_py_any_unwrap(py)
152    }
153}
154
155////////////////////////////////////////////////////////////////////////////////
156// Tests
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        pyo3::prepare_freethreaded_python();
168        let book_order = stub_book_order;
169
170        Python::with_gil(|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        pyo3::prepare_freethreaded_python();
181        let book_order = stub_book_order;
182
183        Python::with_gil(|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}