nautilus_model/python/instruments/
crypto_option.rs1use 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 enums::OptionKind,
30 identifiers::{InstrumentId, Symbol},
31 instruments::CryptoOption,
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 CryptoOption {
39 #[expect(clippy::too_many_arguments)]
41 #[new]
42 #[pyo3(signature = (instrument_id, raw_symbol, underlying, quote_currency, settlement_currency, is_inverse, option_kind, strike_price, 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, tick_scheme=None, info=None))]
43 fn py_new(
44 instrument_id: InstrumentId,
45 raw_symbol: Symbol,
46 underlying: Currency,
47 quote_currency: Currency,
48 settlement_currency: Currency,
49 is_inverse: bool,
50 option_kind: OptionKind,
51 strike_price: Price,
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 tick_scheme: Option<String>,
71 info: Option<Py<PyDict>>,
72 ) -> PyResult<Self> {
73 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(underlying)
84 .quote_currency(quote_currency)
85 .settlement_currency(settlement_currency)
86 .is_inverse(is_inverse)
87 .option_kind(option_kind)
88 .strike_price(strike_price)
89 .activation_ns(activation_ns.into())
90 .expiration_ns(expiration_ns.into())
91 .price_precision(price_precision)
92 .size_precision(size_precision)
93 .price_increment(price_increment)
94 .size_increment(size_increment)
95 .maybe_multiplier(multiplier)
96 .maybe_lot_size(lot_size)
97 .maybe_max_quantity(max_quantity)
98 .maybe_min_quantity(min_quantity)
99 .maybe_max_notional(max_notional)
100 .maybe_min_notional(min_notional)
101 .maybe_max_price(max_price)
102 .maybe_min_price(min_price)
103 .maybe_margin_init(margin_init)
104 .maybe_margin_maint(margin_maint)
105 .maybe_tick_scheme(tick_scheme.map(|name| ustr::Ustr::from(name.as_str())))
106 .maybe_info(info_map)
107 .ts_event(ts_event.into())
108 .ts_init(ts_init.into())
109 .build()
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!(CryptoOption)
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 = "option_kind")]
170 fn py_option_kind(&self) -> OptionKind {
171 self.option_kind
172 }
173
174 #[getter]
175 #[pyo3(name = "strike_price")]
176 fn py_strike_price(&self) -> Price {
177 self.strike_price
178 }
179
180 #[getter]
181 #[pyo3(name = "activation_ns")]
182 fn py_activation_ns(&self) -> u64 {
183 self.activation_ns.as_u64()
184 }
185
186 #[getter]
187 #[pyo3(name = "expiration_ns")]
188 fn py_expiration_ns(&self) -> u64 {
189 self.expiration_ns.as_u64()
190 }
191
192 #[getter]
193 #[pyo3(name = "price_precision")]
194 fn py_price_precision(&self) -> u8 {
195 self.price_precision
196 }
197
198 #[getter]
199 #[pyo3(name = "size_precision")]
200 fn py_size_precision(&self) -> u8 {
201 self.size_precision
202 }
203
204 #[getter]
205 #[pyo3(name = "price_increment")]
206 fn py_price_increment(&self) -> Price {
207 self.price_increment
208 }
209
210 #[getter]
211 #[pyo3(name = "size_increment")]
212 fn py_size_increment(&self) -> Quantity {
213 self.size_increment
214 }
215
216 #[getter]
217 #[pyo3(name = "multiplier")]
218 fn py_multiplier(&self) -> Quantity {
219 self.multiplier
220 }
221
222 #[getter]
223 #[pyo3(name = "lot_size")]
224 fn py_lot_size(&self) -> Quantity {
225 self.lot_size
226 }
227
228 #[getter]
229 #[pyo3(name = "max_quantity")]
230 fn py_max_quantity(&self) -> Option<Quantity> {
231 self.max_quantity
232 }
233
234 #[getter]
235 #[pyo3(name = "min_quantity")]
236 fn py_min_quantity(&self) -> Option<Quantity> {
237 self.min_quantity
238 }
239
240 #[getter]
241 #[pyo3(name = "max_notional")]
242 fn py_max_notional(&self) -> Option<Money> {
243 self.max_notional
244 }
245
246 #[getter]
247 #[pyo3(name = "min_notional")]
248 fn py_min_notional(&self) -> Option<Money> {
249 self.min_notional
250 }
251
252 #[getter]
253 #[pyo3(name = "max_price")]
254 fn py_max_price(&self) -> Option<Price> {
255 self.max_price
256 }
257
258 #[getter]
259 #[pyo3(name = "min_price")]
260 fn py_min_price(&self) -> Option<Price> {
261 self.min_price
262 }
263
264 #[getter]
265 #[pyo3(name = "margin_init")]
266 fn py_margin_init(&self) -> Decimal {
267 self.margin_init
268 }
269
270 #[getter]
271 #[pyo3(name = "margin_maint")]
272 fn py_margin_maint(&self) -> Decimal {
273 self.margin_maint
274 }
275
276 #[getter]
277 #[pyo3(name = "info")]
278 fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
279 if let Some(ref info_map) = self.info {
281 let py_dict = PyDict::new(py);
282
283 for (key, value) in info_map {
284 let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
286 let py_value =
287 PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
288 py_dict.set_item(key, py_value)?;
289 }
290 Ok(py_dict.unbind())
291 } else {
292 Ok(PyDict::new(py).unbind())
293 }
294 }
295
296 #[getter]
297 #[pyo3(name = "ts_event")]
298 fn py_ts_event(&self) -> u64 {
299 self.ts_event.as_u64()
300 }
301
302 #[getter]
303 #[pyo3(name = "ts_init")]
304 fn py_ts_init(&self) -> u64 {
305 self.ts_init.as_u64()
306 }
307
308 #[staticmethod]
309 #[pyo3(name = "from_dict")]
310 fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
311 register_crypto_currencies_from_dict(py, &values, &["underlying"]);
312 crate::python::instruments::from_dict_instrument_pyo3(py, values)
313 }
314
315 #[pyo3(name = "to_dict")]
316 fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
317 let dict = PyDict::new(py);
318 dict.set_item("type", stringify!(CryptoOption))?;
319 dict.set_item("id", self.id.to_string())?;
320 dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
321 dict.set_item("underlying", self.underlying.code.to_string())?;
322 dict.set_item("quote_currency", self.quote_currency.code.to_string())?;
323 dict.set_item(
324 "settlement_currency",
325 self.settlement_currency.code.to_string(),
326 )?;
327 dict.set_item("is_inverse", self.is_inverse)?;
328 dict.set_item("option_kind", self.option_kind.to_string())?;
329 dict.set_item("strike_price", self.strike_price.to_string())?;
330 dict.set_item("activation_ns", self.activation_ns.as_u64())?;
331 dict.set_item("expiration_ns", self.expiration_ns.as_u64())?;
332 dict.set_item("price_precision", self.price_precision)?;
333 dict.set_item("size_precision", self.size_precision)?;
334 dict.set_item("price_increment", self.price_increment.to_string())?;
335 dict.set_item("size_increment", self.size_increment.to_string())?;
336 dict.set_item("multiplier", self.multiplier.to_string())?;
337 dict.set_item("lot_size", self.lot_size.to_string())?;
338 dict.set_item("margin_init", self.margin_init.to_string())?;
339 dict.set_item("margin_maint", self.margin_maint.to_string())?;
340 dict.set_item("ts_event", self.ts_event.as_u64())?;
341 dict.set_item("ts_init", self.ts_init.as_u64())?;
342 if let Some(ref info_map) = self.info {
344 let info_dict = PyDict::new(py);
345
346 for (key, value) in info_map {
347 let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
348 let py_value =
349 PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
350 info_dict.set_item(key, py_value)?;
351 }
352 dict.set_item("info", info_dict)?;
353 } else {
354 dict.set_item("info", PyDict::new(py))?;
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 dict.set_item(
387 "tick_scheme",
388 crate::python::instruments::tick_scheme_to_py(self),
389 )?;
390 Ok(dict.into())
391 }
392}
393
394#[cfg(test)]
395mod tests {
396 use pyo3::{prelude::*, types::PyDict};
397 use rstest::rstest;
398
399 use crate::{
400 enums::CurrencyType,
401 instruments::{CryptoOption, stubs::*},
402 types::Currency,
403 };
404
405 #[rstest]
406 fn test_dict_round_trip(crypto_option_btc_deribit: CryptoOption) {
407 Python::initialize();
408 Python::attach(|py| {
409 let crypto_option = crypto_option_btc_deribit;
410 let values = crypto_option.py_to_dict(py).unwrap();
411 let values: Py<PyDict> = values.extract(py).unwrap();
412 let new_crypto_future = CryptoOption::py_from_dict(py, values).unwrap();
413 assert_eq!(crypto_option, new_crypto_future);
414 });
415 }
416
417 #[rstest]
418 fn test_from_dict_unknown_underlying_registers_as_crypto(
419 crypto_option_btc_deribit: CryptoOption,
420 ) {
421 Python::initialize();
424 Python::attach(|py| {
425 let values = crypto_option_btc_deribit.py_to_dict(py).unwrap();
426 let values: Py<PyDict> = values.extract(py).unwrap();
427 values.bind(py).set_item("underlying", "NEWOPT").unwrap();
428
429 let new_option = CryptoOption::py_from_dict(py, values).unwrap();
430 assert_eq!(new_option.underlying.code, "NEWOPT");
431 assert_eq!(new_option.underlying.precision, 8);
432 assert_eq!(new_option.underlying.currency_type, CurrencyType::Crypto);
433 assert!(Currency::try_from_str("NEWOPT").is_some());
434 });
435 }
436}