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