Skip to main content

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