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