Skip to main content

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