Skip to main content

nautilus_model/python/instruments/
binary_option.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,
31    identifiers::{InstrumentId, Symbol},
32    instruments::BinaryOption,
33    types::{Currency, Money, Price, Quantity},
34};
35
36#[pymethods]
37#[pyo3_stub_gen::derive::gen_stub_pymethods]
38impl BinaryOption {
39    /// Represents a generic binary option instrument.
40    #[expect(clippy::too_many_arguments)]
41    #[new]
42    #[pyo3(signature = (instrument_id, raw_symbol, asset_class, currency, activation_ns, expiration_ns, price_precision, size_precision, price_increment, size_increment, ts_event, ts_init, outcome=None, description=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        asset_class: AssetClass,
47        currency: Currency,
48        activation_ns: u64,
49        expiration_ns: u64,
50        price_precision: u8,
51        size_precision: u8,
52        price_increment: Price,
53        size_increment: Quantity,
54        ts_event: u64,
55        ts_init: u64,
56        outcome: Option<String>,
57        description: Option<String>,
58        max_quantity: Option<Quantity>,
59        min_quantity: Option<Quantity>,
60        max_notional: Option<Money>,
61        min_notional: Option<Money>,
62        max_price: Option<Price>,
63        min_price: Option<Price>,
64        margin_init: Option<Decimal>,
65        margin_maint: Option<Decimal>,
66        maker_fee: Option<Decimal>,
67        taker_fee: Option<Decimal>,
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            currency,
82            activation_ns.into(),
83            expiration_ns.into(),
84            price_precision,
85            size_precision,
86            price_increment,
87            size_increment,
88            outcome.map(|x| Ustr::from(&x)),
89            description.map(|x| Ustr::from(&x)),
90            max_quantity,
91            min_quantity,
92            max_notional,
93            min_notional,
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 __hash__(&self) -> isize {
108        let mut hasher = DefaultHasher::new();
109        self.hash(&mut hasher);
110        hasher.finish() as isize
111    }
112
113    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
114        match op {
115            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
116            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
117            _ => py.NotImplemented(),
118        }
119    }
120
121    #[getter]
122    fn type_name(&self) -> &'static str {
123        stringify!(BinaryOption)
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 = "currency")]
146    fn py_currency(&self) -> Currency {
147        self.currency
148    }
149
150    #[getter]
151    #[pyo3(name = "activation_ns")]
152    fn py_activation_ns(&self) -> u64 {
153        self.activation_ns.as_u64()
154    }
155
156    #[getter]
157    #[pyo3(name = "expiration_ns")]
158    fn py_expiration_ns(&self) -> u64 {
159        self.expiration_ns.as_u64()
160    }
161
162    #[getter]
163    #[pyo3(name = "price_precision")]
164    fn py_price_precision(&self) -> u8 {
165        self.price_precision
166    }
167
168    #[getter]
169    #[pyo3(name = "size_precision")]
170    fn py_size_precision(&self) -> u8 {
171        self.size_precision
172    }
173
174    #[getter]
175    #[pyo3(name = "price_increment")]
176    fn py_price_increment(&self) -> Price {
177        self.price_increment
178    }
179
180    #[getter]
181    #[pyo3(name = "size_increment")]
182    fn py_size_increment(&self) -> Quantity {
183        self.size_increment
184    }
185
186    #[getter]
187    #[pyo3(name = "outcome")]
188    fn py_outcome(&self) -> Option<&str> {
189        match self.outcome {
190            Some(outcome) => Some(outcome.as_str()),
191            None => None,
192        }
193    }
194
195    #[getter]
196    #[pyo3(name = "description")]
197    fn py_description(&self) -> Option<&str> {
198        match self.description {
199            Some(description) => Some(description.as_str()),
200            None => None,
201        }
202    }
203
204    #[getter]
205    #[pyo3(name = "max_quantity")]
206    fn py_max_quantity(&self) -> Option<Quantity> {
207        self.max_quantity
208    }
209
210    #[getter]
211    #[pyo3(name = "min_quantity")]
212    fn py_min_quantity(&self) -> Option<Quantity> {
213        self.min_quantity
214    }
215
216    #[getter]
217    #[pyo3(name = "max_notional")]
218    fn py_max_notional(&self) -> Option<Money> {
219        self.max_notional
220    }
221
222    #[getter]
223    #[pyo3(name = "min_notional")]
224    fn py_min_notional(&self) -> Option<Money> {
225        self.min_notional
226    }
227
228    #[getter]
229    #[pyo3(name = "max_price")]
230    fn py_max_price(&self) -> Option<Price> {
231        self.max_price
232    }
233
234    #[getter]
235    #[pyo3(name = "min_price")]
236    fn py_min_price(&self) -> Option<Price> {
237        self.min_price
238    }
239
240    #[getter]
241    #[pyo3(name = "margin_init")]
242    fn py_margin_init(&self) -> Decimal {
243        self.margin_init
244    }
245
246    #[getter]
247    #[pyo3(name = "margin_maint")]
248    fn py_margin_maint(&self) -> Decimal {
249        self.margin_maint
250    }
251
252    #[getter]
253    #[pyo3(name = "maker_fee")]
254    fn py_maker_fee(&self) -> Decimal {
255        self.maker_fee
256    }
257
258    #[getter]
259    #[pyo3(name = "taker_fee")]
260    fn py_taker_fee(&self) -> Decimal {
261        self.taker_fee
262    }
263
264    #[getter]
265    #[pyo3(name = "info")]
266    fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
267        // Convert HashMap<String, serde_json::Value> back to Python dict
268        if let Some(ref info_map) = self.info {
269            let py_dict = PyDict::new(py);
270
271            for (key, value) in info_map {
272                // Convert serde_json::Value back to Python object via JSON
273                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
274                let py_value =
275                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
276                py_dict.set_item(key, py_value)?;
277            }
278            Ok(py_dict.unbind())
279        } else {
280            Ok(PyDict::new(py).unbind())
281        }
282    }
283
284    #[getter]
285    #[pyo3(name = "ts_event")]
286    fn py_ts_event(&self) -> u64 {
287        self.ts_event.as_u64()
288    }
289
290    #[getter]
291    #[pyo3(name = "ts_init")]
292    fn py_ts_init(&self) -> u64 {
293        self.ts_init.as_u64()
294    }
295
296    #[staticmethod]
297    #[pyo3(name = "from_dict")]
298    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
299        from_dict_pyo3(py, values)
300    }
301
302    #[pyo3(name = "to_dict")]
303    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
304        let dict = PyDict::new(py);
305        dict.set_item("type", stringify!(BinaryOption))?;
306        dict.set_item("id", self.id.to_string())?;
307        dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
308        dict.set_item("asset_class", self.asset_class.to_string())?;
309        dict.set_item("currency", self.currency.code.to_string())?;
310        dict.set_item("activation_ns", self.activation_ns.as_u64())?;
311        dict.set_item("expiration_ns", self.expiration_ns.as_u64())?;
312        dict.set_item("price_precision", self.price_precision)?;
313        dict.set_item("size_precision", self.size_precision)?;
314        dict.set_item("price_increment", self.price_increment.to_string())?;
315        dict.set_item("size_increment", self.size_increment.to_string())?;
316        dict.set_item("margin_init", self.margin_init.to_string())?;
317        dict.set_item("margin_maint", self.margin_maint.to_string())?;
318        dict.set_item("maker_fee", self.maker_fee.to_string())?;
319        dict.set_item("taker_fee", self.taker_fee.to_string())?;
320        dict.set_item("ts_event", self.ts_event.as_u64())?;
321        dict.set_item("ts_init", self.ts_init.as_u64())?;
322        // Serialize info dict
323        if let Some(ref info_map) = self.info {
324            let info_dict = PyDict::new(py);
325
326            for (key, value) in info_map {
327                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
328                let py_value =
329                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
330                info_dict.set_item(key, py_value)?;
331            }
332            dict.set_item("info", info_dict)?;
333        } else {
334            dict.set_item("info", PyDict::new(py))?;
335        }
336
337        match &self.outcome {
338            Some(value) => dict.set_item("outcome", value.to_string())?,
339            None => dict.set_item("outcome", py.None())?,
340        }
341
342        match &self.description {
343            Some(value) => dict.set_item("description", value.to_string())?,
344            None => dict.set_item("description", py.None())?,
345        }
346
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_notional {
358            Some(value) => dict.set_item("max_notional", value.to_string())?,
359            None => dict.set_item("max_notional", py.None())?,
360        }
361
362        match self.min_notional {
363            Some(value) => dict.set_item("min_notional", value.to_string())?,
364            None => dict.set_item("min_notional", py.None())?,
365        }
366
367        match self.max_price {
368            Some(value) => dict.set_item("max_price", value.to_string())?,
369            None => dict.set_item("max_price", py.None())?,
370        }
371
372        match self.min_price {
373            Some(value) => dict.set_item("min_price", value.to_string())?,
374            None => dict.set_item("min_price", py.None())?,
375        }
376        Ok(dict.into())
377    }
378}
379
380#[cfg(test)]
381mod tests {
382    use pyo3::{prelude::*, types::PyDict};
383    use rstest::rstest;
384
385    use crate::instruments::{BinaryOption, stubs::*};
386
387    #[rstest]
388    fn test_dict_round_trip(binary_option: BinaryOption) {
389        Python::initialize();
390        Python::attach(|py| {
391            let values = binary_option.py_to_dict(py).unwrap();
392            let values: Py<PyDict> = values.extract(py).unwrap();
393            let new_binary_option = BinaryOption::py_from_dict(py, values).unwrap();
394            assert_eq!(binary_option, new_binary_option);
395        });
396    }
397}