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 delta;
21pub mod deltas;
22pub mod depth;
23pub mod greeks;
24pub mod order;
25pub mod prices;
26pub mod quote;
27pub mod status;
28pub mod trade;
29
30use indexmap::IndexMap;
31#[cfg(feature = "ffi")]
32use nautilus_core::ffi::cvec::CVec;
33use pyo3::{exceptions::PyValueError, prelude::*, types::PyCapsule};
34
35use crate::data::{
36    Bar, Data, DataType, OrderBookDelta, QuoteTick, TradeTick, is_monotonically_increasing_by_init,
37};
38
39const ERROR_MONOTONICITY: &str = "`data` was not monotonically increasing by the `ts_init` field";
40
41#[pymethods]
42impl DataType {
43    #[new]
44    #[pyo3(signature = (type_name, metadata=None))]
45    fn py_new(type_name: &str, metadata: Option<IndexMap<String, String>>) -> Self {
46        Self::new(type_name, metadata)
47    }
48
49    #[getter]
50    #[pyo3(name = "type_name")]
51    fn py_type_name(&self) -> &str {
52        self.type_name()
53    }
54
55    #[getter]
56    #[pyo3(name = "metadata")]
57    fn py_metadata(&self) -> Option<IndexMap<String, String>> {
58        self.metadata().cloned()
59    }
60
61    #[getter]
62    #[pyo3(name = "topic")]
63    fn py_topic(&self) -> &str {
64        self.topic()
65    }
66}
67
68/// Creates a Python `PyCapsule` object containing a Rust `Data` instance.
69///
70/// This function takes ownership of the `Data` instance and encapsulates it within
71/// a `PyCapsule` object, allowing the Rust data to be passed into the Python runtime.
72///
73/// # Panics
74///
75/// This function will panic if the `PyCapsule` creation fails, which may occur if
76/// there are issues with memory allocation or if the `Data` instance cannot be
77/// properly encapsulated.
78///
79/// # Safety
80///
81/// This function is safe as long as the `Data` instance does not violate Rust's
82/// safety guarantees (e.g., no invalid memory access). Users of the
83/// `PyCapsule` in Python must ensure they understand how to extract and use the
84/// encapsulated `Data` safely, especially when converting the capsule back to a
85/// Rust data structure.
86#[must_use]
87pub fn data_to_pycapsule(py: Python, data: Data) -> PyObject {
88    let capsule = PyCapsule::new(py, data, None).expect("Error creating `PyCapsule`");
89    capsule.into_any().unbind()
90}
91
92/// Drops a `PyCapsule` containing a `CVec` structure.
93///
94/// This function safely extracts and drops the `CVec` instance encapsulated within
95/// a `PyCapsule` object. It is intended for cleaning up after the `Data` instances
96/// have been transferred into Python and are no longer needed.
97///
98/// # Panics
99///
100/// This function panics:
101/// - If the capsule cannot be downcast to a `PyCapsule`, indicating a type mismatch
102/// or improper capsule handling.
103///
104/// # Safety
105///
106/// This function is unsafe as it involves raw pointer dereferencing and manual memory
107/// management. The caller must ensure the `PyCapsule` contains a valid `CVec` pointer.
108/// Incorrect usage can lead to memory corruption or undefined behavior.
109#[pyfunction]
110#[cfg(feature = "ffi")]
111pub fn drop_cvec_pycapsule(capsule: &Bound<'_, PyAny>) {
112    let capsule: &Bound<'_, PyCapsule> = capsule
113        .downcast::<PyCapsule>()
114        .expect("Error on downcast to `&PyCapsule`");
115    let cvec: &CVec = unsafe { &*(capsule.pointer() as *const CVec) };
116    let data: Vec<Data> =
117        unsafe { Vec::from_raw_parts(cvec.ptr.cast::<Data>(), cvec.len, cvec.cap) };
118    drop(data);
119}
120
121#[pyfunction]
122#[cfg(not(feature = "ffi"))]
123pub fn drop_cvec_pycapsule(_capsule: &Bound<'_, PyAny>) {
124    panic!("`ffi` feature is not enabled");
125}
126
127/// Transforms the given `data` Python objects into a vector of [`OrderBookDelta`] objects.
128pub fn pyobjects_to_order_book_deltas(
129    data: Vec<Bound<'_, PyAny>>,
130) -> 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_quote_ticks(data: Vec<Bound<'_, PyAny>>) -> PyResult<Vec<QuoteTick>> {
146    let ticks: 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(&ticks) {
153        return Err(PyValueError::new_err(ERROR_MONOTONICITY));
154    }
155
156    Ok(ticks)
157}
158
159/// Transforms the given `data` Python objects into a vector of [`TradeTick`] objects.
160pub fn pyobjects_to_trade_ticks(data: Vec<Bound<'_, PyAny>>) -> PyResult<Vec<TradeTick>> {
161    let ticks: 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(&ticks) {
168        return Err(PyValueError::new_err(ERROR_MONOTONICITY));
169    }
170
171    Ok(ticks)
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}