Skip to main content

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