Skip to main content

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