1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
use time::OffsetDateTime;
use crate::contracts::Contract;
use crate::market_data::historical::{BarSize, Duration, HistoricalBarUpdate, HistoricalData, WhatToShow};
use crate::market_data::TradingHours;
use crate::Error;
#[cfg(test)]
#[path = "data_tests.rs"]
mod tests;
/// Builder for historical bar data requests.
///
/// Required: one of [`duration`](Self::duration) (with optional [`ending`](Self::ending))
/// or [`between`](Self::between) to specify the time range. Mixing the two styles
/// errors at the terminal.
#[must_use = "HistoricalDataBuilder does nothing until you call .fetch() or .stream()"]
pub struct HistoricalDataBuilder<'a, C> {
client: &'a C,
contract: &'a Contract,
bar_size: BarSize,
what_to_show: WhatToShow,
trading_hours: TradingHours,
duration: Option<Duration>,
ending: Option<OffsetDateTime>,
between: Option<(OffsetDateTime, OffsetDateTime)>,
}
impl<'a, C> HistoricalDataBuilder<'a, C> {
pub(crate) fn new(client: &'a C, contract: &'a Contract, bar_size: BarSize) -> Self {
Self {
client,
contract,
bar_size,
what_to_show: WhatToShow::Trades,
trading_hours: TradingHours::Regular,
duration: None,
ending: None,
between: None,
}
}
/// Override the data type to retrieve (defaults to [`WhatToShow::Trades`]).
pub fn what_to_show(mut self, what_to_show: WhatToShow) -> Self {
self.what_to_show = what_to_show;
self
}
/// Override regular- vs extended-hours (defaults to [`TradingHours::Regular`]).
pub fn trading_hours(mut self, trading_hours: TradingHours) -> Self {
self.trading_hours = trading_hours;
self
}
/// Amount of data going back from the end date (now if [`ending`](Self::ending) is unset).
pub fn duration(mut self, duration: Duration) -> Self {
self.duration = Some(duration);
self
}
/// Anchor the query at a specific end date (defaults to now).
pub fn ending(mut self, end_date: OffsetDateTime) -> Self {
self.ending = Some(end_date);
self
}
/// Convenience: specify an explicit date range (computes duration internally).
pub fn between(mut self, start: OffsetDateTime, end: OffsetDateTime) -> Self {
self.between = Some((start, end));
self
}
/// Resolve the builder's date spec into (end_date, duration). Errors if the
/// user mixed `.between` with `.duration`/`.ending`, or set neither.
fn resolve_date_spec(&self) -> Result<(Option<OffsetDateTime>, Duration), Error> {
match (self.between, self.duration, self.ending) {
(Some(_), Some(_), _) | (Some(_), _, Some(_)) => Err(Error::InvalidArgument(
"historical_data: cannot mix .between(...) with .duration()/.ending()".to_owned(),
)),
(Some((start, end)), None, None) => {
if end <= start {
return Err(Error::InvalidArgument(
"historical_data: .between(start, end) requires end > start".to_owned(),
));
}
let seconds = (end - start).whole_seconds();
if seconds > i32::MAX as i64 {
return Err(Error::InvalidArgument(
"historical_data: .between(start, end) range exceeds i32::MAX seconds".to_owned(),
));
}
Ok((Some(end), Duration::seconds(seconds as i32)))
}
(None, Some(duration), ending) => Ok((ending, duration)),
(None, None, _) => Err(Error::InvalidArgument(
"historical_data: must set .duration() or .between(...)".to_owned(),
)),
}
}
/// Resolve the builder for a streaming request (`keep_up_to_date = true`).
/// IBKR requires `end_date = None` for streaming, so `.ending()` / `.between()`
/// are rejected.
fn resolve_for_stream(&self) -> Result<Duration, Error> {
if self.ending.is_some() || self.between.is_some() {
return Err(Error::InvalidArgument(
"historical_data().stream(): IBKR requires end_date = None for streaming; drop .ending() / .between()".to_owned(),
));
}
self.duration
.ok_or_else(|| Error::InvalidArgument("historical_data().stream(): must set .duration()".to_owned()))
}
}
#[cfg(feature = "sync")]
impl<'a> HistoricalDataBuilder<'a, crate::client::sync::Client> {
/// Submit a one-shot request and return the [`HistoricalData`] bars.
///
/// # Examples
///
/// ```no_run
/// use ibapi::client::blocking::Client;
/// use ibapi::contracts::Contract;
/// use ibapi::market_data::historical::{BarSize, ToDuration};
/// use time::macros::datetime;
///
/// let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
/// let contract = Contract::stock("AAPL").build();
///
/// // 7 days of hourly bars, ending now:
/// let bars = client
/// .historical_data(&contract, BarSize::Hour)
/// .duration(7.days())
/// .fetch()
/// .expect("historical data request failed");
///
/// // Equivalent via explicit date range:
/// let bars = client
/// .historical_data(&contract, BarSize::Hour)
/// .between(datetime!(2023-04-08 0:00 UTC), datetime!(2023-04-15 0:00 UTC))
/// .fetch()
/// .expect("historical data request failed");
/// # let _ = bars;
/// ```
pub fn fetch(self) -> Result<HistoricalData, Error> {
let (end_date, duration) = self.resolve_date_spec()?;
crate::market_data::historical::sync::historical_data(
self.client,
self.contract,
end_date,
duration,
self.bar_size,
self.what_to_show,
self.trading_hours,
)
}
/// Submit a streaming request (`keep_up_to_date = true`) and return a
/// [`Subscription`](crate::subscriptions::Subscription) of [`HistoricalBarUpdate`].
/// IBKR sends initial bars, then per-bar updates as they form.
///
/// Rejects builders that called [`ending`](Self::ending) or [`between`](Self::between) —
/// IBKR requires `end_date = None` for streaming.
///
/// # Examples
///
/// ```no_run
/// use ibapi::client::blocking::Client;
/// use ibapi::contracts::Contract;
/// use ibapi::market_data::historical::{BarSize, ToDuration};
///
/// let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
/// let contract = Contract::stock("SPY").build();
///
/// let subscription = client
/// .historical_data(&contract, BarSize::Min15)
/// .duration(1.days())
/// .stream()
/// .expect("streaming request failed");
/// # drop(subscription);
/// ```
pub fn stream(self) -> Result<crate::subscriptions::sync::Subscription<HistoricalBarUpdate>, Error> {
let duration = self.resolve_for_stream()?;
crate::market_data::historical::sync::historical_data_stream(
self.client,
self.contract,
duration,
self.bar_size,
self.what_to_show,
self.trading_hours,
)
}
}
#[cfg(feature = "async")]
impl<'a> HistoricalDataBuilder<'a, crate::client::r#async::Client> {
/// Submit a one-shot request and return the [`HistoricalData`] bars.
///
/// # Examples
///
/// ```no_run
/// use ibapi::prelude::*;
/// use time::macros::datetime;
///
/// #[tokio::main]
/// async fn main() {
/// let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
/// let contract = Contract::stock("AAPL").build();
///
/// // 7 days of hourly bars, ending now:
/// let bars = client
/// .historical_data(&contract, HistoricalBarSize::Hour)
/// .duration(7.days())
/// .fetch()
/// .await
/// .expect("historical data request failed");
///
/// // Equivalent via explicit date range:
/// let bars = client
/// .historical_data(&contract, HistoricalBarSize::Hour)
/// .between(datetime!(2023-04-08 0:00 UTC), datetime!(2023-04-15 0:00 UTC))
/// .fetch()
/// .await
/// .expect("historical data request failed");
/// let _ = bars;
/// }
/// ```
pub async fn fetch(self) -> Result<HistoricalData, Error> {
let (end_date, duration) = self.resolve_date_spec()?;
crate::market_data::historical::r#async::historical_data(
self.client,
self.contract,
end_date,
duration,
self.bar_size,
self.what_to_show,
self.trading_hours,
)
.await
}
/// Submit a streaming request (`keep_up_to_date = true`) and return a
/// [`Subscription`](crate::subscriptions::Subscription) of [`HistoricalBarUpdate`].
///
/// Rejects builders that called [`ending`](Self::ending) or [`between`](Self::between) —
/// IBKR requires `end_date = None` for streaming.
///
/// # Examples
///
/// ```no_run
/// use ibapi::prelude::*;
///
/// #[tokio::main]
/// async fn main() {
/// let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
/// let contract = Contract::stock("SPY").build();
///
/// let subscription = client
/// .historical_data(&contract, HistoricalBarSize::Min15)
/// .duration(1.days())
/// .stream()
/// .await
/// .expect("streaming request failed");
/// drop(subscription);
/// }
/// ```
pub async fn stream(self) -> Result<crate::subscriptions::Subscription<HistoricalBarUpdate>, Error> {
let duration = self.resolve_for_stream()?;
crate::market_data::historical::r#async::historical_data_stream(
self.client,
self.contract,
duration,
self.bar_size,
self.what_to_show,
self.trading_hours,
)
.await
}
}