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, to_pyvalue_err},
24};
25use pyo3::{basic::CompareOp, prelude::*, types::PyDict};
26use rust_decimal::Decimal;
27use ustr::Ustr;
28
29use crate::{
30    enums::{AssetClass, ExerciseStyle, OptionKind, SettlementType},
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, exchange=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        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        exchange: Option<String>,
66        tick_scheme: Option<String>,
67        info: Option<Py<PyDict>>,
68        underlying_instrument_id: Option<InstrumentId>,
69        exercise_style: Option<ExerciseStyle>,
70        settlement_type: Option<SettlementType>,
71    ) -> PyResult<Self> {
72        // Convert Python dict to Params
73        let info_map = if let Some(info_dict) = info {
74            Python::attach(|py| from_pydict(py, &info_dict))?
75        } else {
76            None
77        };
78
79        Self::builder()
80            .instrument_id(instrument_id)
81            .raw_symbol(raw_symbol)
82            .asset_class(asset_class)
83            .maybe_exchange(exchange.map(|x| Ustr::from(&x)))
84            .underlying(underlying.into())
85            .option_kind(option_kind)
86            .strike_price(strike_price)
87            .currency(currency)
88            .activation_ns(activation_ns.into())
89            .expiration_ns(expiration_ns.into())
90            .price_precision(price_precision)
91            .price_increment(price_increment)
92            .multiplier(multiplier)
93            .lot_size(lot_size)
94            .maybe_max_quantity(max_quantity)
95            .maybe_min_quantity(min_quantity)
96            .maybe_max_price(max_price)
97            .maybe_min_price(min_price)
98            .maybe_margin_init(margin_init)
99            .maybe_margin_maint(margin_maint)
100            .maybe_tick_scheme(tick_scheme.map(|name| ustr::Ustr::from(name.as_str())))
101            .maybe_info(info_map)
102            .maybe_underlying_instrument_id(underlying_instrument_id)
103            .maybe_exercise_style(exercise_style)
104            .maybe_settlement_type(settlement_type)
105            .ts_event(ts_event.into())
106            .ts_init(ts_init.into())
107            .build()
108            .map_err(to_pyvalue_err)
109    }
110
111    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
112        match op {
113            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
114            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
115            _ => py.NotImplemented(),
116        }
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    #[getter]
126    fn type_name(&self) -> &'static str {
127        stringify!(OptionContract)
128    }
129
130    #[getter]
131    #[pyo3(name = "id")]
132    fn py_id(&self) -> InstrumentId {
133        self.id
134    }
135
136    #[getter]
137    #[pyo3(name = "raw_symbol")]
138    fn py_raw_symbol(&self) -> Symbol {
139        self.raw_symbol
140    }
141
142    #[getter]
143    #[pyo3(name = "asset_class")]
144    fn py_asset_class(&self) -> AssetClass {
145        self.asset_class
146    }
147
148    #[getter]
149    #[pyo3(name = "exchange")]
150    fn py_exchange(&self) -> Option<String> {
151        self.exchange.map(|e| e.to_string())
152    }
153
154    #[getter]
155    #[pyo3(name = "underlying")]
156    fn py_underlying(&self) -> &str {
157        self.underlying.as_str()
158    }
159
160    #[getter]
161    #[pyo3(name = "underlying_instrument_id")]
162    fn py_underlying_instrument_id(&self) -> Option<InstrumentId> {
163        self.underlying_instrument_id
164    }
165
166    #[getter]
167    #[pyo3(name = "exercise_style")]
168    fn py_exercise_style(&self) -> Option<ExerciseStyle> {
169        self.exercise_style
170    }
171
172    #[getter]
173    #[pyo3(name = "settlement_type")]
174    fn py_settlement_type(&self) -> Option<SettlementType> {
175        self.settlement_type
176    }
177
178    #[getter]
179    #[pyo3(name = "option_kind")]
180    fn py_option_kind(&self) -> OptionKind {
181        self.option_kind
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 = "strike_price")]
198    fn py_strike_price(&self) -> Price {
199        self.strike_price
200    }
201
202    #[getter]
203    #[pyo3(name = "currency")]
204    fn py_currency(&self) -> Currency {
205        self.currency
206    }
207
208    #[getter]
209    #[pyo3(name = "price_precision")]
210    fn py_price_precision(&self) -> u8 {
211        self.price_precision
212    }
213
214    #[getter]
215    #[pyo3(name = "price_increment")]
216    fn py_price_increment(&self) -> Price {
217        self.price_increment
218    }
219
220    #[getter]
221    #[pyo3(name = "size_increment")]
222    fn py_size_increment(&self) -> Quantity {
223        self.size_increment
224    }
225
226    #[getter]
227    #[pyo3(name = "size_precision")]
228    fn py_size_precision(&self) -> u8 {
229        self.size_precision
230    }
231
232    #[getter]
233    #[pyo3(name = "multiplier")]
234    fn py_multiplier(&self) -> Quantity {
235        self.multiplier
236    }
237
238    #[getter]
239    #[pyo3(name = "lot_size")]
240    fn py_lot_size(&self) -> Quantity {
241        self.lot_size
242    }
243
244    #[getter]
245    #[pyo3(name = "max_quantity")]
246    fn py_max_quantity(&self) -> Option<Quantity> {
247        self.max_quantity
248    }
249
250    #[getter]
251    #[pyo3(name = "min_quantity")]
252    fn py_min_quantity(&self) -> Option<Quantity> {
253        self.min_quantity
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 = "info")]
282    fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
283        // Convert HashMap<String, serde_json::Value> back to Python dict
284        if let Some(ref info_map) = self.info {
285            let py_dict = PyDict::new(py);
286
287            for (key, value) in info_map {
288                // Convert serde_json::Value back to Python object via JSON
289                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
290                let py_value =
291                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
292                py_dict.set_item(key, py_value)?;
293            }
294            Ok(py_dict.unbind())
295        } else {
296            Ok(PyDict::new(py).unbind())
297        }
298    }
299
300    #[getter]
301    #[pyo3(name = "ts_event")]
302    fn py_ts_event(&self) -> u64 {
303        self.ts_event.as_u64()
304    }
305
306    #[getter]
307    #[pyo3(name = "ts_init")]
308    fn py_ts_init(&self) -> u64 {
309        self.ts_init.as_u64()
310    }
311
312    #[staticmethod]
313    #[pyo3(name = "from_dict")]
314    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
315        crate::python::instruments::from_dict_instrument_pyo3(py, values)
316    }
317
318    #[pyo3(name = "to_dict")]
319    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
320        let dict = PyDict::new(py);
321        dict.set_item("type", stringify!(OptionContract))?;
322        dict.set_item("id", self.id.to_string())?;
323        dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
324        dict.set_item("asset_class", self.asset_class.to_string())?;
325        dict.set_item("underlying", self.underlying.to_string())?;
326        dict.set_item("option_kind", self.option_kind.to_string())?;
327        dict.set_item(
328            "underlying_instrument_id",
329            self.underlying_instrument_id.map(|id| id.to_string()),
330        )?;
331        dict.set_item(
332            "exercise_style",
333            self.exercise_style.map(|style| style.to_string()),
334        )?;
335        dict.set_item(
336            "settlement_type",
337            self.settlement_type.map(|kind| kind.to_string()),
338        )?;
339        dict.set_item("activation_ns", self.activation_ns.as_u64())?;
340        dict.set_item("expiration_ns", self.expiration_ns.as_u64())?;
341        dict.set_item("strike_price", self.strike_price.to_string())?;
342        dict.set_item("currency", self.currency.code.to_string())?;
343        dict.set_item("price_precision", self.price_precision)?;
344        dict.set_item("price_increment", self.price_increment.to_string())?;
345        dict.set_item("size_increment", self.size_increment.to_string())?;
346        dict.set_item("size_precision", self.size_precision)?;
347        dict.set_item("multiplier", self.multiplier.to_string())?;
348        dict.set_item("lot_size", self.lot_size.to_string())?;
349        dict.set_item("margin_init", self.margin_init.to_string())?;
350        dict.set_item("margin_maint", self.margin_maint.to_string())?;
351        // Serialize info dict
352        if let Some(ref info_map) = self.info {
353            let info_dict = PyDict::new(py);
354
355            for (key, value) in info_map {
356                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
357                let py_value =
358                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
359                info_dict.set_item(key, py_value)?;
360            }
361            dict.set_item("info", info_dict)?;
362        } else {
363            dict.set_item("info", PyDict::new(py))?;
364        }
365        dict.set_item("ts_event", self.ts_event.as_u64())?;
366        dict.set_item("ts_init", self.ts_init.as_u64())?;
367        match self.max_quantity {
368            Some(value) => dict.set_item("max_quantity", value.to_string())?,
369            None => dict.set_item("max_quantity", py.None())?,
370        }
371
372        match self.min_quantity {
373            Some(value) => dict.set_item("min_quantity", value.to_string())?,
374            None => dict.set_item("min_quantity", 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
387        match self.exchange {
388            Some(value) => dict.set_item("exchange", value.to_string())?,
389            None => dict.set_item("exchange", py.None())?,
390        }
391        dict.set_item(
392            "tick_scheme",
393            crate::python::instruments::tick_scheme_to_py(self),
394        )?;
395        Ok(dict.into())
396    }
397}