1use 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, maker_fee=None, taker_fee=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 maker_fee: Option<Decimal>,
71 taker_fee: Option<Decimal>,
72 tick_scheme: Option<String>,
73 info: Option<Py<PyDict>>,
74 ) -> PyResult<Self> {
75 let info_map = if let Some(info_dict) = info {
77 Python::attach(|py| from_pydict(py, &info_dict))?
78 } else {
79 None
80 };
81
82 Self::new_checked(
83 instrument_id,
84 raw_symbol,
85 underlying,
86 quote_currency,
87 settlement_currency,
88 is_inverse,
89 option_kind,
90 strike_price,
91 activation_ns.into(),
92 expiration_ns.into(),
93 price_precision,
94 size_precision,
95 price_increment,
96 size_increment,
97 multiplier,
98 lot_size,
99 max_quantity,
100 min_quantity,
101 max_notional,
102 min_notional,
103 max_price,
104 min_price,
105 margin_init,
106 margin_maint,
107 maker_fee,
108 taker_fee,
109 tick_scheme.map(|name| ustr::Ustr::from(name.as_str())),
110 info_map,
111 ts_event.into(),
112 ts_init.into(),
113 )
114 .map_err(to_pyvalue_err)
115 }
116
117 fn __hash__(&self) -> isize {
118 let mut hasher = DefaultHasher::new();
119 self.hash(&mut hasher);
120 hasher.finish() as isize
121 }
122
123 fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
124 match op {
125 CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
126 CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
127 _ => py.NotImplemented(),
128 }
129 }
130
131 #[getter]
132 fn type_name(&self) -> &'static str {
133 stringify!(CryptoOption)
134 }
135
136 #[getter]
137 #[pyo3(name = "id")]
138 fn py_id(&self) -> InstrumentId {
139 self.id
140 }
141
142 #[getter]
143 #[pyo3(name = "raw_symbol")]
144 fn py_raw_symbol(&self) -> Symbol {
145 self.raw_symbol
146 }
147
148 #[getter]
149 #[pyo3(name = "underlying")]
150 fn py_underlying(&self) -> Currency {
151 self.underlying
152 }
153
154 #[getter]
155 #[pyo3(name = "quote_currency")]
156 fn py_quote_currency(&self) -> Currency {
157 self.quote_currency
158 }
159
160 #[getter]
161 #[pyo3(name = "settlement_currency")]
162 fn py_settlement_currency(&self) -> Currency {
163 self.settlement_currency
164 }
165
166 #[getter]
167 #[pyo3(name = "is_inverse")]
168 fn py_is_inverse(&self) -> bool {
169 self.is_inverse
170 }
171
172 #[getter]
173 #[pyo3(name = "option_kind")]
174 fn py_option_kind(&self) -> OptionKind {
175 self.option_kind
176 }
177
178 #[getter]
179 #[pyo3(name = "strike_price")]
180 fn py_strike_price(&self) -> Price {
181 self.strike_price
182 }
183
184 #[getter]
185 #[pyo3(name = "activation_ns")]
186 fn py_activation_ns(&self) -> u64 {
187 self.activation_ns.as_u64()
188 }
189
190 #[getter]
191 #[pyo3(name = "expiration_ns")]
192 fn py_expiration_ns(&self) -> u64 {
193 self.expiration_ns.as_u64()
194 }
195
196 #[getter]
197 #[pyo3(name = "price_precision")]
198 fn py_price_precision(&self) -> u8 {
199 self.price_precision
200 }
201
202 #[getter]
203 #[pyo3(name = "size_precision")]
204 fn py_size_precision(&self) -> u8 {
205 self.size_precision
206 }
207
208 #[getter]
209 #[pyo3(name = "price_increment")]
210 fn py_price_increment(&self) -> Price {
211 self.price_increment
212 }
213
214 #[getter]
215 #[pyo3(name = "size_increment")]
216 fn py_size_increment(&self) -> Quantity {
217 self.size_increment
218 }
219
220 #[getter]
221 #[pyo3(name = "multiplier")]
222 fn py_multiplier(&self) -> Quantity {
223 self.multiplier
224 }
225
226 #[getter]
227 #[pyo3(name = "lot_size")]
228 fn py_lot_size(&self) -> Quantity {
229 self.lot_size
230 }
231
232 #[getter]
233 #[pyo3(name = "max_quantity")]
234 fn py_max_quantity(&self) -> Option<Quantity> {
235 self.max_quantity
236 }
237
238 #[getter]
239 #[pyo3(name = "min_quantity")]
240 fn py_min_quantity(&self) -> Option<Quantity> {
241 self.min_quantity
242 }
243
244 #[getter]
245 #[pyo3(name = "max_notional")]
246 fn py_max_notional(&self) -> Option<Money> {
247 self.max_notional
248 }
249
250 #[getter]
251 #[pyo3(name = "min_notional")]
252 fn py_min_notional(&self) -> Option<Money> {
253 self.min_notional
254 }
255
256 #[getter]
257 #[pyo3(name = "max_price")]
258 fn py_max_price(&self) -> Option<Price> {
259 self.max_price
260 }
261
262 #[getter]
263 #[pyo3(name = "min_price")]
264 fn py_min_price(&self) -> Option<Price> {
265 self.min_price
266 }
267
268 #[getter]
269 #[pyo3(name = "margin_init")]
270 fn py_margin_init(&self) -> Decimal {
271 self.margin_init
272 }
273
274 #[getter]
275 #[pyo3(name = "margin_maint")]
276 fn py_margin_maint(&self) -> Decimal {
277 self.margin_maint
278 }
279
280 #[getter]
281 #[pyo3(name = "maker_fee")]
282 fn py_maker_fee(&self) -> Decimal {
283 self.maker_fee
284 }
285
286 #[getter]
287 #[pyo3(name = "taker_fee")]
288 fn py_taker_fee(&self) -> Decimal {
289 self.taker_fee
290 }
291
292 #[getter]
293 #[pyo3(name = "info")]
294 fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
295 if let Some(ref info_map) = self.info {
297 let py_dict = PyDict::new(py);
298
299 for (key, value) in info_map {
300 let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
302 let py_value =
303 PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
304 py_dict.set_item(key, py_value)?;
305 }
306 Ok(py_dict.unbind())
307 } else {
308 Ok(PyDict::new(py).unbind())
309 }
310 }
311
312 #[getter]
313 #[pyo3(name = "ts_event")]
314 fn py_ts_event(&self) -> u64 {
315 self.ts_event.as_u64()
316 }
317
318 #[getter]
319 #[pyo3(name = "ts_init")]
320 fn py_ts_init(&self) -> u64 {
321 self.ts_init.as_u64()
322 }
323
324 #[staticmethod]
325 #[pyo3(name = "from_dict")]
326 fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
327 register_crypto_currencies_from_dict(py, &values, &["underlying"]);
328 crate::python::instruments::from_dict_instrument_pyo3(py, values)
329 }
330
331 #[pyo3(name = "to_dict")]
332 fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
333 let dict = PyDict::new(py);
334 dict.set_item("type", stringify!(CryptoOption))?;
335 dict.set_item("id", self.id.to_string())?;
336 dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
337 dict.set_item("underlying", self.underlying.code.to_string())?;
338 dict.set_item("quote_currency", self.quote_currency.code.to_string())?;
339 dict.set_item(
340 "settlement_currency",
341 self.settlement_currency.code.to_string(),
342 )?;
343 dict.set_item("is_inverse", self.is_inverse)?;
344 dict.set_item("option_kind", self.option_kind.to_string())?;
345 dict.set_item("strike_price", self.strike_price.to_string())?;
346 dict.set_item("activation_ns", self.activation_ns.as_u64())?;
347 dict.set_item("expiration_ns", self.expiration_ns.as_u64())?;
348 dict.set_item("price_precision", self.price_precision)?;
349 dict.set_item("size_precision", self.size_precision)?;
350 dict.set_item("price_increment", self.price_increment.to_string())?;
351 dict.set_item("size_increment", self.size_increment.to_string())?;
352 dict.set_item("multiplier", self.multiplier.to_string())?;
353 dict.set_item("lot_size", self.lot_size.to_string())?;
354 dict.set_item("margin_init", self.margin_init.to_string())?;
355 dict.set_item("margin_maint", self.margin_maint.to_string())?;
356 dict.set_item("maker_fee", self.maker_fee.to_string())?;
357 dict.set_item("taker_fee", self.taker_fee.to_string())?;
358 dict.set_item("ts_event", self.ts_event.as_u64())?;
359 dict.set_item("ts_init", self.ts_init.as_u64())?;
360 if let Some(ref info_map) = self.info {
362 let info_dict = PyDict::new(py);
363
364 for (key, value) in info_map {
365 let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
366 let py_value =
367 PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
368 info_dict.set_item(key, py_value)?;
369 }
370 dict.set_item("info", info_dict)?;
371 } else {
372 dict.set_item("info", PyDict::new(py))?;
373 }
374
375 match self.max_quantity {
376 Some(value) => dict.set_item("max_quantity", value.to_string())?,
377 None => dict.set_item("max_quantity", py.None())?,
378 }
379
380 match self.min_quantity {
381 Some(value) => dict.set_item("min_quantity", value.to_string())?,
382 None => dict.set_item("min_quantity", py.None())?,
383 }
384
385 match self.max_notional {
386 Some(value) => dict.set_item("max_notional", value.to_string())?,
387 None => dict.set_item("max_notional", py.None())?,
388 }
389
390 match self.min_notional {
391 Some(value) => dict.set_item("min_notional", value.to_string())?,
392 None => dict.set_item("min_notional", py.None())?,
393 }
394
395 match self.max_price {
396 Some(value) => dict.set_item("max_price", value.to_string())?,
397 None => dict.set_item("max_price", py.None())?,
398 }
399
400 match self.min_price {
401 Some(value) => dict.set_item("min_price", value.to_string())?,
402 None => dict.set_item("min_price", py.None())?,
403 }
404 dict.set_item(
405 "tick_scheme",
406 crate::python::instruments::tick_scheme_to_py(self),
407 )?;
408 Ok(dict.into())
409 }
410}
411
412#[cfg(test)]
413mod tests {
414 use pyo3::{prelude::*, types::PyDict};
415 use rstest::rstest;
416
417 use crate::{
418 enums::CurrencyType,
419 instruments::{CryptoOption, stubs::*},
420 types::Currency,
421 };
422
423 #[rstest]
424 fn test_dict_round_trip(crypto_option_btc_deribit: CryptoOption) {
425 Python::initialize();
426 Python::attach(|py| {
427 let crypto_option = crypto_option_btc_deribit;
428 let values = crypto_option.py_to_dict(py).unwrap();
429 let values: Py<PyDict> = values.extract(py).unwrap();
430 let new_crypto_future = CryptoOption::py_from_dict(py, values).unwrap();
431 assert_eq!(crypto_option, new_crypto_future);
432 });
433 }
434
435 #[rstest]
436 fn test_from_dict_unknown_underlying_registers_as_crypto(
437 crypto_option_btc_deribit: CryptoOption,
438 ) {
439 Python::initialize();
442 Python::attach(|py| {
443 let values = crypto_option_btc_deribit.py_to_dict(py).unwrap();
444 let values: Py<PyDict> = values.extract(py).unwrap();
445 values.bind(py).set_item("underlying", "NEWOPT").unwrap();
446
447 let new_option = CryptoOption::py_from_dict(py, values).unwrap();
448 assert_eq!(new_option.underlying.code.as_str(), "NEWOPT");
449 assert_eq!(new_option.underlying.precision, 8);
450 assert_eq!(new_option.underlying.currency_type, CurrencyType::Crypto);
451 assert!(Currency::try_from_str("NEWOPT").is_some());
452 });
453 }
454}