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, 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, tick_scheme=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        tick_scheme: Option<String>,
72        info: Option<Py<PyDict>>,
73    ) -> PyResult<Self> {
74        let info_map = if let Some(info_dict) = info {
75            Python::attach(|py| from_pydict(py, &info_dict))?
76        } else {
77            None
78        };
79
80        Self::builder()
81            .instrument_id(instrument_id)
82            .raw_symbol(raw_symbol)
83            .underlying(Ustr::from(underlying))
84            .asset_class(asset_class)
85            .maybe_base_currency(base_currency)
86            .quote_currency(quote_currency)
87            .settlement_currency(settlement_currency)
88            .is_inverse(is_inverse)
89            .price_precision(price_precision)
90            .size_precision(size_precision)
91            .price_increment(price_increment)
92            .size_increment(size_increment)
93            .maybe_multiplier(multiplier)
94            .maybe_lot_size(lot_size)
95            .maybe_max_quantity(max_quantity)
96            .maybe_min_quantity(min_quantity)
97            .maybe_max_notional(max_notional)
98            .maybe_min_notional(min_notional)
99            .maybe_max_price(max_price)
100            .maybe_min_price(min_price)
101            .maybe_margin_init(margin_init)
102            .maybe_margin_maint(margin_maint)
103            .maybe_tick_scheme(tick_scheme.map(|name| ustr::Ustr::from(name.as_str())))
104            .maybe_info(info_map)
105            .ts_event(ts_event.into())
106            .ts_init(ts_init.into())
107            .build()
108            .map_err(to_pyvalue_err)
109    }
110
111    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
112        match op {
113            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
114            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
115            _ => py.NotImplemented(),
116        }
117    }
118
119    fn __hash__(&self) -> isize {
120        let mut hasher = DefaultHasher::new();
121        self.hash(&mut hasher);
122        hasher.finish() as isize
123    }
124
125    #[getter]
126    fn type_name(&self) -> &'static str {
127        stringify!(PerpetualContract)
128    }
129
130    #[getter]
131    #[pyo3(name = "id")]
132    fn py_id(&self) -> InstrumentId {
133        self.id
134    }
135
136    #[getter]
137    #[pyo3(name = "raw_symbol")]
138    fn py_raw_symbol(&self) -> Symbol {
139        self.raw_symbol
140    }
141
142    #[getter]
143    #[pyo3(name = "underlying")]
144    fn py_underlying(&self) -> &str {
145        self.underlying.as_str()
146    }
147
148    #[getter]
149    #[pyo3(name = "asset_class")]
150    fn py_asset_class(&self) -> AssetClass {
151        self.asset_class
152    }
153
154    #[getter]
155    #[pyo3(name = "base_currency")]
156    fn py_base_currency(&self) -> Option<Currency> {
157        self.base_currency
158    }
159
160    #[getter]
161    #[pyo3(name = "quote_currency")]
162    fn py_quote_currency(&self) -> Currency {
163        self.quote_currency
164    }
165
166    #[getter]
167    #[pyo3(name = "settlement_currency")]
168    fn py_settlement_currency(&self) -> Currency {
169        self.settlement_currency
170    }
171
172    #[getter]
173    #[pyo3(name = "is_inverse")]
174    fn py_is_inverse(&self) -> bool {
175        self.is_inverse
176    }
177
178    #[getter]
179    #[pyo3(name = "price_precision")]
180    fn py_price_precision(&self) -> u8 {
181        self.price_precision
182    }
183
184    #[getter]
185    #[pyo3(name = "size_precision")]
186    fn py_size_precision(&self) -> u8 {
187        self.size_precision
188    }
189
190    #[getter]
191    #[pyo3(name = "price_increment")]
192    fn py_price_increment(&self) -> Price {
193        self.price_increment
194    }
195
196    #[getter]
197    #[pyo3(name = "size_increment")]
198    fn py_size_increment(&self) -> Quantity {
199        self.size_increment
200    }
201
202    #[getter]
203    #[pyo3(name = "multiplier")]
204    fn py_multiplier(&self) -> Quantity {
205        self.multiplier
206    }
207
208    #[getter]
209    #[pyo3(name = "lot_size")]
210    fn py_lot_size(&self) -> Quantity {
211        self.lot_size
212    }
213
214    #[getter]
215    #[pyo3(name = "max_quantity")]
216    fn py_max_quantity(&self) -> Option<Quantity> {
217        self.max_quantity
218    }
219
220    #[getter]
221    #[pyo3(name = "min_quantity")]
222    fn py_min_quantity(&self) -> Option<Quantity> {
223        self.min_quantity
224    }
225
226    #[getter]
227    #[pyo3(name = "max_notional")]
228    fn py_max_notional(&self) -> Option<Money> {
229        self.max_notional
230    }
231
232    #[getter]
233    #[pyo3(name = "min_notional")]
234    fn py_min_notional(&self) -> Option<Money> {
235        self.min_notional
236    }
237
238    #[getter]
239    #[pyo3(name = "max_price")]
240    fn py_max_price(&self) -> Option<Price> {
241        self.max_price
242    }
243
244    #[getter]
245    #[pyo3(name = "min_price")]
246    fn py_min_price(&self) -> Option<Price> {
247        self.min_price
248    }
249
250    #[getter]
251    #[pyo3(name = "margin_init")]
252    fn py_margin_init(&self) -> Decimal {
253        self.margin_init
254    }
255
256    #[getter]
257    #[pyo3(name = "margin_maint")]
258    fn py_margin_maint(&self) -> Decimal {
259        self.margin_maint
260    }
261
262    #[getter]
263    #[pyo3(name = "ts_event")]
264    fn py_ts_event(&self) -> u64 {
265        self.ts_event.as_u64()
266    }
267
268    #[getter]
269    #[pyo3(name = "ts_init")]
270    fn py_ts_init(&self) -> u64 {
271        self.ts_init.as_u64()
272    }
273
274    #[getter]
275    #[pyo3(name = "info")]
276    fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
277        if let Some(ref info_map) = self.info {
278            let py_dict = PyDict::new(py);
279
280            for (key, value) in info_map {
281                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
282                let py_value =
283                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
284                py_dict.set_item(key, py_value)?;
285            }
286            Ok(py_dict.unbind())
287        } else {
288            Ok(PyDict::new(py).unbind())
289        }
290    }
291
292    #[staticmethod]
293    #[pyo3(name = "from_dict")]
294    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
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!(PerpetualContract))?;
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.to_string())?;
305        dict.set_item("asset_class", self.asset_class.to_string())?;
306        dict.set_item("quote_currency", self.quote_currency.code.to_string())?;
307        dict.set_item(
308            "settlement_currency",
309            self.settlement_currency.code.to_string(),
310        )?;
311        dict.set_item("is_inverse", self.is_inverse)?;
312        dict.set_item("price_precision", self.price_precision)?;
313        dict.set_item("size_precision", self.size_precision)?;
314        dict.set_item("price_increment", self.price_increment.to_string())?;
315        dict.set_item("size_increment", self.size_increment.to_string())?;
316        dict.set_item("multiplier", self.multiplier.to_string())?;
317        dict.set_item("lot_size", self.lot_size.to_string())?;
318        dict.set_item("margin_init", self.margin_init.to_string())?;
319        dict.set_item("margin_maint", self.margin_maint.to_string())?;
320
321        if let Some(ref info_map) = self.info {
322            let info_dict = PyDict::new(py);
323
324            for (key, value) in info_map {
325                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
326                let py_value =
327                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
328                info_dict.set_item(key, py_value)?;
329            }
330            dict.set_item("info", info_dict)?;
331        } else {
332            dict.set_item("info", PyDict::new(py))?;
333        }
334        dict.set_item("ts_event", self.ts_event.as_u64())?;
335        dict.set_item("ts_init", self.ts_init.as_u64())?;
336        match self.base_currency {
337            Some(value) => dict.set_item("base_currency", value.code.to_string())?,
338            None => dict.set_item("base_currency", py.None())?,
339        }
340
341        match self.max_quantity {
342            Some(value) => dict.set_item("max_quantity", value.to_string())?,
343            None => dict.set_item("max_quantity", py.None())?,
344        }
345
346        match self.min_quantity {
347            Some(value) => dict.set_item("min_quantity", value.to_string())?,
348            None => dict.set_item("min_quantity", py.None())?,
349        }
350
351        match self.max_notional {
352            Some(value) => dict.set_item("max_notional", value.to_string())?,
353            None => dict.set_item("max_notional", py.None())?,
354        }
355
356        match self.min_notional {
357            Some(value) => dict.set_item("min_notional", value.to_string())?,
358            None => dict.set_item("min_notional", py.None())?,
359        }
360
361        match self.max_price {
362            Some(value) => dict.set_item("max_price", value.to_string())?,
363            None => dict.set_item("max_price", py.None())?,
364        }
365
366        match self.min_price {
367            Some(value) => dict.set_item("min_price", value.to_string())?,
368            None => dict.set_item("min_price", py.None())?,
369        }
370        dict.set_item(
371            "tick_scheme",
372            crate::python::instruments::tick_scheme_to_py(self),
373        )?;
374        Ok(dict.into())
375    }
376}