Skip to main content

nautilus_model/python/instruments/
option_contract.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    enums::{AssetClass, OptionKind},
31    identifiers::{InstrumentId, Symbol},
32    instruments::OptionContract,
33    types::{Currency, Price, Quantity},
34};
35
36#[pymethods]
37#[pyo3_stub_gen::derive::gen_stub_pymethods]
38impl OptionContract {
39    /// Represents a generic option contract instrument.
40    #[expect(clippy::too_many_arguments)]
41    #[new]
42    #[pyo3(signature = (instrument_id, raw_symbol, asset_class, underlying, option_kind, strike_price, currency, activation_ns, expiration_ns, price_precision, price_increment, multiplier, lot_size, ts_event, ts_init,  max_quantity=None, min_quantity=None, max_price=None, min_price=None, margin_init=None, margin_maint=None, maker_fee=None, taker_fee=None, exchange=None, info=None))]
43    fn py_new(
44        instrument_id: InstrumentId,
45        raw_symbol: Symbol,
46        asset_class: AssetClass,
47        underlying: String,
48        option_kind: OptionKind,
49        strike_price: Price,
50        currency: Currency,
51        activation_ns: u64,
52        expiration_ns: u64,
53        price_precision: u8,
54        price_increment: Price,
55        multiplier: Quantity,
56        lot_size: Quantity,
57        ts_event: u64,
58        ts_init: u64,
59        max_quantity: Option<Quantity>,
60        min_quantity: Option<Quantity>,
61        max_price: Option<Price>,
62        min_price: Option<Price>,
63        margin_init: Option<Decimal>,
64        margin_maint: Option<Decimal>,
65        maker_fee: Option<Decimal>,
66        taker_fee: Option<Decimal>,
67        exchange: Option<String>,
68        info: Option<Py<PyDict>>,
69    ) -> PyResult<Self> {
70        // Convert Python dict to Params
71        let info_map = if let Some(info_dict) = info {
72            Python::attach(|py| from_pydict(py, info_dict))?
73        } else {
74            None
75        };
76
77        Self::new_checked(
78            instrument_id,
79            raw_symbol,
80            asset_class,
81            exchange.map(|x| Ustr::from(&x)),
82            underlying.into(),
83            option_kind,
84            strike_price,
85            currency,
86            activation_ns.into(),
87            expiration_ns.into(),
88            price_precision,
89            price_increment,
90            multiplier,
91            lot_size,
92            max_quantity,
93            min_quantity,
94            max_price,
95            min_price,
96            margin_init,
97            margin_maint,
98            maker_fee,
99            taker_fee,
100            info_map,
101            ts_event.into(),
102            ts_init.into(),
103        )
104        .map_err(to_pyvalue_err)
105    }
106
107    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
108        match op {
109            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
110            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
111            _ => py.NotImplemented(),
112        }
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    #[getter]
122    fn type_name(&self) -> &'static str {
123        stringify!(OptionContract)
124    }
125
126    #[getter]
127    #[pyo3(name = "id")]
128    fn py_id(&self) -> InstrumentId {
129        self.id
130    }
131
132    #[getter]
133    #[pyo3(name = "raw_symbol")]
134    fn py_raw_symbol(&self) -> Symbol {
135        self.raw_symbol
136    }
137
138    #[getter]
139    #[pyo3(name = "asset_class")]
140    fn py_asset_class(&self) -> AssetClass {
141        self.asset_class
142    }
143
144    #[getter]
145    #[pyo3(name = "exchange")]
146    fn py_exchange(&self) -> Option<String> {
147        self.exchange.map(|e| e.to_string())
148    }
149
150    #[getter]
151    #[pyo3(name = "underlying")]
152    fn py_underlying(&self) -> &str {
153        self.underlying.as_str()
154    }
155
156    #[getter]
157    #[pyo3(name = "option_kind")]
158    fn py_option_kind(&self) -> OptionKind {
159        self.option_kind
160    }
161
162    #[getter]
163    #[pyo3(name = "activation_ns")]
164    fn py_activation_ns(&self) -> u64 {
165        self.activation_ns.as_u64()
166    }
167
168    #[getter]
169    #[pyo3(name = "expiration_ns")]
170    fn py_expiration_ns(&self) -> u64 {
171        self.expiration_ns.as_u64()
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 = "currency")]
182    fn py_currency(&self) -> Currency {
183        self.currency
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 = "price_increment")]
194    fn py_price_increment(&self) -> Price {
195        self.price_increment
196    }
197
198    #[getter]
199    #[pyo3(name = "size_increment")]
200    fn py_size_increment(&self) -> Quantity {
201        self.size_increment
202    }
203
204    #[getter]
205    #[pyo3(name = "size_precision")]
206    fn py_size_precision(&self) -> u8 {
207        self.size_precision
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_price")]
236    fn py_max_price(&self) -> Option<Price> {
237        self.max_price
238    }
239
240    #[getter]
241    #[pyo3(name = "min_price")]
242    fn py_min_price(&self) -> Option<Price> {
243        self.min_price
244    }
245
246    #[getter]
247    #[pyo3(name = "margin_init")]
248    fn py_margin_init(&self) -> Decimal {
249        self.margin_init
250    }
251
252    #[getter]
253    #[pyo3(name = "margin_maint")]
254    fn py_margin_maint(&self) -> Decimal {
255        self.margin_maint
256    }
257
258    #[getter]
259    #[pyo3(name = "maker_fee")]
260    fn py_maker_fee(&self) -> Decimal {
261        self.maker_fee
262    }
263
264    #[getter]
265    #[pyo3(name = "taker_fee")]
266    fn py_taker_fee(&self) -> Decimal {
267        self.taker_fee
268    }
269
270    #[getter]
271    #[pyo3(name = "info")]
272    fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
273        // Convert HashMap<String, serde_json::Value> back to Python dict
274        if let Some(ref info_map) = self.info {
275            let py_dict = PyDict::new(py);
276
277            for (key, value) in info_map {
278                // Convert serde_json::Value back to Python object via JSON
279                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
280                let py_value =
281                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
282                py_dict.set_item(key, py_value)?;
283            }
284            Ok(py_dict.unbind())
285        } else {
286            Ok(PyDict::new(py).unbind())
287        }
288    }
289
290    #[getter]
291    #[pyo3(name = "ts_event")]
292    fn py_ts_event(&self) -> u64 {
293        self.ts_event.as_u64()
294    }
295
296    #[getter]
297    #[pyo3(name = "ts_init")]
298    fn py_ts_init(&self) -> u64 {
299        self.ts_init.as_u64()
300    }
301
302    #[staticmethod]
303    #[pyo3(name = "from_dict")]
304    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
305        from_dict_pyo3(py, values)
306    }
307
308    #[pyo3(name = "to_dict")]
309    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
310        let dict = PyDict::new(py);
311        dict.set_item("type", stringify!(OptionContract))?;
312        dict.set_item("id", self.id.to_string())?;
313        dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
314        dict.set_item("asset_class", self.asset_class.to_string())?;
315        dict.set_item("underlying", self.underlying.to_string())?;
316        dict.set_item("option_kind", self.option_kind.to_string())?;
317        dict.set_item("activation_ns", self.activation_ns.as_u64())?;
318        dict.set_item("expiration_ns", self.expiration_ns.as_u64())?;
319        dict.set_item("strike_price", self.strike_price.to_string())?;
320        dict.set_item("currency", self.currency.code.to_string())?;
321        dict.set_item("price_precision", self.price_precision)?;
322        dict.set_item("price_increment", self.price_increment.to_string())?;
323        dict.set_item("size_increment", self.size_increment.to_string())?;
324        dict.set_item("size_precision", self.size_precision)?;
325        dict.set_item("multiplier", self.multiplier.to_string())?;
326        dict.set_item("lot_size", self.lot_size.to_string())?;
327        dict.set_item("margin_init", self.margin_init.to_string())?;
328        dict.set_item("margin_maint", self.margin_maint.to_string())?;
329        dict.set_item("maker_fee", self.maker_fee.to_string())?;
330        dict.set_item("taker_fee", self.taker_fee.to_string())?;
331        // Serialize info dict
332        if let Some(ref info_map) = self.info {
333            let info_dict = PyDict::new(py);
334
335            for (key, value) in info_map {
336                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
337                let py_value =
338                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
339                info_dict.set_item(key, py_value)?;
340            }
341            dict.set_item("info", info_dict)?;
342        } else {
343            dict.set_item("info", PyDict::new(py))?;
344        }
345        dict.set_item("ts_event", self.ts_event.as_u64())?;
346        dict.set_item("ts_init", self.ts_init.as_u64())?;
347        match self.max_quantity {
348            Some(value) => dict.set_item("max_quantity", value.to_string())?,
349            None => dict.set_item("max_quantity", py.None())?,
350        }
351
352        match self.min_quantity {
353            Some(value) => dict.set_item("min_quantity", value.to_string())?,
354            None => dict.set_item("min_quantity", py.None())?,
355        }
356
357        match self.max_price {
358            Some(value) => dict.set_item("max_price", value.to_string())?,
359            None => dict.set_item("max_price", py.None())?,
360        }
361
362        match self.min_price {
363            Some(value) => dict.set_item("min_price", value.to_string())?,
364            None => dict.set_item("min_price", py.None())?,
365        }
366
367        match self.exchange {
368            Some(value) => dict.set_item("exchange", value.to_string())?,
369            None => dict.set_item("exchange", py.None())?,
370        }
371        Ok(dict.into())
372    }
373}