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, maker_fee=None, taker_fee=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        maker_fee: Option<Decimal>,
66        taker_fee: 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::new_checked(
78            instrument_id,
79            raw_symbol,
80            base_currency,
81            quote_currency,
82            settlement_currency,
83            is_inverse,
84            price_precision,
85            size_precision,
86            price_increment,
87            size_increment,
88            multiplier,
89            lot_size,
90            max_quantity,
91            min_quantity,
92            max_notional,
93            min_notional,
94            max_price,
95            min_price,
96            margin_init,
97            margin_maint,
98            maker_fee,
99            taker_fee,
100            tick_scheme.map(|name| ustr::Ustr::from(name.as_str())),
101            info_map,
102            ts_event.into(),
103            ts_init.into(),
104        )
105        .map_err(to_pyvalue_err)
106    }
107
108    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
109        match op {
110            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
111            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
112            _ => py.NotImplemented(),
113        }
114    }
115
116    fn __hash__(&self) -> isize {
117        let mut hasher = DefaultHasher::new();
118        self.hash(&mut hasher);
119        hasher.finish() as isize
120    }
121
122    #[getter]
123    fn type_name(&self) -> &'static str {
124        stringify!(CryptoPerpetual)
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 = "base_currency")]
141    fn py_base_currency(&self) -> Currency {
142        self.base_currency
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 = "price_precision")]
165    fn py_price_precision(&self) -> u8 {
166        self.price_precision
167    }
168
169    #[getter]
170    #[pyo3(name = "size_precision")]
171    fn py_size_precision(&self) -> u8 {
172        self.size_precision
173    }
174
175    #[getter]
176    #[pyo3(name = "price_increment")]
177    fn py_price_increment(&self) -> Price {
178        self.price_increment
179    }
180
181    #[getter]
182    #[pyo3(name = "size_increment")]
183    fn py_size_increment(&self) -> Quantity {
184        self.size_increment
185    }
186
187    #[getter]
188    #[pyo3(name = "multiplier")]
189    fn py_multiplier(&self) -> Quantity {
190        self.multiplier
191    }
192
193    #[getter]
194    #[pyo3(name = "lot_size")]
195    fn py_lot_size(&self) -> Quantity {
196        self.lot_size
197    }
198
199    #[getter]
200    #[pyo3(name = "max_quantity")]
201    fn py_max_quantity(&self) -> Option<Quantity> {
202        self.max_quantity
203    }
204
205    #[getter]
206    #[pyo3(name = "min_quantity")]
207    fn py_min_quantity(&self) -> Option<Quantity> {
208        self.min_quantity
209    }
210
211    #[getter]
212    #[pyo3(name = "max_notional")]
213    fn py_max_notional(&self) -> Option<Money> {
214        self.max_notional
215    }
216
217    #[getter]
218    #[pyo3(name = "min_notional")]
219    fn py_min_notional(&self) -> Option<Money> {
220        self.min_notional
221    }
222
223    #[getter]
224    #[pyo3(name = "max_price")]
225    fn py_max_price(&self) -> Option<Price> {
226        self.max_price
227    }
228
229    #[getter]
230    #[pyo3(name = "min_price")]
231    fn py_min_price(&self) -> Option<Price> {
232        self.min_price
233    }
234
235    #[getter]
236    #[pyo3(name = "ts_event")]
237    fn py_ts_event(&self) -> u64 {
238        self.ts_event.as_u64()
239    }
240
241    #[getter]
242    #[pyo3(name = "ts_init")]
243    fn py_ts_init(&self) -> u64 {
244        self.ts_init.as_u64()
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 = "maker_fee")]
261    fn py_maker_fee(&self) -> Decimal {
262        self.maker_fee
263    }
264
265    #[getter]
266    #[pyo3(name = "taker_fee")]
267    fn py_taker_fee(&self) -> Decimal {
268        self.taker_fee
269    }
270
271    #[getter]
272    #[pyo3(name = "info")]
273    fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
274        // Convert HashMap<String, serde_json::Value> back to Python dict
275        if let Some(ref info_map) = self.info {
276            let py_dict = PyDict::new(py);
277
278            for (key, value) in info_map {
279                // Convert serde_json::Value back to Python object via JSON
280                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
281                let py_value =
282                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
283                py_dict.set_item(key, py_value)?;
284            }
285            Ok(py_dict.unbind())
286        } else {
287            Ok(PyDict::new(py).unbind())
288        }
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, &["base_currency"]);
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!(CryptoPerpetual))?;
302        dict.set_item("id", self.id.to_string())?;
303        dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
304        dict.set_item("base_currency", self.base_currency.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("price_precision", self.price_precision)?;
312        dict.set_item("size_precision", self.size_precision)?;
313        dict.set_item("price_increment", self.price_increment.to_string())?;
314        dict.set_item("size_increment", self.size_increment.to_string())?;
315        dict.set_item("maker_fee", self.maker_fee.to_string())?;
316        dict.set_item("taker_fee", self.taker_fee.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        // Serialize info dict
320        if let Some(ref info_map) = self.info {
321            let info_dict = PyDict::new(py);
322
323            for (key, value) in info_map {
324                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
325                let py_value =
326                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
327                info_dict.set_item(key, py_value)?;
328            }
329            dict.set_item("info", info_dict)?;
330        } else {
331            dict.set_item("info", PyDict::new(py))?;
332        }
333        dict.set_item("ts_event", self.ts_event.as_u64())?;
334        dict.set_item("ts_init", self.ts_init.as_u64())?;
335        dict.set_item("multiplier", self.multiplier.to_string())?;
336        dict.set_item("lot_size", self.lot_size.to_string())?;
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::{enums::CurrencyType, instruments::CryptoPerpetual, types::Currency};
380
381    #[rstest]
382    fn test_from_dict_unknown_base_currency_registers_as_crypto() {
383        // Regression: newly listed base assets (e.g. Binance `0GUSDT-PERP`) must not
384        // fail `from_dict` just because the code is absent from the built-in map.
385        Python::initialize();
386        Python::attach(|py| {
387            let dict = PyDict::new(py);
388            dict.set_item("type", "CryptoPerpetual").unwrap();
389            dict.set_item("id", "0GUSDT-PERP.BINANCE").unwrap();
390            dict.set_item("raw_symbol", "0GUSDT").unwrap();
391            dict.set_item("base_currency", "0G").unwrap();
392            dict.set_item("quote_currency", "USDT").unwrap();
393            dict.set_item("settlement_currency", "USDT").unwrap();
394            dict.set_item("is_inverse", false).unwrap();
395            dict.set_item("price_precision", 4).unwrap();
396            dict.set_item("size_precision", 0).unwrap();
397            dict.set_item("price_increment", "0.0001").unwrap();
398            dict.set_item("size_increment", "1").unwrap();
399            dict.set_item("multiplier", "1").unwrap();
400            dict.set_item("lot_size", "1").unwrap();
401            dict.set_item("max_quantity", py.None()).unwrap();
402            dict.set_item("min_quantity", "1").unwrap();
403            dict.set_item("max_notional", py.None()).unwrap();
404            dict.set_item("min_notional", py.None()).unwrap();
405            dict.set_item("max_price", py.None()).unwrap();
406            dict.set_item("min_price", py.None()).unwrap();
407            dict.set_item("margin_init", "0").unwrap();
408            dict.set_item("margin_maint", "0").unwrap();
409            dict.set_item("maker_fee", "0.0002").unwrap();
410            dict.set_item("taker_fee", "0.0004").unwrap();
411            dict.set_item("ts_event", 1_758_067_200_000_000_000u64)
412                .unwrap();
413            dict.set_item("ts_init", 1_758_067_200_000_000_000u64)
414                .unwrap();
415
416            let values: Py<PyDict> = dict.unbind();
417            let perp = CryptoPerpetual::py_from_dict(py, values).unwrap();
418
419            assert_eq!(perp.base_currency.code.as_str(), "0G");
420            assert_eq!(perp.base_currency.precision, 8);
421            assert_eq!(perp.base_currency.currency_type, CurrencyType::Crypto);
422            assert_eq!(perp.quote_currency.code.as_str(), "USDT");
423            assert_eq!(perp.settlement_currency.code.as_str(), "USDT");
424
425            // Side effect: the unknown code is now in the registry for subsequent strict lookups
426            assert!(Currency::try_from_str("0G").is_some());
427        });
428    }
429}