Skip to main content

nautilus_model/python/instruments/
crypto_option_spread.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    identifiers::{InstrumentId, Symbol},
31    instruments::CryptoOptionSpread,
32    python::instruments::register_crypto_currencies_from_dict,
33    types::{Currency, Money, Price, Quantity},
34};
35
36#[pymethods]
37#[pyo3_stub_gen::derive::gen_stub_pymethods]
38impl CryptoOptionSpread {
39    /// Represents a crypto option spread instrument, with crypto assets as underlying and for
40    /// settlement.
41    #[expect(clippy::too_many_arguments)]
42    #[new]
43    #[pyo3(signature = (instrument_id, raw_symbol, underlying, quote_currency, settlement_currency, is_inverse, strategy_type, 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, maker_fee=None, taker_fee=None, info=None))]
44    fn py_new(
45        instrument_id: InstrumentId,
46        raw_symbol: Symbol,
47        underlying: Currency,
48        quote_currency: Currency,
49        settlement_currency: Currency,
50        is_inverse: bool,
51        strategy_type: &str,
52        activation_ns: u64,
53        expiration_ns: u64,
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        multiplier: Option<Quantity>,
61        lot_size: Option<Quantity>,
62        max_quantity: Option<Quantity>,
63        min_quantity: Option<Quantity>,
64        max_notional: Option<Money>,
65        min_notional: Option<Money>,
66        max_price: Option<Price>,
67        min_price: Option<Price>,
68        margin_init: Option<Decimal>,
69        margin_maint: Option<Decimal>,
70        maker_fee: Option<Decimal>,
71        taker_fee: Option<Decimal>,
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::new_checked(
81            instrument_id,
82            raw_symbol,
83            underlying,
84            quote_currency,
85            settlement_currency,
86            is_inverse,
87            Ustr::from(strategy_type),
88            activation_ns.into(),
89            expiration_ns.into(),
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 __hash__(&self) -> isize {
114        let mut hasher = DefaultHasher::new();
115        self.hash(&mut hasher);
116        hasher.finish() as isize
117    }
118
119    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
120        match op {
121            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
122            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
123            _ => py.NotImplemented(),
124        }
125    }
126
127    #[getter]
128    fn type_name(&self) -> &'static str {
129        stringify!(CryptoOptionSpread)
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) -> Currency {
147        self.underlying
148    }
149
150    #[getter]
151    #[pyo3(name = "quote_currency")]
152    fn py_quote_currency(&self) -> Currency {
153        self.quote_currency
154    }
155
156    #[getter]
157    #[pyo3(name = "settlement_currency")]
158    fn py_settlement_currency(&self) -> Currency {
159        self.settlement_currency
160    }
161
162    #[getter]
163    #[pyo3(name = "is_inverse")]
164    fn py_is_inverse(&self) -> bool {
165        self.is_inverse
166    }
167
168    #[getter]
169    #[pyo3(name = "strategy_type")]
170    fn py_strategy_type(&self) -> String {
171        self.strategy_type.to_string()
172    }
173
174    #[getter]
175    #[pyo3(name = "activation_ns")]
176    fn py_activation_ns(&self) -> u64 {
177        self.activation_ns.as_u64()
178    }
179
180    #[getter]
181    #[pyo3(name = "expiration_ns")]
182    fn py_expiration_ns(&self) -> u64 {
183        self.expiration_ns.as_u64()
184    }
185
186    #[getter]
187    #[pyo3(name = "price_precision")]
188    fn py_price_precision(&self) -> u8 {
189        self.price_precision
190    }
191
192    #[getter]
193    #[pyo3(name = "size_precision")]
194    fn py_size_precision(&self) -> u8 {
195        self.size_precision
196    }
197
198    #[getter]
199    #[pyo3(name = "price_increment")]
200    fn py_price_increment(&self) -> Price {
201        self.price_increment
202    }
203
204    #[getter]
205    #[pyo3(name = "size_increment")]
206    fn py_size_increment(&self) -> Quantity {
207        self.size_increment
208    }
209
210    #[getter]
211    #[pyo3(name = "multiplier")]
212    fn py_multiplier(&self) -> Quantity {
213        self.multiplier
214    }
215
216    #[getter]
217    #[pyo3(name = "lot_size")]
218    fn py_lot_size(&self) -> Quantity {
219        self.lot_size
220    }
221
222    #[getter]
223    #[pyo3(name = "max_quantity")]
224    fn py_max_quantity(&self) -> Option<Quantity> {
225        self.max_quantity
226    }
227
228    #[getter]
229    #[pyo3(name = "min_quantity")]
230    fn py_min_quantity(&self) -> Option<Quantity> {
231        self.min_quantity
232    }
233
234    #[getter]
235    #[pyo3(name = "max_notional")]
236    fn py_max_notional(&self) -> Option<Money> {
237        self.max_notional
238    }
239
240    #[getter]
241    #[pyo3(name = "min_notional")]
242    fn py_min_notional(&self) -> Option<Money> {
243        self.min_notional
244    }
245
246    #[getter]
247    #[pyo3(name = "max_price")]
248    fn py_max_price(&self) -> Option<Price> {
249        self.max_price
250    }
251
252    #[getter]
253    #[pyo3(name = "min_price")]
254    fn py_min_price(&self) -> Option<Price> {
255        self.min_price
256    }
257
258    #[getter]
259    #[pyo3(name = "margin_init")]
260    fn py_margin_init(&self) -> Decimal {
261        self.margin_init
262    }
263
264    #[getter]
265    #[pyo3(name = "margin_maint")]
266    fn py_margin_maint(&self) -> Decimal {
267        self.margin_maint
268    }
269
270    #[getter]
271    #[pyo3(name = "maker_fee")]
272    fn py_maker_fee(&self) -> Decimal {
273        self.maker_fee
274    }
275
276    #[getter]
277    #[pyo3(name = "taker_fee")]
278    fn py_taker_fee(&self) -> Decimal {
279        self.taker_fee
280    }
281
282    #[getter]
283    #[pyo3(name = "info")]
284    fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
285        if let Some(ref info_map) = self.info {
286            let py_dict = PyDict::new(py);
287
288            for (key, value) in info_map {
289                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
290                let py_value =
291                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
292                py_dict.set_item(key, py_value)?;
293            }
294            Ok(py_dict.unbind())
295        } else {
296            Ok(PyDict::new(py).unbind())
297        }
298    }
299
300    #[getter]
301    #[pyo3(name = "ts_event")]
302    fn py_ts_event(&self) -> u64 {
303        self.ts_event.as_u64()
304    }
305
306    #[getter]
307    #[pyo3(name = "ts_init")]
308    fn py_ts_init(&self) -> u64 {
309        self.ts_init.as_u64()
310    }
311
312    #[staticmethod]
313    #[pyo3(name = "from_dict")]
314    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
315        register_crypto_currencies_from_dict(py, &values, &["underlying"]);
316        from_dict_pyo3(py, values)
317    }
318
319    #[pyo3(name = "to_dict")]
320    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
321        let dict = PyDict::new(py);
322        dict.set_item("type", stringify!(CryptoOptionSpread))?;
323        dict.set_item("id", self.id.to_string())?;
324        dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
325        dict.set_item("underlying", self.underlying.code.to_string())?;
326        dict.set_item("quote_currency", self.quote_currency.code.to_string())?;
327        dict.set_item(
328            "settlement_currency",
329            self.settlement_currency.code.to_string(),
330        )?;
331        dict.set_item("is_inverse", self.is_inverse)?;
332        dict.set_item("strategy_type", self.strategy_type.to_string())?;
333        dict.set_item("activation_ns", self.activation_ns.as_u64())?;
334        dict.set_item("expiration_ns", self.expiration_ns.as_u64())?;
335        dict.set_item("price_precision", self.price_precision)?;
336        dict.set_item("size_precision", self.size_precision)?;
337        dict.set_item("price_increment", self.price_increment.to_string())?;
338        dict.set_item("size_increment", self.size_increment.to_string())?;
339        dict.set_item("multiplier", self.multiplier.to_string())?;
340        dict.set_item("lot_size", self.lot_size.to_string())?;
341        dict.set_item("margin_init", self.margin_init.to_string())?;
342        dict.set_item("margin_maint", self.margin_maint.to_string())?;
343        dict.set_item("maker_fee", self.maker_fee.to_string())?;
344        dict.set_item("taker_fee", self.taker_fee.to_string())?;
345        dict.set_item("ts_event", self.ts_event.as_u64())?;
346        dict.set_item("ts_init", self.ts_init.as_u64())?;
347
348        if let Some(ref info_map) = self.info {
349            let info_dict = PyDict::new(py);
350
351            for (key, value) in info_map {
352                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
353                let py_value =
354                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
355                info_dict.set_item(key, py_value)?;
356            }
357            dict.set_item("info", info_dict)?;
358        } else {
359            dict.set_item("info", PyDict::new(py))?;
360        }
361
362        match self.max_quantity {
363            Some(value) => dict.set_item("max_quantity", value.to_string())?,
364            None => dict.set_item("max_quantity", py.None())?,
365        }
366
367        match self.min_quantity {
368            Some(value) => dict.set_item("min_quantity", value.to_string())?,
369            None => dict.set_item("min_quantity", py.None())?,
370        }
371
372        match self.max_notional {
373            Some(value) => dict.set_item("max_notional", value.to_string())?,
374            None => dict.set_item("max_notional", py.None())?,
375        }
376
377        match self.min_notional {
378            Some(value) => dict.set_item("min_notional", value.to_string())?,
379            None => dict.set_item("min_notional", py.None())?,
380        }
381
382        match self.max_price {
383            Some(value) => dict.set_item("max_price", value.to_string())?,
384            None => dict.set_item("max_price", py.None())?,
385        }
386
387        match self.min_price {
388            Some(value) => dict.set_item("min_price", value.to_string())?,
389            None => dict.set_item("min_price", py.None())?,
390        }
391        Ok(dict.into())
392    }
393}
394
395#[cfg(test)]
396mod tests {
397    use pyo3::{prelude::*, types::PyDict};
398    use rstest::rstest;
399
400    use crate::instruments::{CryptoOptionSpread, stubs::*};
401
402    #[rstest]
403    fn test_dict_round_trip(crypto_option_spread_btc_deribit: CryptoOptionSpread) {
404        Python::initialize();
405        Python::attach(|py| {
406            let original = crypto_option_spread_btc_deribit;
407            let values = original.py_to_dict(py).unwrap();
408            let values: Py<PyDict> = values.extract(py).unwrap();
409            let restored = CryptoOptionSpread::py_from_dict(py, values).unwrap();
410            assert_eq!(original, restored);
411        });
412    }
413}