nautilus_serialization/python/
arrow.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.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::io::Cursor;
17
18use arrow::{ipc::writer::StreamWriter, record_batch::RecordBatch};
19use nautilus_core::python::to_pyvalue_err;
20use nautilus_model::{
21    data::{
22        Bar, IndexPriceUpdate, MarkPriceUpdate, OrderBookDelta, OrderBookDepth10, QuoteTick,
23        TradeTick, close::InstrumentClose,
24    },
25    python::data::{
26        pyobjects_to_bars, pyobjects_to_book_deltas, pyobjects_to_index_prices,
27        pyobjects_to_mark_prices, pyobjects_to_quotes, pyobjects_to_trades,
28    },
29};
30use pyo3::{
31    conversion::IntoPyObjectExt,
32    exceptions::{PyRuntimeError, PyTypeError, PyValueError},
33    prelude::*,
34    types::{PyBytes, PyType},
35};
36
37use crate::arrow::{
38    ArrowSchemaProvider, bars_to_arrow_record_batch_bytes, book_deltas_to_arrow_record_batch_bytes,
39    book_depth10_to_arrow_record_batch_bytes, index_prices_to_arrow_record_batch_bytes,
40    instrument_closes_to_arrow_record_batch_bytes, mark_prices_to_arrow_record_batch_bytes,
41    quotes_to_arrow_record_batch_bytes, trades_to_arrow_record_batch_bytes,
42};
43
44/// Transforms the given record `batches` into Python `bytes`.
45fn arrow_record_batch_to_pybytes(py: Python, batch: RecordBatch) -> PyResult<Py<PyBytes>> {
46    // Create a cursor to write to a byte array in memory
47    let mut cursor = Cursor::new(Vec::new());
48    {
49        let mut writer = StreamWriter::try_new(&mut cursor, &batch.schema())
50            .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
51
52        writer
53            .write(&batch)
54            .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
55
56        writer
57            .finish()
58            .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
59    }
60
61    let buffer = cursor.into_inner();
62    let pybytes = PyBytes::new(py, &buffer);
63
64    Ok(pybytes.into())
65}
66
67/// Returns a mapping from field names to Arrow data types for the given Rust data class.
68///
69/// # Errors
70///
71/// Returns a `PyErr` if the class name is not recognized or schema extraction fails.
72#[pyfunction]
73pub fn get_arrow_schema_map(py: Python<'_>, cls: &Bound<'_, PyType>) -> PyResult<Py<PyAny>> {
74    let cls_str: String = cls.getattr("__name__")?.extract()?;
75    let result_map = match cls_str.as_str() {
76        stringify!(OrderBookDelta) => OrderBookDelta::get_schema_map(),
77        stringify!(OrderBookDepth10) => OrderBookDepth10::get_schema_map(),
78        stringify!(QuoteTick) => QuoteTick::get_schema_map(),
79        stringify!(TradeTick) => TradeTick::get_schema_map(),
80        stringify!(Bar) => Bar::get_schema_map(),
81        stringify!(MarkPriceUpdate) => MarkPriceUpdate::get_schema_map(),
82        stringify!(IndexPriceUpdate) => IndexPriceUpdate::get_schema_map(),
83        _ => {
84            return Err(PyTypeError::new_err(format!(
85                "Arrow schema for `{cls_str}` is not currently implemented in Rust."
86            )));
87        }
88    };
89
90    result_map.into_py_any(py)
91}
92
93/// Returns Python `bytes` from the given list of legacy data objects, which can be passed
94/// to `pa.ipc.open_stream` to create a `RecordBatchReader`.
95///
96/// # Errors
97///
98/// Returns an error if:
99/// - The input list is empty: `PyErr`.
100/// - An unsupported data type is encountered or conversion fails: `PyErr`.
101///
102/// # Panics
103///
104/// Panics if `data.first()` returns `None` (should not occur due to emptiness check).
105#[pyfunction]
106pub fn pyobjects_to_arrow_record_batch_bytes(
107    py: Python,
108    data: Vec<Bound<'_, PyAny>>,
109) -> PyResult<Py<PyBytes>> {
110    if data.is_empty() {
111        return Err(to_pyvalue_err("Empty data"));
112    }
113
114    let data_type: String = data
115        .first()
116        .unwrap() // SAFETY: Unwrap safe as already checked that `data` not empty
117        .as_ref()
118        .getattr("__class__")?
119        .getattr("__name__")?
120        .extract()?;
121
122    match data_type.as_str() {
123        stringify!(OrderBookDelta) => {
124            let deltas = pyobjects_to_book_deltas(data)?;
125            py_book_deltas_to_arrow_record_batch_bytes(py, deltas)
126        }
127        stringify!(QuoteTick) => {
128            let quotes = pyobjects_to_quotes(data)?;
129            py_quotes_to_arrow_record_batch_bytes(py, quotes)
130        }
131        stringify!(TradeTick) => {
132            let trades = pyobjects_to_trades(data)?;
133            py_trades_to_arrow_record_batch_bytes(py, trades)
134        }
135        stringify!(Bar) => {
136            let bars = pyobjects_to_bars(data)?;
137            py_bars_to_arrow_record_batch_bytes(py, bars)
138        }
139        stringify!(MarkPriceUpdate) => {
140            let updates = pyobjects_to_mark_prices(data)?;
141            py_mark_prices_to_arrow_record_batch_bytes(py, updates)
142        }
143        stringify!(IndexPriceUpdate) => {
144            let index_prices = pyobjects_to_index_prices(data)?;
145            py_index_prices_to_arrow_record_batch_bytes(py, index_prices)
146        }
147        stringify!(InstrumentClose) => {
148            let closes = pyobjects_to_index_prices(data)?;
149            py_index_prices_to_arrow_record_batch_bytes(py, closes)
150        }
151        _ => Err(PyValueError::new_err(format!(
152            "unsupported data type: {data_type}"
153        ))),
154    }
155}
156
157/// Converts a list of `OrderBookDelta` into Arrow IPC bytes for Python.
158///
159/// # Errors
160///
161/// Returns a `PyErr` if encoding fails.
162#[pyfunction(name = "book_deltas_to_arrow_record_batch_bytes")]
163pub fn py_book_deltas_to_arrow_record_batch_bytes(
164    py: Python,
165    data: Vec<OrderBookDelta>,
166) -> PyResult<Py<PyBytes>> {
167    match book_deltas_to_arrow_record_batch_bytes(data) {
168        Ok(batch) => arrow_record_batch_to_pybytes(py, batch),
169        Err(e) => Err(to_pyvalue_err(e)),
170    }
171}
172
173/// Converts a list of `OrderBookDepth10` into Arrow IPC bytes for Python.
174///
175/// # Errors
176///
177/// Returns a `PyErr` if encoding fails.
178#[pyfunction(name = "book_depth10_to_arrow_record_batch_bytes")]
179pub fn py_book_depth10_to_arrow_record_batch_bytes(
180    py: Python,
181    data: Vec<OrderBookDepth10>,
182) -> PyResult<Py<PyBytes>> {
183    match book_depth10_to_arrow_record_batch_bytes(data) {
184        Ok(batch) => arrow_record_batch_to_pybytes(py, batch),
185        Err(e) => Err(to_pyvalue_err(e)),
186    }
187}
188
189/// Converts a list of `QuoteTick` into Arrow IPC bytes for Python.
190///
191/// # Errors
192///
193/// Returns a `PyErr` if encoding fails.
194#[pyfunction(name = "quotes_to_arrow_record_batch_bytes")]
195pub fn py_quotes_to_arrow_record_batch_bytes(
196    py: Python,
197    data: Vec<QuoteTick>,
198) -> PyResult<Py<PyBytes>> {
199    match quotes_to_arrow_record_batch_bytes(data) {
200        Ok(batch) => arrow_record_batch_to_pybytes(py, batch),
201        Err(e) => Err(to_pyvalue_err(e)),
202    }
203}
204
205/// Converts a list of `TradeTick` into Arrow IPC bytes for Python.
206///
207/// # Errors
208///
209/// Returns a `PyErr` if encoding fails.
210#[pyfunction(name = "trades_to_arrow_record_batch_bytes")]
211pub fn py_trades_to_arrow_record_batch_bytes(
212    py: Python,
213    data: Vec<TradeTick>,
214) -> PyResult<Py<PyBytes>> {
215    match trades_to_arrow_record_batch_bytes(data) {
216        Ok(batch) => arrow_record_batch_to_pybytes(py, batch),
217        Err(e) => Err(to_pyvalue_err(e)),
218    }
219}
220
221/// Converts a list of `Bar` into Arrow IPC bytes for Python.
222///
223/// # Errors
224///
225/// Returns a `PyErr` if encoding fails.
226#[pyfunction(name = "bars_to_arrow_record_batch_bytes")]
227pub fn py_bars_to_arrow_record_batch_bytes(py: Python, data: Vec<Bar>) -> PyResult<Py<PyBytes>> {
228    match bars_to_arrow_record_batch_bytes(data) {
229        Ok(batch) => arrow_record_batch_to_pybytes(py, batch),
230        Err(e) => Err(to_pyvalue_err(e)),
231    }
232}
233
234/// Converts a list of `MarkPriceUpdate` into Arrow IPC bytes for Python.
235///
236/// # Errors
237///
238/// Returns a `PyErr` if encoding fails.
239#[pyfunction(name = "mark_prices_to_arrow_record_batch_bytes")]
240pub fn py_mark_prices_to_arrow_record_batch_bytes(
241    py: Python,
242    data: Vec<MarkPriceUpdate>,
243) -> PyResult<Py<PyBytes>> {
244    match mark_prices_to_arrow_record_batch_bytes(data) {
245        Ok(batch) => arrow_record_batch_to_pybytes(py, batch),
246        Err(e) => Err(to_pyvalue_err(e)),
247    }
248}
249
250/// Converts a list of `IndexPriceUpdate` into Arrow IPC bytes for Python.
251///
252/// # Errors
253///
254/// Returns a `PyErr` if encoding fails.
255#[pyfunction(name = "index_prices_to_arrow_record_batch_bytes")]
256pub fn py_index_prices_to_arrow_record_batch_bytes(
257    py: Python,
258    data: Vec<IndexPriceUpdate>,
259) -> PyResult<Py<PyBytes>> {
260    match index_prices_to_arrow_record_batch_bytes(data) {
261        Ok(batch) => arrow_record_batch_to_pybytes(py, batch),
262        Err(e) => Err(to_pyvalue_err(e)),
263    }
264}
265
266/// Converts a list of `InstrumentClose` into Arrow IPC bytes for Python.
267///
268/// # Errors
269///
270/// Returns a `PyErr` if encoding fails.
271#[pyfunction(name = "instrument_closes_to_arrow_record_batch_bytes")]
272pub fn py_instrument_closes_to_arrow_record_batch_bytes(
273    py: Python,
274    data: Vec<InstrumentClose>,
275) -> PyResult<Py<PyBytes>> {
276    match instrument_closes_to_arrow_record_batch_bytes(data) {
277        Ok(batch) => arrow_record_batch_to_pybytes(py, batch),
278        Err(e) => Err(to_pyvalue_err(e)),
279    }
280}