Skip to main content

nautilus_model/python/instruments/
crypto_future.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;
27
28use crate::{
29    identifiers::{InstrumentId, Symbol},
30    instruments::CryptoFuture,
31    python::instruments::register_crypto_currencies_from_dict,
32    types::{Currency, Money, Price, Quantity},
33};
34
35#[pymethods]
36#[pyo3_stub_gen::derive::gen_stub_pymethods]
37impl CryptoFuture {
38    /// Represents a deliverable futures contract instrument, with crypto assets as underlying and for settlement.
39    #[expect(clippy::too_many_arguments)]
40    #[new]
41    #[pyo3(signature = (instrument_id, raw_symbol, underlying, quote_currency, settlement_currency, is_inverse, activation_ns, expiration_ns, price_precision, size_precision, price_increment, size_increment,ts_event, ts_init, multiplier=None, 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, tick_scheme=None, info=None))]
42    fn py_new(
43        instrument_id: InstrumentId,
44        raw_symbol: Symbol,
45        underlying: Currency,
46        quote_currency: Currency,
47        settlement_currency: Currency,
48        is_inverse: bool,
49        activation_ns: u64,
50        expiration_ns: u64,
51        price_precision: u8,
52        size_precision: u8,
53        price_increment: Price,
54        size_increment: Quantity,
55        ts_event: u64,
56        ts_init: u64,
57        multiplier: Option<Quantity>,
58        lot_size: Option<Quantity>,
59        max_quantity: Option<Quantity>,
60        min_quantity: Option<Quantity>,
61        max_notional: Option<Money>,
62        min_notional: Option<Money>,
63        max_price: Option<Price>,
64        min_price: Option<Price>,
65        margin_init: Option<Decimal>,
66        margin_maint: Option<Decimal>,
67        tick_scheme: Option<String>,
68        info: Option<Py<PyDict>>,
69    ) -> PyResult<Self> {
70        // Convert Python dict to Params
71        let info_map = if let Some(info_dict) = info {
72            Python::attach(|py| from_pydict(py, &info_dict))?
73        } else {
74            None
75        };
76
77        Self::builder()
78            .instrument_id(instrument_id)
79            .raw_symbol(raw_symbol)
80            .underlying(underlying)
81            .quote_currency(quote_currency)
82            .settlement_currency(settlement_currency)
83            .is_inverse(is_inverse)
84            .activation_ns(activation_ns.into())
85            .expiration_ns(expiration_ns.into())
86            .price_precision(price_precision)
87            .size_precision(size_precision)
88            .price_increment(price_increment)
89            .size_increment(size_increment)
90            .maybe_multiplier(multiplier)
91            .maybe_lot_size(lot_size)
92            .maybe_max_quantity(max_quantity)
93            .maybe_min_quantity(min_quantity)
94            .maybe_max_notional(max_notional)
95            .maybe_min_notional(min_notional)
96            .maybe_max_price(max_price)
97            .maybe_min_price(min_price)
98            .maybe_margin_init(margin_init)
99            .maybe_margin_maint(margin_maint)
100            .maybe_tick_scheme(tick_scheme.map(|name| ustr::Ustr::from(name.as_str())))
101            .maybe_info(info_map)
102            .ts_event(ts_event.into())
103            .ts_init(ts_init.into())
104            .build()
105            .map_err(to_pyvalue_err)
106    }
107
108    fn __hash__(&self) -> isize {
109        let mut hasher = DefaultHasher::new();
110        self.hash(&mut hasher);
111        hasher.finish() as isize
112    }
113
114    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
115        match op {
116            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
117            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
118            _ => py.NotImplemented(),
119        }
120    }
121
122    #[getter]
123    fn type_name(&self) -> &'static str {
124        stringify!(CryptoFuture)
125    }
126
127    #[getter]
128    #[pyo3(name = "id")]
129    fn py_id(&self) -> InstrumentId {
130        self.id
131    }
132
133    #[getter]
134    #[pyo3(name = "raw_symbol")]
135    fn py_raw_symbol(&self) -> Symbol {
136        self.raw_symbol
137    }
138
139    #[getter]
140    #[pyo3(name = "underlying")]
141    fn py_underlying(&self) -> Currency {
142        self.underlying
143    }
144
145    #[getter]
146    #[pyo3(name = "quote_currency")]
147    fn py_quote_currency(&self) -> Currency {
148        self.quote_currency
149    }
150
151    #[getter]
152    #[pyo3(name = "settlement_currency")]
153    fn py_settlement_currency(&self) -> Currency {
154        self.settlement_currency
155    }
156
157    #[getter]
158    #[pyo3(name = "is_inverse")]
159    fn py_is_inverse(&self) -> bool {
160        self.is_inverse
161    }
162
163    #[getter]
164    #[pyo3(name = "activation_ns")]
165    fn py_activation_ns(&self) -> u64 {
166        self.activation_ns.as_u64()
167    }
168
169    #[getter]
170    #[pyo3(name = "expiration_ns")]
171    fn py_expiration_ns(&self) -> u64 {
172        self.expiration_ns.as_u64()
173    }
174
175    #[getter]
176    #[pyo3(name = "price_precision")]
177    fn py_price_precision(&self) -> u8 {
178        self.price_precision
179    }
180
181    #[getter]
182    #[pyo3(name = "size_precision")]
183    fn py_size_precision(&self) -> u8 {
184        self.size_precision
185    }
186
187    #[getter]
188    #[pyo3(name = "price_increment")]
189    fn py_price_increment(&self) -> Price {
190        self.price_increment
191    }
192
193    #[getter]
194    #[pyo3(name = "size_increment")]
195    fn py_size_increment(&self) -> Quantity {
196        self.size_increment
197    }
198
199    #[getter]
200    #[pyo3(name = "multiplier")]
201    fn py_multiplier(&self) -> Quantity {
202        self.multiplier
203    }
204
205    #[getter]
206    #[pyo3(name = "lot_size")]
207    fn py_lot_size(&self) -> Quantity {
208        self.lot_size
209    }
210
211    #[getter]
212    #[pyo3(name = "max_quantity")]
213    fn py_max_quantity(&self) -> Option<Quantity> {
214        self.max_quantity
215    }
216
217    #[getter]
218    #[pyo3(name = "min_quantity")]
219    fn py_min_quantity(&self) -> Option<Quantity> {
220        self.min_quantity
221    }
222
223    #[getter]
224    #[pyo3(name = "max_notional")]
225    fn py_max_notional(&self) -> Option<Money> {
226        self.max_notional
227    }
228
229    #[getter]
230    #[pyo3(name = "min_notional")]
231    fn py_min_notional(&self) -> Option<Money> {
232        self.min_notional
233    }
234
235    #[getter]
236    #[pyo3(name = "max_price")]
237    fn py_max_price(&self) -> Option<Price> {
238        self.max_price
239    }
240
241    #[getter]
242    #[pyo3(name = "min_price")]
243    fn py_min_price(&self) -> Option<Price> {
244        self.min_price
245    }
246
247    #[getter]
248    #[pyo3(name = "margin_init")]
249    fn py_margin_init(&self) -> Decimal {
250        self.margin_init
251    }
252
253    #[getter]
254    #[pyo3(name = "margin_maint")]
255    fn py_margin_maint(&self) -> Decimal {
256        self.margin_maint
257    }
258
259    #[getter]
260    #[pyo3(name = "info")]
261    fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
262        // Convert HashMap<String, serde_json::Value> back to Python dict
263        if let Some(ref info_map) = self.info {
264            let py_dict = PyDict::new(py);
265
266            for (key, value) in info_map {
267                // Convert serde_json::Value back to Python object via JSON
268                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
269                let py_value =
270                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
271                py_dict.set_item(key, py_value)?;
272            }
273            Ok(py_dict.unbind())
274        } else {
275            Ok(PyDict::new(py).unbind())
276        }
277    }
278
279    #[getter]
280    #[pyo3(name = "ts_event")]
281    fn py_ts_event(&self) -> u64 {
282        self.ts_event.as_u64()
283    }
284
285    #[getter]
286    #[pyo3(name = "ts_init")]
287    fn py_ts_init(&self) -> u64 {
288        self.ts_init.as_u64()
289    }
290
291    #[staticmethod]
292    #[pyo3(name = "from_dict")]
293    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
294        register_crypto_currencies_from_dict(py, &values, &["underlying"]);
295        crate::python::instruments::from_dict_instrument_pyo3(py, values)
296    }
297
298    #[pyo3(name = "to_dict")]
299    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
300        let dict = PyDict::new(py);
301        dict.set_item("type", stringify!(CryptoFuture))?;
302        dict.set_item("id", self.id.to_string())?;
303        dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
304        dict.set_item("underlying", self.underlying.code.to_string())?;
305        dict.set_item("quote_currency", self.quote_currency.code.to_string())?;
306        dict.set_item(
307            "settlement_currency",
308            self.settlement_currency.code.to_string(),
309        )?;
310        dict.set_item("is_inverse", self.is_inverse)?;
311        dict.set_item("activation_ns", self.activation_ns.as_u64())?;
312        dict.set_item("expiration_ns", self.expiration_ns.as_u64())?;
313        dict.set_item("price_precision", self.price_precision)?;
314        dict.set_item("size_precision", self.size_precision)?;
315        dict.set_item("price_increment", self.price_increment.to_string())?;
316        dict.set_item("size_increment", self.size_increment.to_string())?;
317        dict.set_item("margin_init", self.margin_init.to_string())?;
318        dict.set_item("margin_maint", self.margin_maint.to_string())?;
319        dict.set_item("multiplier", self.multiplier.to_string())?;
320        dict.set_item("lot_size", self.lot_size.to_string())?;
321        // Serialize info dict
322        if let Some(ref info_map) = self.info {
323            let info_dict = PyDict::new(py);
324
325            for (key, value) in info_map {
326                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
327                let py_value =
328                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
329                info_dict.set_item(key, py_value)?;
330            }
331            dict.set_item("info", info_dict)?;
332        } else {
333            dict.set_item("info", PyDict::new(py))?;
334        }
335        dict.set_item("ts_event", self.ts_event.as_u64())?;
336        dict.set_item("ts_init", self.ts_init.as_u64())?;
337        match self.max_quantity {
338            Some(value) => dict.set_item("max_quantity", value.to_string())?,
339            None => dict.set_item("max_quantity", py.None())?,
340        }
341
342        match self.min_quantity {
343            Some(value) => dict.set_item("min_quantity", value.to_string())?,
344            None => dict.set_item("min_quantity", py.None())?,
345        }
346
347        match self.max_notional {
348            Some(value) => dict.set_item("max_notional", value.to_string())?,
349            None => dict.set_item("max_notional", py.None())?,
350        }
351
352        match self.min_notional {
353            Some(value) => dict.set_item("min_notional", value.to_string())?,
354            None => dict.set_item("min_notional", py.None())?,
355        }
356
357        match self.max_price {
358            Some(value) => dict.set_item("max_price", value.to_string())?,
359            None => dict.set_item("max_price", py.None())?,
360        }
361
362        match self.min_price {
363            Some(value) => dict.set_item("min_price", value.to_string())?,
364            None => dict.set_item("min_price", py.None())?,
365        }
366        dict.set_item(
367            "tick_scheme",
368            crate::python::instruments::tick_scheme_to_py(self),
369        )?;
370        Ok(dict.into())
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use pyo3::{prelude::*, types::PyDict};
377    use rstest::rstest;
378
379    use crate::{
380        enums::CurrencyType,
381        instruments::{CryptoFuture, stubs::*},
382        types::Currency,
383    };
384
385    #[rstest]
386    fn test_dict_round_trip(crypto_future_btcusdt: CryptoFuture) {
387        Python::initialize();
388        Python::attach(|py| {
389            let crypto_future = crypto_future_btcusdt;
390            let values = crypto_future.py_to_dict(py).unwrap();
391            let values: Py<PyDict> = values.extract(py).unwrap();
392            let new_crypto_future = CryptoFuture::py_from_dict(py, values).unwrap();
393            assert_eq!(crypto_future, new_crypto_future);
394        });
395    }
396
397    #[rstest]
398    fn test_from_dict_unknown_underlying_registers_as_crypto(crypto_future_btcusdt: CryptoFuture) {
399        // Regression: newly listed underlyings must round-trip through `from_dict`
400        // without requiring prior registration of the currency in the Rust map.
401        Python::initialize();
402        Python::attach(|py| {
403            let values = crypto_future_btcusdt.py_to_dict(py).unwrap();
404            let values: Py<PyDict> = values.extract(py).unwrap();
405            values.bind(py).set_item("underlying", "NEWFUT").unwrap();
406
407            let new_future = CryptoFuture::py_from_dict(py, values).unwrap();
408            assert_eq!(new_future.underlying.code, "NEWFUT");
409            assert_eq!(new_future.underlying.precision, 8);
410            assert_eq!(new_future.underlying.currency_type, CurrencyType::Crypto);
411            assert!(Currency::try_from_str("NEWFUT").is_some());
412        });
413    }
414}