nautilus_databento/python/
live.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//! Python bindings for the Databento live client.
17
18use std::{
19    fs,
20    path::PathBuf,
21    str::FromStr,
22    sync::{Arc, RwLock},
23};
24
25use ahash::AHashMap;
26use databento::{dbn, live::Subscription};
27use indexmap::IndexMap;
28use nautilus_core::python::{IntoPyObjectNautilusExt, to_pyruntime_err, to_pyvalue_err};
29use nautilus_model::{
30    identifiers::{InstrumentId, Symbol, Venue},
31    python::{data::data_to_pycapsule, instruments::instrument_any_to_pyobject},
32};
33use pyo3::prelude::*;
34use time::OffsetDateTime;
35
36use crate::{
37    live::{DatabentoFeedHandler, LiveCommand, LiveMessage},
38    symbology::{check_consistent_symbology, infer_symbology_type, instrument_id_to_symbol_string},
39    types::DatabentoPublisher,
40};
41
42#[cfg_attr(
43    feature = "python",
44    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.databento")
45)]
46#[derive(Debug)]
47pub struct DatabentoLiveClient {
48    #[pyo3(get)]
49    pub key: String,
50    #[pyo3(get)]
51    pub dataset: String,
52    is_running: bool,
53    is_closed: bool,
54    cmd_tx: tokio::sync::mpsc::UnboundedSender<LiveCommand>,
55    cmd_rx: Option<tokio::sync::mpsc::UnboundedReceiver<LiveCommand>>,
56    buffer_size: usize,
57    publisher_venue_map: IndexMap<u16, Venue>,
58    symbol_venue_map: Arc<RwLock<AHashMap<Symbol, Venue>>>,
59    use_exchange_as_venue: bool,
60    bars_timestamp_on_close: bool,
61}
62
63impl DatabentoLiveClient {
64    #[must_use]
65    pub fn is_closed(&self) -> bool {
66        self.cmd_tx.is_closed()
67    }
68
69    async fn process_messages(
70        mut msg_rx: tokio::sync::mpsc::Receiver<LiveMessage>,
71        callback: PyObject,
72        callback_pyo3: PyObject,
73    ) -> PyResult<()> {
74        tracing::debug!("Processing messages...");
75        // Continue to process messages until channel is hung up
76        while let Some(msg) = msg_rx.recv().await {
77            tracing::trace!("Received message: {msg:?}");
78            match msg {
79                LiveMessage::Data(data) => Python::with_gil(|py| {
80                    let py_obj = data_to_pycapsule(py, data);
81                    call_python(py, &callback, py_obj);
82                }),
83                LiveMessage::Instrument(data) => {
84                    Python::with_gil(|py| match instrument_any_to_pyobject(py, data) {
85                        Ok(py_obj) => call_python(py, &callback, py_obj),
86                        Err(e) => tracing::error!("Failed creating instrument: {e}"),
87                    });
88                }
89                LiveMessage::Status(data) => Python::with_gil(|py| {
90                    let py_obj = data.into_py_any_unwrap(py);
91                    call_python(py, &callback_pyo3, py_obj);
92                }),
93                LiveMessage::Imbalance(data) => Python::with_gil(|py| {
94                    let py_obj = data.into_py_any_unwrap(py);
95                    call_python(py, &callback_pyo3, py_obj);
96                }),
97                LiveMessage::Statistics(data) => Python::with_gil(|py| {
98                    let py_obj = data.into_py_any_unwrap(py);
99                    call_python(py, &callback_pyo3, py_obj);
100                }),
101                LiveMessage::Close => {
102                    // Graceful close
103                    break;
104                }
105                LiveMessage::Error(e) => {
106                    // Return error to Python
107                    return Err(to_pyruntime_err(e));
108                }
109            }
110        }
111
112        msg_rx.close();
113        tracing::debug!("Closed message receiver");
114
115        Ok(())
116    }
117
118    fn send_command(&self, cmd: LiveCommand) -> PyResult<()> {
119        self.cmd_tx.send(cmd).map_err(to_pyruntime_err)
120    }
121}
122
123fn call_python(py: Python, callback: &PyObject, py_obj: PyObject) {
124    if let Err(e) = callback.call1(py, (py_obj,)) {
125        // TODO: Improve this by checking for the actual exception type
126        if !e.to_string().contains("CancelledError") {
127            tracing::error!("Error calling Python: {e}");
128        }
129    }
130}
131
132#[pymethods]
133impl DatabentoLiveClient {
134    /// # Errors
135    ///
136    /// Returns a `PyErr` if reading or parsing the publishers file fails.
137    #[new]
138    pub fn py_new(
139        key: String,
140        dataset: String,
141        publishers_filepath: PathBuf,
142        use_exchange_as_venue: bool,
143        bars_timestamp_on_close: Option<bool>,
144    ) -> PyResult<Self> {
145        let publishers_json = fs::read_to_string(publishers_filepath).map_err(to_pyvalue_err)?;
146        let publishers_vec: Vec<DatabentoPublisher> =
147            serde_json::from_str(&publishers_json).map_err(to_pyvalue_err)?;
148        let publisher_venue_map = publishers_vec
149            .into_iter()
150            .map(|p| (p.publisher_id, Venue::from(p.venue.as_str())))
151            .collect::<IndexMap<u16, Venue>>();
152
153        let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel::<LiveCommand>();
154
155        // Hard-coded to a reasonable size for now
156        let buffer_size = 100_000;
157
158        Ok(Self {
159            key,
160            dataset,
161            cmd_tx,
162            cmd_rx: Some(cmd_rx),
163            buffer_size,
164            is_running: false,
165            is_closed: false,
166            publisher_venue_map,
167            symbol_venue_map: Arc::new(RwLock::new(AHashMap::new())),
168            use_exchange_as_venue,
169            bars_timestamp_on_close: bars_timestamp_on_close.unwrap_or(true),
170        })
171    }
172
173    #[pyo3(name = "is_running")]
174    const fn py_is_running(&self) -> bool {
175        self.is_running
176    }
177
178    #[pyo3(name = "is_closed")]
179    const fn py_is_closed(&self) -> bool {
180        self.is_closed
181    }
182
183    #[pyo3(name = "subscribe")]
184    #[pyo3(signature = (schema, instrument_ids, start=None, snapshot=None))]
185    fn py_subscribe(
186        &mut self,
187        schema: String,
188        instrument_ids: Vec<InstrumentId>,
189        start: Option<u64>,
190        snapshot: Option<bool>,
191    ) -> PyResult<()> {
192        let mut symbol_venue_map = self
193            .symbol_venue_map
194            .write()
195            .map_err(|e| to_pyruntime_err(format!("symbol_venue_map lock poisoned: {e}")))?;
196        let symbols: Vec<String> = instrument_ids
197            .iter()
198            .map(|instrument_id| {
199                instrument_id_to_symbol_string(*instrument_id, &mut symbol_venue_map)
200            })
201            .collect();
202        let first_symbol = symbols
203            .first()
204            .ok_or_else(|| to_pyvalue_err("No symbols provided"))?;
205        let stype_in = infer_symbology_type(first_symbol);
206        let symbols: Vec<&str> = symbols.iter().map(String::as_str).collect();
207        check_consistent_symbology(symbols.as_slice()).map_err(to_pyvalue_err)?;
208        let mut sub = Subscription::builder()
209            .symbols(symbols)
210            .schema(dbn::Schema::from_str(&schema).map_err(to_pyvalue_err)?)
211            .stype_in(stype_in)
212            .build();
213
214        if let Some(start) = start {
215            let start = OffsetDateTime::from_unix_timestamp_nanos(i128::from(start))
216                .map_err(to_pyvalue_err)?;
217            sub.start = Some(start);
218        }
219        sub.use_snapshot = snapshot.unwrap_or(false);
220
221        self.send_command(LiveCommand::Subscribe(sub))
222    }
223
224    #[pyo3(name = "start")]
225    fn py_start<'py>(
226        &mut self,
227        py: Python<'py>,
228        callback: PyObject,
229        callback_pyo3: PyObject,
230    ) -> PyResult<Bound<'py, PyAny>> {
231        if self.is_closed {
232            return Err(to_pyruntime_err("Client already closed"));
233        }
234        if self.is_running {
235            return Err(to_pyruntime_err("Client already running"));
236        }
237
238        tracing::debug!("Starting client");
239
240        self.is_running = true;
241
242        let (msg_tx, msg_rx) = tokio::sync::mpsc::channel::<LiveMessage>(self.buffer_size);
243
244        // Consume the receiver
245        // SAFETY: We guard the client from being started more than once with the
246        // `is_running` flag, so here it is safe to unwrap the command receiver.
247        let cmd_rx = self
248            .cmd_rx
249            .take()
250            .ok_or_else(|| to_pyruntime_err("Command receiver already taken"))?;
251
252        let mut feed_handler = DatabentoFeedHandler::new(
253            self.key.clone(),
254            self.dataset.clone(),
255            cmd_rx,
256            msg_tx,
257            self.publisher_venue_map.clone(),
258            self.symbol_venue_map.clone(),
259            self.use_exchange_as_venue,
260            self.bars_timestamp_on_close,
261        );
262
263        self.send_command(LiveCommand::Start)?;
264
265        pyo3_async_runtimes::tokio::future_into_py(py, async move {
266            let (proc_handle, feed_handle) = tokio::join!(
267                Self::process_messages(msg_rx, callback, callback_pyo3),
268                feed_handler.run(),
269            );
270
271            match proc_handle {
272                Ok(()) => tracing::debug!("Message processor completed"),
273                Err(e) => tracing::error!("Message processor error: {e}"),
274            }
275
276            match feed_handle {
277                Ok(()) => tracing::debug!("Feed handler completed"),
278                Err(e) => tracing::error!("Feed handler error: {e}"),
279            }
280
281            Ok(())
282        })
283    }
284
285    #[pyo3(name = "close")]
286    fn py_close(&mut self) -> PyResult<()> {
287        if !self.is_running {
288            return Err(to_pyruntime_err("Client never started"));
289        }
290        if self.is_closed {
291            return Err(to_pyruntime_err("Client already closed"));
292        }
293
294        tracing::debug!("Closing client");
295
296        if !self.is_closed() {
297            self.send_command(LiveCommand::Close)?;
298        }
299
300        self.is_running = false;
301        self.is_closed = true;
302
303        Ok(())
304    }
305}