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, serialization::from_dict_pyo3, 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, maker_fee=None, taker_fee=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        maker_fee: Option<Decimal>,
66        taker_fee: Option<Decimal>,
67        info: Option<Py<PyDict>>,
68    ) -> PyResult<Self> {
69        let info_map = if let Some(info_dict) = info {
70            Python::attach(|py| from_pydict(py, info_dict))?
71        } else {
72            None
73        };
74
75        Self::new_checked(
76            instrument_id,
77            raw_symbol,
78            asset_class,
79            base_currency,
80            quote_currency,
81            price_precision,
82            size_precision,
83            price_increment,
84            size_increment,
85            lot_size,
86            max_quantity,
87            min_quantity,
88            max_notional,
89            min_notional,
90            max_price,
91            min_price,
92            margin_init,
93            margin_maint,
94            maker_fee,
95            taker_fee,
96            info_map,
97            ts_event.into(),
98            ts_init.into(),
99        )
100        .map_err(to_pyvalue_err)
101    }
102
103    fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> Py<PyAny> {
104        match op {
105            CompareOp::Eq => self.eq(other).into_py_any_unwrap(py),
106            CompareOp::Ne => self.ne(other).into_py_any_unwrap(py),
107            _ => py.NotImplemented(),
108        }
109    }
110
111    fn __hash__(&self) -> isize {
112        let mut hasher = DefaultHasher::new();
113        self.hash(&mut hasher);
114        hasher.finish() as isize
115    }
116
117    #[getter]
118    fn type_name(&self) -> &'static str {
119        stringify!(Cfd)
120    }
121
122    #[getter]
123    #[pyo3(name = "id")]
124    fn py_id(&self) -> InstrumentId {
125        self.id
126    }
127
128    #[getter]
129    #[pyo3(name = "raw_symbol")]
130    fn py_raw_symbol(&self) -> Symbol {
131        self.raw_symbol
132    }
133
134    #[getter]
135    #[pyo3(name = "asset_class")]
136    fn py_asset_class(&self) -> AssetClass {
137        self.asset_class
138    }
139
140    #[getter]
141    #[pyo3(name = "base_currency")]
142    fn py_base_currency(&self) -> Option<Currency> {
143        self.base_currency
144    }
145
146    #[getter]
147    #[pyo3(name = "quote_currency")]
148    fn py_quote_currency(&self) -> Currency {
149        self.quote_currency
150    }
151
152    #[getter]
153    #[pyo3(name = "price_precision")]
154    fn py_price_precision(&self) -> u8 {
155        self.price_precision
156    }
157
158    #[getter]
159    #[pyo3(name = "size_precision")]
160    fn py_size_precision(&self) -> u8 {
161        self.size_precision
162    }
163
164    #[getter]
165    #[pyo3(name = "price_increment")]
166    fn py_price_increment(&self) -> Price {
167        self.price_increment
168    }
169
170    #[getter]
171    #[pyo3(name = "size_increment")]
172    fn py_size_increment(&self) -> Quantity {
173        self.size_increment
174    }
175
176    #[getter]
177    #[pyo3(name = "lot_size")]
178    fn py_lot_size(&self) -> Option<Quantity> {
179        self.lot_size
180    }
181
182    #[getter]
183    #[pyo3(name = "max_quantity")]
184    fn py_max_quantity(&self) -> Option<Quantity> {
185        self.max_quantity
186    }
187
188    #[getter]
189    #[pyo3(name = "min_quantity")]
190    fn py_min_quantity(&self) -> Option<Quantity> {
191        self.min_quantity
192    }
193
194    #[getter]
195    #[pyo3(name = "max_notional")]
196    fn py_max_notional(&self) -> Option<Money> {
197        self.max_notional
198    }
199
200    #[getter]
201    #[pyo3(name = "min_notional")]
202    fn py_min_notional(&self) -> Option<Money> {
203        self.min_notional
204    }
205
206    #[getter]
207    #[pyo3(name = "max_price")]
208    fn py_max_price(&self) -> Option<Price> {
209        self.max_price
210    }
211
212    #[getter]
213    #[pyo3(name = "min_price")]
214    fn py_min_price(&self) -> Option<Price> {
215        self.min_price
216    }
217
218    #[getter]
219    #[pyo3(name = "margin_init")]
220    fn py_margin_init(&self) -> Decimal {
221        self.margin_init
222    }
223
224    #[getter]
225    #[pyo3(name = "margin_maint")]
226    fn py_margin_maint(&self) -> Decimal {
227        self.margin_maint
228    }
229
230    #[getter]
231    #[pyo3(name = "maker_fee")]
232    fn py_maker_fee(&self) -> Decimal {
233        self.maker_fee
234    }
235
236    #[getter]
237    #[pyo3(name = "taker_fee")]
238    fn py_taker_fee(&self) -> Decimal {
239        self.taker_fee
240    }
241
242    #[getter]
243    #[pyo3(name = "ts_event")]
244    fn py_ts_event(&self) -> u64 {
245        self.ts_event.as_u64()
246    }
247
248    #[getter]
249    #[pyo3(name = "ts_init")]
250    fn py_ts_init(&self) -> u64 {
251        self.ts_init.as_u64()
252    }
253
254    #[getter]
255    #[pyo3(name = "info")]
256    fn py_info(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
257        if let Some(ref info_map) = self.info {
258            let py_dict = PyDict::new(py);
259
260            for (key, value) in info_map {
261                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
262                let py_value =
263                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
264                py_dict.set_item(key, py_value)?;
265            }
266            Ok(py_dict.unbind())
267        } else {
268            Ok(PyDict::new(py).unbind())
269        }
270    }
271
272    #[staticmethod]
273    #[pyo3(name = "from_dict")]
274    fn py_from_dict(py: Python<'_>, values: Py<PyDict>) -> PyResult<Self> {
275        from_dict_pyo3(py, values)
276    }
277
278    #[pyo3(name = "to_dict")]
279    fn py_to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
280        let dict = PyDict::new(py);
281        dict.set_item("type", stringify!(Cfd))?;
282        dict.set_item("id", self.id.to_string())?;
283        dict.set_item("raw_symbol", self.raw_symbol.to_string())?;
284        dict.set_item("asset_class", self.asset_class.to_string())?;
285        dict.set_item("quote_currency", self.quote_currency.code.to_string())?;
286        dict.set_item("price_precision", self.price_precision)?;
287        dict.set_item("size_precision", self.size_precision)?;
288        dict.set_item("price_increment", self.price_increment.to_string())?;
289        dict.set_item("size_increment", self.size_increment.to_string())?;
290        dict.set_item("ts_event", self.ts_event.as_u64())?;
291        dict.set_item("ts_init", self.ts_init.as_u64())?;
292
293        if let Some(ref info_map) = self.info {
294            let info_dict = PyDict::new(py);
295
296            for (key, value) in info_map {
297                let json_str = serde_json::to_string(value).map_err(to_pyvalue_err)?;
298                let py_value =
299                    PyModule::import(py, "json")?.call_method("loads", (json_str,), None)?;
300                info_dict.set_item(key, py_value)?;
301            }
302            dict.set_item("info", info_dict)?;
303        } else {
304            dict.set_item("info", PyDict::new(py))?;
305        }
306        dict.set_item("margin_init", self.margin_init.to_string())?;
307        dict.set_item("margin_maint", self.margin_maint.to_string())?;
308        dict.set_item("maker_fee", self.maker_fee.to_string())?;
309        dict.set_item("taker_fee", self.taker_fee.to_string())?;
310        match self.base_currency {
311            Some(value) => dict.set_item("base_currency", value.code.to_string())?,
312            None => dict.set_item("base_currency", py.None())?,
313        }
314
315        match self.lot_size {
316            Some(value) => dict.set_item("lot_size", value.to_string())?,
317            None => dict.set_item("lot_size", py.None())?,
318        }
319
320        match self.max_quantity {
321            Some(value) => dict.set_item("max_quantity", value.to_string())?,
322            None => dict.set_item("max_quantity", py.None())?,
323        }
324
325        match self.min_quantity {
326            Some(value) => dict.set_item("min_quantity", value.to_string())?,
327            None => dict.set_item("min_quantity", py.None())?,
328        }
329
330        match self.max_notional {
331            Some(value) => dict.set_item("max_notional", value.to_string())?,
332            None => dict.set_item("max_notional", py.None())?,
333        }
334
335        match self.min_notional {
336            Some(value) => dict.set_item("min_notional", value.to_string())?,
337            None => dict.set_item("min_notional", py.None())?,
338        }
339
340        match self.max_price {
341            Some(value) => dict.set_item("max_price", value.to_string())?,
342            None => dict.set_item("max_price", py.None())?,
343        }
344
345        match self.min_price {
346            Some(value) => dict.set_item("min_price", value.to_string())?,
347            None => dict.set_item("min_price", py.None())?,
348        }
349        Ok(dict.into())
350    }
351}