nautilus_model/python/data/
mod.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
16//! Data types for the trading domain model.
17
18pub mod bar;
19pub mod bet;
20pub mod close;
21pub mod delta;
22pub mod deltas;
23pub mod depth;
24pub mod greeks;
25pub mod order;
26pub mod prices;
27pub mod quote;
28pub mod status;
29pub mod trade;
30
31use indexmap::IndexMap;
32#[cfg(feature = "ffi")]
33use nautilus_core::ffi::cvec::CVec;
34use pyo3::{exceptions::PyValueError, prelude::*, types::PyCapsule};
35
36use crate::data::{
37    Bar, Data, DataType, IndexPriceUpdate, MarkPriceUpdate, OrderBookDelta, QuoteTick, TradeTick,
38    close::InstrumentClose, is_monotonically_increasing_by_init,
39};
40
41const ERROR_MONOTONICITY: &str = "`data` was not monotonically increasing by the `ts_init` field";
42
43#[pymethods]
44impl DataType {
45    #[new]
46    #[pyo3(signature = (type_name, metadata=None))]
47    fn py_new(type_name: &str, metadata: Option<IndexMap<String, String>>) -> Self {
48        Self::new(type_name, metadata)
49    }
50
51    #[getter]
52    #[pyo3(name = "type_name")]
53    fn py_type_name(&self) -> &str {
54        self.type_name()
55    }
56
57    #[getter]
58    #[pyo3(name = "metadata")]
59    fn py_metadata(&self) -> Option<IndexMap<String, String>> {
60        self.metadata().cloned()
61    }
62
63    #[getter]
64    #[pyo3(name = "topic")]
65    fn py_topic(&self) -> &str {
66        self.topic()
67    }
68}
69
70/// Creates a Python `PyCapsule` object containing a Rust `Data` instance.
71///
72/// This function takes ownership of the `Data` instance and encapsulates it within
73/// a `PyCapsule` object, allowing the Rust data to be passed into the Python runtime.
74///
75/// # Panics
76///
77/// This function will panic if the `PyCapsule` creation fails, which may occur if
78/// there are issues with memory allocation or if the `Data` instance cannot be
79/// properly encapsulated.
80///
81/// # Safety
82///
83/// This function is safe as long as the `Data` instance does not violate Rust's
84/// safety guarantees (e.g., no invalid memory access). Users of the
85/// `PyCapsule` in Python must ensure they understand how to extract and use the
86/// encapsulated `Data` safely, especially when converting the capsule back to a
87/// Rust data structure.
88#[must_use]
89pub fn data_to_pycapsule(py: Python, data: Data) -> PyObject {
90    let capsule = PyCapsule::new(py, data, None).expect("Error creating `PyCapsule`");
91    capsule.into_any().unbind()
92}
93
94/// Drops a `PyCapsule` containing a `CVec` structure.
95///
96/// This function safely extracts and drops the `CVec` instance encapsulated within
97/// a `PyCapsule` object. It is intended for cleaning up after the `Data` instances
98/// have been transferred into Python and are no longer needed.
99///
100/// # Panics
101///
102/// This function panics:
103/// - If the capsule cannot be downcast to a `PyCapsule`, indicating a type mismatch
104/// or improper capsule handling.
105///
106/// # Safety
107///
108/// This function is unsafe as it involves raw pointer dereferencing and manual memory
109/// management. The caller must ensure the `PyCapsule` contains a valid `CVec` pointer.
110/// Incorrect usage can lead to memory corruption or undefined behavior.
111#[pyfunction]
112#[cfg(feature = "ffi")]
113pub fn drop_cvec_pycapsule(capsule: &Bound<'_, PyAny>) {
114    let capsule: &Bound<'_, PyCapsule> = capsule
115        .downcast::<PyCapsule>()
116        .expect("Error on downcast to `&PyCapsule`");
117    let cvec: &CVec = unsafe { &*(capsule.pointer() as *const CVec) };
118    let data: Vec<Data> =
119        unsafe { Vec::from_raw_parts(cvec.ptr.cast::<Data>(), cvec.len, cvec.cap) };
120    drop(data);
121}
122
123#[pyfunction]
124#[cfg(not(feature = "ffi"))]
125pub fn drop_cvec_pycapsule(_capsule: &Bound<'_, PyAny>) {
126    panic!("`ffi` feature is not enabled");
127}
128
129/// Transforms the given `data` Python objects into a vector of [`OrderBookDelta`] objects.
130pub fn pyobjects_to_book_deltas(data: Vec<Bound<'_, PyAny>>) -> PyResult<Vec<OrderBookDelta>> {
131    let deltas: Vec<OrderBookDelta> = data
132        .into_iter()
133        .map(|obj| OrderBookDelta::from_pyobject(&obj))
134        .collect::<PyResult<Vec<OrderBookDelta>>>()?;
135
136    // Validate monotonically increasing
137    if !is_monotonically_increasing_by_init(&deltas) {
138        return Err(PyValueError::new_err(ERROR_MONOTONICITY));
139    }
140
141    Ok(deltas)
142}
143
144/// Transforms the given `data` Python objects into a vector of [`QuoteTick`] objects.
145pub fn pyobjects_to_quotes(data: Vec<Bound<'_, PyAny>>) -> PyResult<Vec<QuoteTick>> {
146    let quotes: Vec<QuoteTick> = data
147        .into_iter()
148        .map(|obj| QuoteTick::from_pyobject(&obj))
149        .collect::<PyResult<Vec<QuoteTick>>>()?;
150
151    // Validate monotonically increasing
152    if !is_monotonically_increasing_by_init(&quotes) {
153        return Err(PyValueError::new_err(ERROR_MONOTONICITY));
154    }
155
156    Ok(quotes)
157}
158
159/// Transforms the given `data` Python objects into a vector of [`TradeTick`] objects.
160pub fn pyobjects_to_trades(data: Vec<Bound<'_, PyAny>>) -> PyResult<Vec<TradeTick>> {
161    let trades: Vec<TradeTick> = data
162        .into_iter()
163        .map(|obj| TradeTick::from_pyobject(&obj))
164        .collect::<PyResult<Vec<TradeTick>>>()?;
165
166    // Validate monotonically increasing
167    if !is_monotonically_increasing_by_init(&trades) {
168        return Err(PyValueError::new_err(ERROR_MONOTONICITY));
169    }
170
171    Ok(trades)
172}
173
174/// Transforms the given `data` Python objects into a vector of [`Bar`] objects.
175pub fn pyobjects_to_bars(data: Vec<Bound<'_, PyAny>>) -> PyResult<Vec<Bar>> {
176    let bars: Vec<Bar> = data
177        .into_iter()
178        .map(|obj| Bar::from_pyobject(&obj))
179        .collect::<PyResult<Vec<Bar>>>()?;
180
181    // Validate monotonically increasing
182    if !is_monotonically_increasing_by_init(&bars) {
183        return Err(PyValueError::new_err(ERROR_MONOTONICITY));
184    }
185
186    Ok(bars)
187}
188
189/// Transforms the given `data` Python objects into a vector of [`MarkPriceUpdate`] objects.
190pub fn pyobjects_to_mark_prices(data: Vec<Bound<'_, PyAny>>) -> PyResult<Vec<MarkPriceUpdate>> {
191    let mark_prices: Vec<MarkPriceUpdate> = data
192        .into_iter()
193        .map(|obj| MarkPriceUpdate::from_pyobject(&obj))
194        .collect::<PyResult<Vec<MarkPriceUpdate>>>()?;
195
196    // Validate monotonically increasing
197    if !is_monotonically_increasing_by_init(&mark_prices) {
198        return Err(PyValueError::new_err(ERROR_MONOTONICITY));
199    }
200
201    Ok(mark_prices)
202}
203
204/// Transforms the given `data` Python objects into a vector of [`IndexPriceUpdate`] objects.
205pub fn pyobjects_to_index_prices(data: Vec<Bound<'_, PyAny>>) -> PyResult<Vec<IndexPriceUpdate>> {
206    let index_prices: Vec<IndexPriceUpdate> = data
207        .into_iter()
208        .map(|obj| IndexPriceUpdate::from_pyobject(&obj))
209        .collect::<PyResult<Vec<IndexPriceUpdate>>>()?;
210
211    // Validate monotonically increasing
212    if !is_monotonically_increasing_by_init(&index_prices) {
213        return Err(PyValueError::new_err(ERROR_MONOTONICITY));
214    }
215
216    Ok(index_prices)
217}
218
219/// Transforms the given `data` Python objects into a vector of [`InstrumentClose`] objects.
220pub fn pyobjects_to_instrument_closes(
221    data: Vec<Bound<'_, PyAny>>,
222) -> PyResult<Vec<InstrumentClose>> {
223    let closes: Vec<InstrumentClose> = data
224        .into_iter()
225        .map(|obj| InstrumentClose::from_pyobject(&obj))
226        .collect::<PyResult<Vec<InstrumentClose>>>()?;
227
228    // Validate monotonically increasing
229    if !is_monotonically_increasing_by_init(&closes) {
230        return Err(PyValueError::new_err(ERROR_MONOTONICITY));
231    }
232
233    Ok(closes)
234}