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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use log::{debug, error, warn};
use time::OffsetDateTime;
use crate::client::ClientRequestBuilders;
use crate::contracts::Contract;
use crate::messages::IncomingMessages;
use crate::protocol::{check_version, Features};
use crate::subscriptions::r#async::Subscription;
use crate::transport::{AsyncInternalSubscription, AsyncMessageBus};
use crate::{Client, Error, MAX_RETRIES};
use super::common::{self, decoders, encoders};
use super::{BarSize, Duration, HistogramEntry, HistoricalBarUpdate, HistoricalData, Schedule, TickDecoder, WhatToShow};
use crate::market_data::TradingHours;
// === Public API Functions ===
impl Client {
/// Returns the timestamp of earliest available historical data for a contract and data type.
///
/// # Arguments
/// * `contract` - [Contract] to retrieve the head timestamp for.
/// * `what_to_show` - requested bar type: [WhatToShow].
/// * `trading_hours` - Use [TradingHours::Regular] for data generated only during regular trading hours, or [TradingHours::Extended] to include data from outside regular trading hours.
///
/// # Examples
///
/// ```no_run
/// use ibapi::Client;
/// use ibapi::contracts::Contract;
/// use ibapi::market_data::historical::WhatToShow;
/// use ibapi::market_data::TradingHours;
///
/// #[tokio::main]
/// async fn main() {
/// let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
///
/// let contract = Contract::stock("MSFT").build();
/// let result = client
/// .head_timestamp(&contract, WhatToShow::Trades, TradingHours::Regular)
/// .await
/// .expect("head timestamp failed");
///
/// println!("head_timestamp: {result:?}");
/// }
/// ```
pub async fn head_timestamp(&self, contract: &Contract, what_to_show: WhatToShow, trading_hours: TradingHours) -> Result<OffsetDateTime, Error> {
check_version(self.server_version(), Features::HEAD_TIMESTAMP)?;
let builder = self.request();
let request = encoders::encode_request_head_timestamp(builder.request_id(), contract, what_to_show, trading_hours.use_rth())?;
let mut subscription = builder.send_raw(request).await?;
match subscription.next().await {
Some(Ok(message)) if message.message_type() == IncomingMessages::HeadTimestamp => Ok(decoders::decode_head_timestamp(&message)?),
Some(Ok(message)) => Err(Error::unexpected_response(&message)),
Some(Err(e)) => Err(e),
None => {
// Connection might have been reset, retry
Box::pin(self.head_timestamp(contract, what_to_show, trading_hours)).await
}
}
}
/// Build a request for historical bar data.
///
/// Required: a date spec via either [`HistoricalDataBuilder::duration`](super::HistoricalDataBuilder::duration)
/// (with optional [`HistoricalDataBuilder::ending`](super::HistoricalDataBuilder::ending)) or
/// [`HistoricalDataBuilder::between`](super::HistoricalDataBuilder::between). Terminals:
/// [`HistoricalDataBuilder::fetch`](super::HistoricalDataBuilder::fetch) for a one-shot
/// [`HistoricalData`] result; [`HistoricalDataBuilder::stream`](super::HistoricalDataBuilder::stream)
/// for a `Subscription<HistoricalBarUpdate>` that yields bars as they arrive.
///
/// # Arguments
/// * `contract` - Contract object that is subject of query
/// * `bar_size` - Bar size (resolution)
///
/// # 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();
///
/// // IBKR-native: amount of data ending at a specific time (or now)
/// let bars = client
/// .historical_data(&contract, HistoricalBarSize::Hour)
/// .what_to_show(HistoricalWhatToShow::Trades)
/// .duration(7.days())
/// .fetch()
/// .await
/// .expect("historical data request failed");
///
/// // Convenience: explicit date range (computes duration internally)
/// 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 fn historical_data<'a>(&'a self, contract: &'a Contract, bar_size: BarSize) -> super::HistoricalDataBuilder<'a, Self> {
super::HistoricalDataBuilder::new(self, contract, bar_size)
}
/// Build a request for [`Schedule`] data over the given duration.
///
/// Defaults to anchoring at the current time. Use [`HistoricalScheduleBuilder::ending`](super::HistoricalScheduleBuilder::ending)
/// to anchor at a specific end date.
///
/// # Arguments
/// * `contract` - [Contract] to retrieve [Schedule] for.
/// * `duration` - [Duration] of the interval to retrieve.
///
/// # 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("GM").build();
///
/// // Ending now:
/// let schedule = client
/// .historical_schedules(&contract, 30.days())
/// .fetch()
/// .await
/// .expect("historical schedule request failed");
///
/// // Anchored to a specific end date:
/// let schedule = client
/// .historical_schedules(&contract, 30.days())
/// .ending(datetime!(2023-04-15 0:00 UTC))
/// .fetch()
/// .await
/// .expect("historical schedule request failed");
///
/// for session in &schedule.sessions {
/// println!("{session:?}");
/// }
/// }
/// ```
pub fn historical_schedules<'a>(&'a self, contract: &'a Contract, duration: Duration) -> super::HistoricalScheduleBuilder<'a, Self> {
super::HistoricalScheduleBuilder::new(self, contract, duration)
}
/// Build a request for historical time & sales data (tick-by-tick).
///
/// The terminal method selects the tick type:
/// [`HistoricalTicksBuilder::trade`](super::HistoricalTicksBuilder::trade) /
/// `.mid_point()` / `.bid_ask(IgnoreSize)`. Use
/// [`HistoricalTicksBuilder::starting`](super::HistoricalTicksBuilder::starting) /
/// `.ending()` to anchor the query (at least one is required per IBKR).
///
/// # Arguments
/// * `contract` - [Contract] object that is subject of query
/// * `number_of_ticks` - Number of distinct data points. Max currently 1000 per request.
///
/// # Examples
///
/// ```no_run
/// use ibapi::prelude::*;
/// use ibapi::market_data::IgnoreSize;
/// 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("TSLA").build();
///
/// // Trade ticks anchored at a start date:
/// let mut trades = client
/// .historical_ticks(&contract, 100)
/// .starting(datetime!(2023-04-15 0:00 UTC))
/// .trade()
/// .await
/// .expect("historical ticks request failed");
///
/// while let Some(tick) = trades.next().await {
/// println!("{tick:?}");
/// }
///
/// // Bid/ask ticks anchored at an end date, ignoring tick sizes:
/// let _quotes = client
/// .historical_ticks(&contract, 100)
/// .ending(datetime!(2023-04-15 0:00 UTC))
/// .bid_ask(IgnoreSize::Yes)
/// .await
/// .expect("historical ticks request failed");
/// }
/// ```
pub fn historical_ticks<'a>(&'a self, contract: &'a Contract, number_of_ticks: i32) -> super::HistoricalTicksBuilder<'a, Self> {
super::HistoricalTicksBuilder::new(self, contract, number_of_ticks)
}
/// Cancels an in-flight historical ticks request.
///
/// # Arguments
/// * `request_id` - The request ID of the historical ticks subscription to cancel.
pub async fn cancel_historical_ticks(&self, request_id: i32) -> Result<(), Error> {
check_version(self.server_version(), Features::CANCEL_CONTRACT_DATA)?;
let message = encoders::encode_cancel_historical_ticks(request_id)?;
self.send_message(message).await?;
Ok(())
}
/// Requests data histogram of specified contract.
///
/// # Arguments
/// * `contract` - [Contract] to retrieve [HistogramEntry] data for.
/// * `trading_hours` - Regular trading hours only, or include extended hours.
/// * `period` - The time period of each histogram bar (e.g., `BarSize::Day`, `BarSize::Week`, `BarSize::Month`).
///
/// # Examples
///
/// ```no_run
/// use ibapi::Client;
/// use ibapi::contracts::Contract;
/// use ibapi::market_data::historical::BarSize;
/// use ibapi::market_data::TradingHours;
///
/// #[tokio::main]
/// async fn main() {
/// let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
///
/// let contract = Contract::stock("GM").build();
/// let histogram = client
/// .histogram_data(&contract, TradingHours::Regular, BarSize::Week)
/// .await
/// .expect("histogram request failed");
///
/// for item in &histogram {
/// println!("{item:?}");
/// }
/// }
/// ```
pub async fn histogram_data(&self, contract: &Contract, trading_hours: TradingHours, period: BarSize) -> Result<Vec<HistogramEntry>, Error> {
check_version(self.server_version(), Features::HISTOGRAM)?;
loop {
let builder = self.request();
let request = encoders::encode_request_histogram_data(builder.request_id(), contract, trading_hours.use_rth(), period)?;
let mut subscription = builder.send_raw(request).await?;
match subscription.next().await {
Some(Ok(message)) => return decoders::decode_histogram_data(&message),
Some(Err(e)) => return Err(e),
None => continue, // Connection reset, retry
}
}
}
}
pub(crate) async fn historical_data(
client: &Client,
contract: &Contract,
end_date: Option<OffsetDateTime>,
duration: Duration,
bar_size: BarSize,
what_to_show: WhatToShow,
trading_hours: TradingHours,
) -> Result<HistoricalData, Error> {
common::validate_historical_data(client.server_version(), contract, end_date, Some(what_to_show))?;
for _ in 0..MAX_RETRIES {
let builder = client.request();
let request = encoders::encode_request_historical_data(
builder.request_id(),
contract,
end_date,
duration,
bar_size,
Some(what_to_show),
trading_hours.use_rth(),
false,
&Vec::<crate::contracts::TagValue>::default(),
)?;
let mut subscription = builder.send_raw(request).await?;
match subscription.next().await {
Some(Ok(message)) if message.message_type() == IncomingMessages::HistoricalData => {
let mut data = decoders::decode_historical_data(&message)?;
if let Some(Ok(end_msg)) = subscription.next().await {
let (start, end) = decoders::decode_historical_data_end(&end_msg)?;
data.start = start;
data.end = end;
}
return Ok(data);
}
Some(Ok(message)) if message.message_type() == IncomingMessages::Error => return Err(Error::from(message)),
Some(Ok(message)) => return Err(Error::unexpected_response(&message)),
Some(Err(e)) => return Err(e),
None => continue, // Connection reset, retry
}
}
Err(Error::ConnectionReset)
}
pub(crate) async fn historical_data_stream(
client: &Client,
contract: &Contract,
duration: Duration,
bar_size: BarSize,
what_to_show: WhatToShow,
trading_hours: TradingHours,
) -> Result<Subscription<HistoricalBarUpdate>, Error> {
if !contract.trading_class.is_empty() || contract.contract_id > 0 {
check_version(client.server_version(), Features::TRADING_CLASS)?;
}
let builder = client.request();
let request = encoders::encode_request_historical_data(
builder.request_id(),
contract,
None, // IBKR requires end_date=None when keep_up_to_date=true
duration,
bar_size,
Some(what_to_show),
trading_hours.use_rth(),
true, // keep_up_to_date — the whole point of .stream()
&Vec::<crate::contracts::TagValue>::default(),
)?;
builder.send::<HistoricalBarUpdate>(request).await
}
// pub(crate) internal plumbing called from `HistoricalTicksBuilder`; the
// public API is already a builder, so flat args here are the deliberate
// seam between the typed builder and the wire encoder (rule 19 canary
// acceptable for builder-fed helpers).
#[allow(clippy::too_many_arguments)]
pub(crate) async fn historical_ticks<T: TickDecoder<T> + Send>(
client: &Client,
contract: &Contract,
start: Option<OffsetDateTime>,
end: Option<OffsetDateTime>,
number_of_ticks: i32,
what_to_show: WhatToShow,
trading_hours: TradingHours,
ignore_size: bool,
) -> Result<TickSubscription<T>, Error> {
check_version(client.server_version(), Features::HISTORICAL_TICKS)?;
let builder = client.request();
let request = encoders::encode_request_historical_ticks(
builder.request_id(),
contract,
start,
end,
number_of_ticks,
what_to_show,
trading_hours.use_rth(),
ignore_size,
)?;
let request_id = builder.request_id();
let subscription = builder.send_raw(request).await?;
Ok(TickSubscription::new(subscription, request_id, Arc::clone(&client.message_bus)))
}
pub(crate) async fn historical_schedule(
client: &Client,
contract: &Contract,
end_date: Option<OffsetDateTime>,
duration: Duration,
) -> Result<Schedule, Error> {
common::validate_historical_data(client.server_version(), contract, end_date, Some(WhatToShow::Schedule))?;
loop {
let builder = client.request();
let request = encoders::encode_request_historical_data(
builder.request_id(),
contract,
end_date,
duration,
BarSize::Day,
Some(WhatToShow::Schedule),
true,
false,
&Vec::<crate::contracts::TagValue>::default(),
)?;
let mut subscription = builder.send_raw(request).await?;
match subscription.next().await {
Some(Ok(message)) if message.message_type() == IncomingMessages::HistoricalSchedule => {
return decoders::decode_historical_schedule(&message)
}
Some(Ok(message)) => return Err(Error::unexpected_response(&message)),
Some(Err(e)) => return Err(e),
None => continue, // Connection reset, retry
}
}
}
// === TickSubscription and related types ===
/// Async subscription handle that decodes historical tick batches as they arrive.
#[must_use = "TickSubscription must be polled (.next().await) to receive ticks; dropping it cancels the request"]
pub struct TickSubscription<T: TickDecoder<T> + Send> {
done: bool,
messages: AsyncInternalSubscription,
buffer: VecDeque<T>,
error: Option<Error>,
request_id: i32,
message_bus: Arc<dyn AsyncMessageBus>,
cancelled: AtomicBool,
}
impl<T: TickDecoder<T> + Send> TickSubscription<T> {
fn new(messages: AsyncInternalSubscription, request_id: i32, message_bus: Arc<dyn AsyncMessageBus>) -> Self {
Self {
done: false,
messages,
buffer: VecDeque::new(),
error: None,
request_id,
message_bus,
cancelled: AtomicBool::new(false),
}
}
/// Cancel the historical-ticks request. Safe to call after completion (no-op).
/// Also fired automatically on `Drop` for unfinished subscriptions; explicit calls are idempotent.
pub async fn cancel(&self) {
if self.cancelled.swap(true, Ordering::Relaxed) {
return;
}
match encoders::encode_cancel_historical_ticks(self.request_id) {
Ok(message) => {
if let Err(e) = self.message_bus.cancel_subscription(self.request_id, message).await {
warn!("error cancelling historical ticks subscription: {e}");
}
}
Err(e) => error!("error encoding cancel historical ticks: {e}"),
}
}
/// Block until the next tick batch is available.
pub async fn next(&mut self) -> Option<T> {
self.clear_error();
loop {
if let Some(tick) = self.next_buffered() {
return Some(tick);
}
if self.done {
return None;
}
match self.fill_buffer().await {
Ok(()) => continue,
Err(()) => return None,
}
}
}
async fn fill_buffer(&mut self) -> Result<(), ()> {
match self.messages.next().await {
Some(Ok(message)) if message.message_type() == T::MESSAGE_TYPE => {
let (ticks, done) = T::decode(&message).unwrap();
self.buffer.extend(ticks);
self.done = done;
Ok(())
}
Some(Ok(message)) => {
debug!("unexpected message: {message:?}");
Ok(())
}
Some(Err(_)) => Err(()),
None => Err(()),
}
}
fn next_buffered(&mut self) -> Option<T> {
self.buffer.pop_front()
}
#[allow(dead_code)]
fn set_error(&mut self, e: Error) {
self.error = Some(e);
}
fn clear_error(&mut self) {
self.error = None;
}
}
impl<T: TickDecoder<T> + Send> Drop for TickSubscription<T> {
fn drop(&mut self) {
if self.done || self.cancelled.swap(true, Ordering::Relaxed) {
return;
}
let request_id = self.request_id;
let message_bus = self.message_bus.clone();
if let Ok(message) = encoders::encode_cancel_historical_ticks(request_id) {
tokio::spawn(async move {
if let Err(e) = message_bus.cancel_subscription(request_id, message).await {
warn!("error sending cancel historical ticks in drop: {e}");
}
});
}
}
}
#[cfg(test)]
#[path = "async_tests.rs"]
mod tests;