Skip to main content

nautilus_interactive_brokers/python/
historical.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
16//! Python bindings for the Interactive Brokers historical data client.
17
18use ibapi::contracts::Contract;
19use jiff::Timestamp;
20use nautilus_common::live::block_on_nautilus_with;
21use nautilus_core::python::{to_pyruntime_err, to_pyvalue_err};
22use nautilus_model::{
23    data::{Bar, Data},
24    identifiers::InstrumentId,
25    instruments::any::InstrumentAny,
26    python::{data::data_to_pyobject, instruments::instrument_any_to_pyobject},
27};
28use pyo3::{prelude::*, types::PyList};
29
30use crate::{
31    common::enums::IbHistoricalTickType, config::InteractiveBrokersDataClientConfig,
32    historical::HistoricalInteractiveBrokersClient,
33    providers::instruments::InteractiveBrokersInstrumentProvider,
34    python::conversion::py_list_to_contracts,
35};
36
37#[pymethods]
38#[pyo3_stub_gen::derive::gen_stub_pymethods]
39impl HistoricalInteractiveBrokersClient {
40    #[new]
41    fn py_new(
42        instrument_provider: InteractiveBrokersInstrumentProvider,
43        config: InteractiveBrokersDataClientConfig,
44    ) -> PyResult<Self> {
45        block_on_nautilus_with(move || Self::connect_with_provider(instrument_provider, config))
46            .map_err(to_pyruntime_err)
47    }
48
49    fn __repr__(&self) -> String {
50        format!("{self:?}")
51    }
52
53    /// Request historical bars.
54    ///
55    /// # Continuous futures
56    ///
57    /// Continuous futures (`CONTFUT`) reject an explicit end date/time with IB
58    /// error 10339. For these contracts the end date is dropped and only the
59    /// first duration segment is requested, anchored to the current time, so
60    /// the returned bars may fall outside `[start_date_time, end_date_time]`.
61    /// A warning is logged when the requested end date/time is in the past or
62    /// the range spans more than one duration segment.
63    #[pyo3(signature = (bar_specifications, end_date_time, start_date_time=None, duration=None, contracts=None, instrument_ids=None, use_rth=true, timeout=60))]
64    #[pyo3(name = "request_bars")]
65    #[allow(clippy::too_many_arguments)]
66    fn py_request_bars<'py>(
67        &self,
68        py: Python<'py>,
69        bar_specifications: Vec<String>,
70        end_date_time: Timestamp,
71        start_date_time: Option<Timestamp>,
72        duration: Option<String>,
73        contracts: Option<&Bound<'py, PyList>>,
74        instrument_ids: Option<Vec<InstrumentId>>,
75        use_rth: bool,
76        timeout: u64,
77    ) -> PyResult<Bound<'py, PyAny>> {
78        let client = self.clone();
79        let bar_specs = bar_specifications;
80        let duration_str = duration;
81
82        // Convert Python contracts list to Rust Contracts
83        let contracts_vec: Option<Vec<Contract>> = if let Some(py_contracts) = contracts {
84            match py_list_to_contracts(py_contracts) {
85                Ok(contracts) => Some(contracts),
86                Err(e) => {
87                    return Err(to_pyvalue_err(format!("Failed to convert contracts: {e}")));
88                }
89            }
90        } else {
91            None
92        };
93
94        pyo3_async_runtimes::tokio::future_into_py(py, async move {
95            // Convert Vec<String> to Vec<&str> for the request
96            let bar_specs_refs: Vec<&str> = bar_specs.iter().map(|s| s.as_str()).collect();
97            let bars: Vec<Bar> = client
98                .request_bars(
99                    bar_specs_refs,
100                    end_date_time,
101                    start_date_time,
102                    duration_str.as_deref(),
103                    contracts_vec,
104                    instrument_ids,
105                    use_rth,
106                    timeout,
107                )
108                .await
109                .map_err(to_pyruntime_err)?;
110            // Convert bars to Python objects
111            Ok(bars)
112        })
113    }
114
115    /// Request historical ticks (quotes or trades).
116    #[pyo3(signature = (tick_type, start_date_time, end_date_time, contracts=None, instrument_ids=None, use_rth=true, timeout=60, limit=0))]
117    #[pyo3(name = "request_ticks")]
118    #[allow(clippy::too_many_arguments)]
119    fn py_request_ticks<'py>(
120        &self,
121        py: Python<'py>,
122        tick_type: IbHistoricalTickType,
123        start_date_time: Timestamp,
124        end_date_time: Timestamp,
125        contracts: Option<&Bound<'py, PyList>>,
126        instrument_ids: Option<Vec<InstrumentId>>,
127        use_rth: bool,
128        timeout: u64,
129        limit: usize,
130    ) -> PyResult<Bound<'py, PyAny>> {
131        let client = self.clone();
132
133        // Convert Python contracts list to Rust Contracts
134        let contracts_vec: Option<Vec<Contract>> = if let Some(py_contracts) = contracts {
135            match py_list_to_contracts(py_contracts) {
136                Ok(contracts) => Some(contracts),
137                Err(e) => {
138                    return Err(to_pyvalue_err(format!("Failed to convert contracts: {e}")));
139                }
140            }
141        } else {
142            None
143        };
144
145        pyo3_async_runtimes::tokio::future_into_py(py, async move {
146            let data_vec: Vec<Data> = client
147                .request_ticks(
148                    tick_type,
149                    start_date_time,
150                    end_date_time,
151                    contracts_vec,
152                    instrument_ids,
153                    use_rth,
154                    timeout,
155                    limit,
156                )
157                .await
158                .map_err(to_pyruntime_err)?;
159            // Convert Data values to native Python objects.
160            Python::attach(|py| -> PyResult<Py<PyList>> {
161                let py_list = PyList::empty(py);
162                for data in data_vec {
163                    let py_obj = data_to_pyobject(py, data)?;
164                    py_list.append(py_obj)?;
165                }
166
167                Ok(py_list.into())
168            })
169        })
170    }
171
172    /// Request instruments.
173    #[pyo3(signature = (instrument_ids=None, contracts=None))]
174    #[pyo3(name = "request_instruments")]
175    fn py_request_instruments<'py>(
176        &self,
177        py: Python<'py>,
178        instrument_ids: Option<Vec<InstrumentId>>,
179        contracts: Option<&Bound<'py, PyList>>,
180    ) -> PyResult<Bound<'py, PyAny>> {
181        let client = self.clone();
182
183        // Convert Python contracts list to Rust Contracts
184        let contracts_vec: Option<Vec<Contract>> = if let Some(py_contracts) = contracts {
185            match py_list_to_contracts(py_contracts) {
186                Ok(contracts) => Some(contracts),
187                Err(e) => {
188                    return Err(to_pyvalue_err(format!("Failed to convert contracts: {e}")));
189                }
190            }
191        } else {
192            None
193        };
194
195        pyo3_async_runtimes::tokio::future_into_py(py, async move {
196            let instruments: Vec<InstrumentAny> = client
197                .request_instruments(instrument_ids, contracts_vec)
198                .await
199                .map_err(to_pyruntime_err)?;
200            // Convert instruments to Python objects
201            Python::attach(|py| -> PyResult<Py<PyList>> {
202                let py_list = PyList::empty(py);
203
204                for instrument in instruments {
205                    let py_obj =
206                        instrument_any_to_pyobject(py, instrument).map_err(to_pyruntime_err)?;
207                    py_list.append(py_obj)?;
208                }
209
210                Ok(py_list.into())
211            })
212        })
213    }
214}