nautilus_model/python/instruments/
binary_option.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 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::python::{serialization::from_dict_pyo3, to_pyvalue_err};
22use pyo3::{basic::CompareOp, prelude::*, types::PyDict};
23use rust_decimal::Decimal;
24use ustr::Ustr;
25
26use crate::{
27    enums::AssetClass,
28    identifiers::{InstrumentId, Symbol},
29    instruments::BinaryOption,
30    types::{Currency, Money, Price, Quantity},
31};
32
33#[pymethods]
34impl BinaryOption {
35    #[allow(clippy::too_many_arguments)]
36    #[new]
37    #[pyo3(signature = (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))]
38    fn py_new(
39        id: InstrumentId,
40        raw_symbol: Symbol,
41        asset_class: AssetClass,
42        currency: Currency,
43        activation_ns: u64,
44        expiration_ns: u64,
45        price_precision: u8,
46        size_precision: u8,
47        price_increment: Price,
48        size_increment: Quantity,
49        ts_event: u64,
50        ts_init: u64,
51        outcome: Option<String>,
52        description: Option<String>,
53        max_quantity: Option<Quantity>,
54        min_quantity: Option<Quantity>,
55        max_notional: Option<Money>,
56        min_notional: Option<Money>,
57        max_price: Option<Price>,
58        min_price: Option<Price>,
59        margin_init: Option<Decimal>,
60        margin_maint: Option<Decimal>,
61        maker_fee: Option<Decimal>,
62        taker_fee: Option<Decimal>,
63    ) -> PyResult<Self> {
64        Self::new_checked(
65            id,
66            raw_symbol,
67            asset_class,
68            currency,
69            activation_ns.into(),
70            expiration_ns.into(),
71            price_precision,
72            size_precision,
73            price_increment,
74            size_increment,
75            outcome.map(|x| Ustr::from(&x)),
76            description.map(|x| Ustr::from(&x)),
77            max_quantity,
78            min_quantity,
79            max_notional,
80            min_notional,
81            max_price,
82            min_price,
83            margin_init,
84            margin_maint,
85            maker_fee,
86            taker_fee,
87            ts_event.into(),
88            ts_init.into(),
89        )
90        .map_err(to_pyvalue_err)
91    }
92
93    fn __hash__(&self) -> isize {
94        let mut hasher = DefaultHasher::new();
95        self.hash(&mut hasher);
96        hasher.finish() as isize
97    }
98
99    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
100        match op {
101            CompareOp::Eq => self.eq(other).into_py(py),
102            _ => panic!("Not implemented"),
103        }
104    }
105
106    #[getter]
107    fn type_str(&self) -> &str {
108        stringify!(BinaryOption)
109    }
110
111    #[getter]
112    #[pyo3(name = "id")]
113    fn py_id(&self) -> InstrumentId {
114        self.id
115    }
116
117    #[getter]
118    #[pyo3(name = "raw_symbol")]
119    fn py_raw_symbol(&self) -> Symbol {
120        self.raw_symbol
121    }
122
123    #[getter]
124    #[pyo3(name = "asset_class")]
125    fn py_asset_class(&self) -> AssetClass {
126        self.asset_class
127    }
128
129    #[getter]
130    #[pyo3(name = "currency")]
131    fn py_currency(&self) -> Currency {
132        self.currency
133    }
134
135    #[getter]
136    #[pyo3(name = "activation_ns")]
137    fn py_activation_ns(&self) -> u64 {
138        self.activation_ns.as_u64()
139    }
140
141    #[getter]
142    #[pyo3(name = "expiration_ns")]
143    fn py_expiration_ns(&self) -> u64 {
144        self.expiration_ns.as_u64()
145    }
146
147    #[getter]
148    #[pyo3(name = "price_precision")]
149    fn py_price_precision(&self) -> u8 {
150        self.price_precision
151    }
152
153    #[getter]
154    #[pyo3(name = "size_precision")]
155    fn py_size_precision(&self) -> u8 {
156        self.size_precision
157    }
158
159    #[getter]
160    #[pyo3(name = "price_increment")]
161    fn py_price_increment(&self) -> Price {
162        self.price_increment
163    }
164
165    #[getter]
166    #[pyo3(name = "size_increment")]
167    fn py_size_increment(&self) -> Quantity {
168        self.size_increment
169    }
170
171    #[getter]
172    #[pyo3(name = "outcome")]
173    fn py_outcome(&self) -> Option<&str> {
174        match self.outcome {
175            Some(outcome) => Some(outcome.as_str()),
176            None => None,
177        }
178    }
179
180    #[getter]
181    #[pyo3(name = "description")]
182    fn py_description(&self) -> Option<&str> {
183        match self.description {
184            Some(description) => Some(description.as_str()),
185            None => None,
186        }
187    }
188
189    #[getter]
190    #[pyo3(name = "max_quantity")]
191    fn py_max_quantity(&self) -> Option<Quantity> {
192        self.max_quantity
193    }
194
195    #[getter]
196    #[pyo3(name = "min_quantity")]
197    fn py_min_quantity(&self) -> Option<Quantity> {
198        self.min_quantity
199    }
200
201    #[getter]
202    #[pyo3(name = "max_notional")]
203    fn py_max_notional(&self) -> Option<Money> {
204        self.max_notional
205    }
206
207    #[getter]
208    #[pyo3(name = "min_notional")]
209    fn py_min_notional(&self) -> Option<Money> {
210        self.min_notional
211    }
212
213    #[getter]
214    #[pyo3(name = "max_price")]
215    fn py_max_price(&self) -> Option<Price> {
216        self.max_price
217    }
218
219    #[getter]
220    #[pyo3(name = "min_price")]
221    fn py_min_price(&self) -> Option<Price> {
222        self.min_price
223    }
224
225    #[getter]
226    #[pyo3(name = "margin_init")]
227    fn py_margin_init(&self) -> Decimal {
228        self.margin_init
229    }
230
231    #[getter]
232    #[pyo3(name = "margin_maint")]
233    fn py_margin_maint(&self) -> Decimal {
234        self.margin_maint
235    }
236
237    #[getter]
238    #[pyo3(name = "maker_fee")]
239    fn py_maker_fee(&self) -> Decimal {
240        self.maker_fee
241    }
242
243    #[getter]
244    #[pyo3(name = "taker_fee")]
245    fn py_taker_fee(&self) -> Decimal {
246        self.taker_fee
247    }
248
249    #[getter]
250    #[pyo3(name = "info")]
251    fn py_info(&self, py: Python<'_>) -> PyResult<PyObject> {
252        Ok(PyDict::new(py).into())
253    }
254
255    #[getter]
256    #[pyo3(name = "ts_event")]
257    fn py_ts_event(&self) -> u64 {
258        self.ts_event.as_u64()
259    }
260
261    #[getter]
262    #[pyo3(name = "ts_init")]
263    fn py_ts_init(&self) -> u64 {
264        self.ts_init.as_u64()
265    }
266
267    #[staticmethod]
268    #[pyo3(name = "from_dict")]
269    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
270        from_dict_pyo3(py, values)
271    }
272
273    #[pyo3(name = "to_dict")]
274    fn py_to_dict(&self, py: Python<'_>) -> PyResult<PyObject> {
275        let dict = PyDict::new(py);
276        dict.set_item("type", stringify!(BinaryOption))?;
277        dict.set_item("id", self.id.to_string())?;
278        dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
279        dict.set_item("asset_class", self.asset_class.to_string())?;
280        dict.set_item("currency", self.currency.code.to_string())?;
281        dict.set_item("activation_ns", self.activation_ns.as_u64())?;
282        dict.set_item("expiration_ns", self.expiration_ns.as_u64())?;
283        dict.set_item("price_precision", self.price_precision)?;
284        dict.set_item("size_precision", self.size_precision)?;
285        dict.set_item("price_increment", self.price_increment.to_string())?;
286        dict.set_item("size_increment", self.size_increment.to_string())?;
287        dict.set_item("margin_init", self.margin_init.to_string())?;
288        dict.set_item("margin_maint", self.margin_maint.to_string())?;
289        dict.set_item("maker_fee", self.maker_fee.to_string())?;
290        dict.set_item("taker_fee", self.taker_fee.to_string())?;
291        dict.set_item("ts_event", self.ts_event.as_u64())?;
292        dict.set_item("ts_init", self.ts_init.as_u64())?;
293        dict.set_item("info", PyDict::new(py))?;
294        match &self.outcome {
295            Some(value) => dict.set_item("outcome", value.to_string())?,
296            None => dict.set_item("outcome", py.None())?,
297        }
298        match &self.description {
299            Some(value) => dict.set_item("description", value.to_string())?,
300            None => dict.set_item("description", py.None())?,
301        }
302        match self.max_quantity {
303            Some(value) => dict.set_item("max_quantity", value.to_string())?,
304            None => dict.set_item("max_quantity", py.None())?,
305        }
306        match self.min_quantity {
307            Some(value) => dict.set_item("min_quantity", value.to_string())?,
308            None => dict.set_item("min_quantity", py.None())?,
309        }
310        match self.max_notional {
311            Some(value) => dict.set_item("max_notional", value.to_string())?,
312            None => dict.set_item("max_notional", py.None())?,
313        }
314        match self.min_notional {
315            Some(value) => dict.set_item("min_notional", value.to_string())?,
316            None => dict.set_item("min_notional", py.None())?,
317        }
318        match self.max_price {
319            Some(value) => dict.set_item("max_price", value.to_string())?,
320            None => dict.set_item("max_price", py.None())?,
321        }
322        match self.min_price {
323            Some(value) => dict.set_item("min_price", value.to_string())?,
324            None => dict.set_item("min_price", py.None())?,
325        }
326        Ok(dict.into())
327    }
328}
329
330////////////////////////////////////////////////////////////////////////////////
331// Tests
332////////////////////////////////////////////////////////////////////////////////
333#[cfg(test)]
334mod tests {
335    use pyo3::{prelude::*, prepare_freethreaded_python, types::PyDict};
336    use rstest::rstest;
337
338    use crate::instruments::{stubs::*, BinaryOption};
339
340    #[rstest]
341    fn test_dict_round_trip(binary_option: BinaryOption) {
342        prepare_freethreaded_python();
343        Python::with_gil(|py| {
344            let values = binary_option.py_to_dict(py).unwrap();
345            let values: Py<PyDict> = values.extract(py).unwrap();
346            let new_binary_option = BinaryOption::py_from_dict(py, values).unwrap();
347            assert_eq!(binary_option, new_binary_option);
348        })
349    }
350}