Skip to main content

nautilus_model/python/instruments/
commodity.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    from_pydict,
23    python::{IntoPyObjectNautilusExt, serialization::from_dict_pyo3, to_pyvalue_err},
24};
25use pyo3::{basic::CompareOp, prelude::*, types::PyDict};
26use rust_decimal::Decimal;
27
28use crate::{
29    enums::AssetClass,
30    identifiers::{InstrumentId, Symbol},
31    instruments::Commodity,
32    types::{Currency, Money, Price, Quantity},
33};
34
35#[pymethods]
36impl Commodity {
37    #[allow(clippy::too_many_arguments)]
38    #[new]
39    #[pyo3(signature = (instrument_id, raw_symbol, asset_class, quote_currency, price_precision, size_precision, price_increment, size_increment, ts_event, ts_init, lot_size=None, max_quantity=None, min_quantity=None, max_notional=None, min_notional=None, max_price=None, min_price=None, margin_init=None, margin_maint=None, maker_fee=None, taker_fee=None, info=None))]
40    fn py_new(
41        instrument_id: InstrumentId,
42        raw_symbol: Symbol,
43        asset_class: AssetClass,
44        quote_currency: Currency,
45        price_precision: u8,
46        size_precision: u8,
47        price_increment: Price,
48        size_increment: Quantity,
49        ts_event: u64,
50        ts_init: u64,
51        lot_size: Option<Quantity>,
52        max_quantity: Option<Quantity>,
53        min_quantity: Option<Quantity>,
54        max_notional: Option<Money>,
55        min_notional: Option<Money>,
56        max_price: Option<Price>,
57        min_price: Option<Price>,
58        margin_init: Option<Decimal>,
59        margin_maint: Option<Decimal>,
60        maker_fee: Option<Decimal>,
61        taker_fee: Option<Decimal>,
62        info: Option<Py<PyDict>>,
63    ) -> PyResult<Self> {
64        let info_map = if let Some(info_dict) = info {
65            Python::attach(|py| from_pydict(py, info_dict))?
66        } else {
67            None
68        };
69
70        Self::new_checked(
71            instrument_id,
72            raw_symbol,
73            asset_class,
74            quote_currency,
75            price_precision,
76            size_precision,
77            price_increment,
78            size_increment,
79            lot_size,
80            max_quantity,
81            min_quantity,
82            max_notional,
83            min_notional,
84            max_price,
85            min_price,
86            margin_init,
87            margin_maint,
88            maker_fee,
89            taker_fee,
90            info_map,
91            ts_event.into(),
92            ts_init.into(),
93        )
94        .map_err(to_pyvalue_err)
95    }
96
97    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
98        match op {
99            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
100            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
101            _ => py.NotImplemented(),
102        }
103    }
104
105    fn __hash__(&self) -> isize {
106        let mut hasher = DefaultHasher::new();
107        self.hash(&mut hasher);
108        hasher.finish() as isize
109    }
110
111    #[getter]
112    fn type_str(&self) -> &str {
113        stringify!(Commodity)
114    }
115
116    #[getter]
117    #[pyo3(name = "id")]
118    fn py_id(&self) -> InstrumentId {
119        self.id
120    }
121
122    #[getter]
123    #[pyo3(name = "raw_symbol")]
124    fn py_raw_symbol(&self) -> Symbol {
125        self.raw_symbol
126    }
127
128    #[getter]
129    #[pyo3(name = "asset_class")]
130    fn py_asset_class(&self) -> AssetClass {
131        self.asset_class
132    }
133
134    #[getter]
135    #[pyo3(name = "quote_currency")]
136    fn py_quote_currency(&self) -> Currency {
137        self.quote_currency
138    }
139
140    #[getter]
141    #[pyo3(name = "price_precision")]
142    fn py_price_precision(&self) -> u8 {
143        self.price_precision
144    }
145
146    #[getter]
147    #[pyo3(name = "size_precision")]
148    fn py_size_precision(&self) -> u8 {
149        self.size_precision
150    }
151
152    #[getter]
153    #[pyo3(name = "price_increment")]
154    fn py_price_increment(&self) -> Price {
155        self.price_increment
156    }
157
158    #[getter]
159    #[pyo3(name = "size_increment")]
160    fn py_size_increment(&self) -> Quantity {
161        self.size_increment
162    }
163
164    #[getter]
165    #[pyo3(name = "lot_size")]
166    fn py_lot_size(&self) -> Option<Quantity> {
167        self.lot_size
168    }
169
170    #[getter]
171    #[pyo3(name = "max_quantity")]
172    fn py_max_quantity(&self) -> Option<Quantity> {
173        self.max_quantity
174    }
175
176    #[getter]
177    #[pyo3(name = "min_quantity")]
178    fn py_min_quantity(&self) -> Option<Quantity> {
179        self.min_quantity
180    }
181
182    #[getter]
183    #[pyo3(name = "max_notional")]
184    fn py_max_notional(&self) -> Option<Money> {
185        self.max_notional
186    }
187
188    #[getter]
189    #[pyo3(name = "min_notional")]
190    fn py_min_notional(&self) -> Option<Money> {
191        self.min_notional
192    }
193
194    #[getter]
195    #[pyo3(name = "max_price")]
196    fn py_max_price(&self) -> Option<Price> {
197        self.max_price
198    }
199
200    #[getter]
201    #[pyo3(name = "min_price")]
202    fn py_min_price(&self) -> Option<Price> {
203        self.min_price
204    }
205
206    #[getter]
207    #[pyo3(name = "margin_init")]
208    fn py_margin_init(&self) -> Decimal {
209        self.margin_init
210    }
211
212    #[getter]
213    #[pyo3(name = "margin_maint")]
214    fn py_margin_maint(&self) -> Decimal {
215        self.margin_maint
216    }
217
218    #[getter]
219    #[pyo3(name = "maker_fee")]
220    fn py_maker_fee(&self) -> Decimal {
221        self.maker_fee
222    }
223
224    #[getter]
225    #[pyo3(name = "taker_fee")]
226    fn py_taker_fee(&self) -> Decimal {
227        self.taker_fee
228    }
229
230    #[getter]
231    #[pyo3(name = "ts_event")]
232    fn py_ts_event(&self) -> u64 {
233        self.ts_event.as_u64()
234    }
235
236    #[getter]
237    #[pyo3(name = "ts_init")]
238    fn py_ts_init(&self) -> u64 {
239        self.ts_init.as_u64()
240    }
241
242    #[getter]
243    #[pyo3(name = "info")]
244    fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
245        if let Some(ref info_map) = self.info {
246            let py_dict = PyDict::new(py);
247            for (key, value) in info_map {
248                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
249                let py_value =
250                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
251                py_dict.set_item(key, py_value)?;
252            }
253            Ok(py_dict.unbind())
254        } else {
255            Ok(PyDict::new(py).unbind())
256        }
257    }
258
259    #[staticmethod]
260    #[pyo3(name = "from_dict")]
261    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
262        from_dict_pyo3(py, values)
263    }
264
265    #[pyo3(name = "to_dict")]
266    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
267        let dict = PyDict::new(py);
268        dict.set_item("type", stringify!(Commodity))?;
269        dict.set_item("id", self.id.to_string())?;
270        dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
271        dict.set_item("asset_class", self.asset_class.to_string())?;
272        dict.set_item("quote_currency", self.quote_currency.code.to_string())?;
273        dict.set_item("price_precision", self.price_precision)?;
274        dict.set_item("size_precision", self.size_precision)?;
275        dict.set_item("price_increment", self.price_increment.to_string())?;
276        dict.set_item("size_increment", self.size_increment.to_string())?;
277        dict.set_item("ts_event", self.ts_event.as_u64())?;
278        dict.set_item("ts_init", self.ts_init.as_u64())?;
279
280        if let Some(ref info_map) = self.info {
281            let info_dict = PyDict::new(py);
282            for (key, value) in info_map {
283                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
284                let py_value =
285                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
286                info_dict.set_item(key, py_value)?;
287            }
288            dict.set_item("info", info_dict)?;
289        } else {
290            dict.set_item("info", PyDict::new(py))?;
291        }
292        dict.set_item("margin_init", self.margin_init.to_string())?;
293        dict.set_item("margin_maint", self.margin_maint.to_string())?;
294        dict.set_item("maker_fee", self.maker_fee.to_string())?;
295        dict.set_item("taker_fee", self.taker_fee.to_string())?;
296        match self.lot_size {
297            Some(value) => dict.set_item("lot_size", value.to_string())?,
298            None => dict.set_item("lot_size", py.None())?,
299        }
300        match self.max_quantity {
301            Some(value) => dict.set_item("max_quantity", value.to_string())?,
302            None => dict.set_item("max_quantity", py.None())?,
303        }
304        match self.min_quantity {
305            Some(value) => dict.set_item("min_quantity", value.to_string())?,
306            None => dict.set_item("min_quantity", py.None())?,
307        }
308        match self.max_notional {
309            Some(value) => dict.set_item("max_notional", value.to_string())?,
310            None => dict.set_item("max_notional", py.None())?,
311        }
312        match self.min_notional {
313            Some(value) => dict.set_item("min_notional", value.to_string())?,
314            None => dict.set_item("min_notional", py.None())?,
315        }
316        match self.max_price {
317            Some(value) => dict.set_item("max_price", value.to_string())?,
318            None => dict.set_item("max_price", py.None())?,
319        }
320        match self.min_price {
321            Some(value) => dict.set_item("min_price", value.to_string())?,
322            None => dict.set_item("min_price", py.None())?,
323        }
324        Ok(dict.into())
325    }
326}