Skip to main content

nautilus_model/python/instruments/
cfd.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;
27
28use crate::{
29    enums::AssetClass,
30    identifiers::{InstrumentId, Symbol},
31    instruments::Cfd,
32    types::{Currency, Money, Price, Quantity},
33};
34
35#[pymethods]
36#[pyo3_stub_gen::derive::gen_stub_pymethods]
37impl Cfd {
38    /// Represents a Contract for Difference (CFD) instrument.
39    ///
40    /// Can represent both Fiat FX and Cryptocurrency pairs.
41    #[expect(clippy::too_many_arguments)]
42    #[new]
43    #[pyo3(signature = (instrument_id, raw_symbol, asset_class, quote_currency, price_precision, size_precision, price_increment, size_increment, ts_event, ts_init, base_currency=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, tick_scheme=None, info=None))]
44    fn py_new(
45        instrument_id: InstrumentId,
46        raw_symbol: Symbol,
47        asset_class: AssetClass,
48        quote_currency: Currency,
49        price_precision: u8,
50        size_precision: u8,
51        price_increment: Price,
52        size_increment: Quantity,
53        ts_event: u64,
54        ts_init: u64,
55        base_currency: Option<Currency>,
56        lot_size: Option<Quantity>,
57        max_quantity: Option<Quantity>,
58        min_quantity: Option<Quantity>,
59        max_notional: Option<Money>,
60        min_notional: Option<Money>,
61        max_price: Option<Price>,
62        min_price: Option<Price>,
63        margin_init: Option<Decimal>,
64        margin_maint: Option<Decimal>,
65        tick_scheme: Option<String>,
66        info: Option<Py<PyDict>>,
67    ) -> PyResult<Self> {
68        let info_map = if let Some(info_dict) = info {
69            Python::attach(|py| from_pydict(py, &info_dict))?
70        } else {
71            None
72        };
73
74        Self::builder()
75            .instrument_id(instrument_id)
76            .raw_symbol(raw_symbol)
77            .asset_class(asset_class)
78            .maybe_base_currency(base_currency)
79            .quote_currency(quote_currency)
80            .price_precision(price_precision)
81            .size_precision(size_precision)
82            .price_increment(price_increment)
83            .size_increment(size_increment)
84            .maybe_lot_size(lot_size)
85            .maybe_max_quantity(max_quantity)
86            .maybe_min_quantity(min_quantity)
87            .maybe_max_notional(max_notional)
88            .maybe_min_notional(min_notional)
89            .maybe_max_price(max_price)
90            .maybe_min_price(min_price)
91            .maybe_margin_init(margin_init)
92            .maybe_margin_maint(margin_maint)
93            .maybe_tick_scheme(tick_scheme.map(|name| ustr::Ustr::from(name.as_str())))
94            .maybe_info(info_map)
95            .ts_event(ts_event.into())
96            .ts_init(ts_init.into())
97            .build()
98            .map_err(to_pyvalue_err)
99    }
100
101    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
102        match op {
103            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
104            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
105            _ => py.NotImplemented(),
106        }
107    }
108
109    fn __hash__(&self) -> isize {
110        let mut hasher = DefaultHasher::new();
111        self.hash(&mut hasher);
112        hasher.finish() as isize
113    }
114
115    #[getter]
116    fn type_name(&self) -> &'static str {
117        stringify!(Cfd)
118    }
119
120    #[getter]
121    #[pyo3(name = "id")]
122    fn py_id(&self) -> InstrumentId {
123        self.id
124    }
125
126    #[getter]
127    #[pyo3(name = "raw_symbol")]
128    fn py_raw_symbol(&self) -> Symbol {
129        self.raw_symbol
130    }
131
132    #[getter]
133    #[pyo3(name = "asset_class")]
134    fn py_asset_class(&self) -> AssetClass {
135        self.asset_class
136    }
137
138    #[getter]
139    #[pyo3(name = "base_currency")]
140    fn py_base_currency(&self) -> Option<Currency> {
141        self.base_currency
142    }
143
144    #[getter]
145    #[pyo3(name = "quote_currency")]
146    fn py_quote_currency(&self) -> Currency {
147        self.quote_currency
148    }
149
150    #[getter]
151    #[pyo3(name = "price_precision")]
152    fn py_price_precision(&self) -> u8 {
153        self.price_precision
154    }
155
156    #[getter]
157    #[pyo3(name = "size_precision")]
158    fn py_size_precision(&self) -> u8 {
159        self.size_precision
160    }
161
162    #[getter]
163    #[pyo3(name = "price_increment")]
164    fn py_price_increment(&self) -> Price {
165        self.price_increment
166    }
167
168    #[getter]
169    #[pyo3(name = "size_increment")]
170    fn py_size_increment(&self) -> Quantity {
171        self.size_increment
172    }
173
174    #[getter]
175    #[pyo3(name = "lot_size")]
176    fn py_lot_size(&self) -> Option<Quantity> {
177        self.lot_size
178    }
179
180    #[getter]
181    #[pyo3(name = "max_quantity")]
182    fn py_max_quantity(&self) -> Option<Quantity> {
183        self.max_quantity
184    }
185
186    #[getter]
187    #[pyo3(name = "min_quantity")]
188    fn py_min_quantity(&self) -> Option<Quantity> {
189        self.min_quantity
190    }
191
192    #[getter]
193    #[pyo3(name = "max_notional")]
194    fn py_max_notional(&self) -> Option<Money> {
195        self.max_notional
196    }
197
198    #[getter]
199    #[pyo3(name = "min_notional")]
200    fn py_min_notional(&self) -> Option<Money> {
201        self.min_notional
202    }
203
204    #[getter]
205    #[pyo3(name = "max_price")]
206    fn py_max_price(&self) -> Option<Price> {
207        self.max_price
208    }
209
210    #[getter]
211    #[pyo3(name = "min_price")]
212    fn py_min_price(&self) -> Option<Price> {
213        self.min_price
214    }
215
216    #[getter]
217    #[pyo3(name = "margin_init")]
218    fn py_margin_init(&self) -> Decimal {
219        self.margin_init
220    }
221
222    #[getter]
223    #[pyo3(name = "margin_maint")]
224    fn py_margin_maint(&self) -> Decimal {
225        self.margin_maint
226    }
227
228    #[getter]
229    #[pyo3(name = "ts_event")]
230    fn py_ts_event(&self) -> u64 {
231        self.ts_event.as_u64()
232    }
233
234    #[getter]
235    #[pyo3(name = "ts_init")]
236    fn py_ts_init(&self) -> u64 {
237        self.ts_init.as_u64()
238    }
239
240    #[getter]
241    #[pyo3(name = "info")]
242    fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
243        if let Some(ref info_map) = self.info {
244            let py_dict = PyDict::new(py);
245
246            for (key, value) in info_map {
247                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
248                let py_value =
249                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
250                py_dict.set_item(key, py_value)?;
251            }
252            Ok(py_dict.unbind())
253        } else {
254            Ok(PyDict::new(py).unbind())
255        }
256    }
257
258    #[staticmethod]
259    #[pyo3(name = "from_dict")]
260    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
261        crate::python::instruments::from_dict_instrument_pyo3(py, values)
262    }
263
264    #[pyo3(name = "to_dict")]
265    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
266        let dict = PyDict::new(py);
267        dict.set_item("type", stringify!(Cfd))?;
268        dict.set_item("id", self.id.to_string())?;
269        dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
270        dict.set_item("asset_class", self.asset_class.to_string())?;
271        dict.set_item("quote_currency", self.quote_currency.code.to_string())?;
272        dict.set_item("price_precision", self.price_precision)?;
273        dict.set_item("size_precision", self.size_precision)?;
274        dict.set_item("price_increment", self.price_increment.to_string())?;
275        dict.set_item("size_increment", self.size_increment.to_string())?;
276        dict.set_item("ts_event", self.ts_event.as_u64())?;
277        dict.set_item("ts_init", self.ts_init.as_u64())?;
278
279        if let Some(ref info_map) = self.info {
280            let info_dict = PyDict::new(py);
281
282            for (key, value) in info_map {
283                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
284                let py_value =
285                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
286                info_dict.set_item(key, py_value)?;
287            }
288            dict.set_item("info", info_dict)?;
289        } else {
290            dict.set_item("info", PyDict::new(py))?;
291        }
292        dict.set_item("margin_init", self.margin_init.to_string())?;
293        dict.set_item("margin_maint", self.margin_maint.to_string())?;
294        match self.base_currency {
295            Some(value) => dict.set_item("base_currency", value.code.to_string())?,
296            None => dict.set_item("base_currency", py.None())?,
297        }
298
299        match self.lot_size {
300            Some(value) => dict.set_item("lot_size", value.to_string())?,
301            None => dict.set_item("lot_size", py.None())?,
302        }
303
304        match self.max_quantity {
305            Some(value) => dict.set_item("max_quantity", value.to_string())?,
306            None => dict.set_item("max_quantity", py.None())?,
307        }
308
309        match self.min_quantity {
310            Some(value) => dict.set_item("min_quantity", value.to_string())?,
311            None => dict.set_item("min_quantity", py.None())?,
312        }
313
314        match self.max_notional {
315            Some(value) => dict.set_item("max_notional", value.to_string())?,
316            None => dict.set_item("max_notional", py.None())?,
317        }
318
319        match self.min_notional {
320            Some(value) => dict.set_item("min_notional", value.to_string())?,
321            None => dict.set_item("min_notional", py.None())?,
322        }
323
324        match self.max_price {
325            Some(value) => dict.set_item("max_price", value.to_string())?,
326            None => dict.set_item("max_price", py.None())?,
327        }
328
329        match self.min_price {
330            Some(value) => dict.set_item("min_price", value.to_string())?,
331            None => dict.set_item("min_price", py.None())?,
332        }
333        dict.set_item(
334            "tick_scheme",
335            crate::python::instruments::tick_scheme_to_py(self),
336        )?;
337        Ok(dict.into())
338    }
339}