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, types::fixed::FloatArithmetic},
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: Option<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    const fn py_side(&self) -> Option<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) -> PyResult<f64> {
105        self.price.check_float_precision()?;
106        self.size.check_float_precision()?;
107        Ok(self.exposure())
108    }
109
110    /// Returns the signed order size as `f64`, positive for buys, negative for sells.
111    #[pyo3(name = "signed_size")]
112    fn py_signed_size(&self) -> PyResult<f64> {
113        self.size.check_float_precision()?;
114        Ok(self.signed_size())
115    }
116
117    /// Constructs a `BookOrder` from its dictionary representation.
118    ///
119    /// # Errors
120    ///
121    /// Returns an error if deserialization from the Python dict fails.
122    #[staticmethod]
123    #[pyo3(name = "from_dict")]
124    pub fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
125        from_dict_pyo3(py, values)
126    }
127
128    /// Converts the `BookOrder` into a Python dict representation.
129    ///
130    /// # Errors
131    ///
132    /// Returns an error if serialization into a Python dict fails.
133    #[pyo3(name = "to_dict")]
134    pub fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
135        to_dict_pyo3(py, self)
136    }
137
138    /// Return JSON encoded bytes representation of the object.
139    #[pyo3(name = "to_json_bytes")]
140    fn py_to_json_bytes(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
141        self.to_json_bytes()
142            .map_err(to_pyvalue_err)?
143            .into_py_any(py)
144    }
145
146    /// Return `MsgPack` encoded bytes representation of the object.
147    #[pyo3(name = "to_msgpack_bytes")]
148    fn py_to_msgpack_bytes(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
149        self.to_msgpack_bytes()
150            .map_err(to_pyvalue_err)?
151            .into_py_any(py)
152    }
153
154    fn __reduce__(&self, py: Python) -> PyResult<Py<PyAny>> {
155        let from_dict = py.get_type::<Self>().getattr("from_dict")?;
156        let dict = self.py_to_dict(py)?;
157        (from_dict, (dict,)).into_py_any(py)
158    }
159}
160
161#[pymethods]
162impl BookOrder {
163    #[staticmethod]
164    #[pyo3(name = "from_json")]
165    fn py_from_json(data: &[u8]) -> PyResult<Self> {
166        Self::from_json_bytes(data).map_err(to_pyvalue_err)
167    }
168
169    #[staticmethod]
170    #[pyo3(name = "from_msgpack")]
171    fn py_from_msgpack(data: &[u8]) -> PyResult<Self> {
172        Self::from_msgpack_bytes(data).map_err(to_pyvalue_err)
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use rstest::rstest;
179
180    use super::*;
181    use crate::data::stubs::stub_book_order;
182
183    #[rstest]
184    fn test_to_dict(stub_book_order: BookOrder) {
185        let book_order = stub_book_order;
186
187        Python::initialize();
188        Python::attach(|py| {
189            let dict_string = book_order.py_to_dict(py).unwrap().to_string();
190            let expected_string =
191                "{'side': 'BUY', 'price': '100.00', 'size': '10', 'order_id': 123456}";
192            assert_eq!(dict_string, expected_string);
193        });
194    }
195
196    #[rstest]
197    fn test_from_dict(stub_book_order: BookOrder) {
198        let book_order = stub_book_order;
199
200        Python::initialize();
201        Python::attach(|py| {
202            let dict = book_order.py_to_dict(py).unwrap();
203            let parsed = BookOrder::py_from_dict(py, dict).unwrap();
204            assert_eq!(parsed, book_order);
205        });
206    }
207}