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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use log::{debug, error, warn};
use time::OffsetDateTime;
use crate::client::blocking::ClientRequestBuilders;
use crate::contracts::Contract;
use crate::messages::IncomingMessages;
use crate::protocol::{check_version, Features};
use crate::subscriptions::sync::Subscription;
use crate::transport::{InternalSubscription, MessageBus, Response};
use crate::{client::sync::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;
impl Client {
/// Returns the timestamp of earliest available historical data for a contract and data type.
///
/// ```no_run
/// use ibapi::client::blocking::Client;
/// use ibapi::contracts::Contract;
/// use ibapi::market_data::historical::{self, WhatToShow};
/// use ibapi::market_data::TradingHours;
///
/// let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
///
/// let contract = Contract::stock("MSFT").build();
/// let what_to_show = WhatToShow::Trades;
/// let trading_hours = TradingHours::Regular;
///
/// let result = client.head_timestamp(&contract, what_to_show, trading_hours).expect("head timestamp failed");
///
/// print!("head_timestamp: {result:?}");
/// ```
pub 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 subscription = builder.send_raw(request)?;
match subscription.next() {
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(Error::ConnectionReset)) => self.head_timestamp(contract, what_to_show, trading_hours),
Some(Err(e)) => Err(e),
None => Err(Error::UnexpectedEndOfStream),
}
}
/// 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::client::blocking::Client;
/// use ibapi::contracts::Contract;
/// use ibapi::market_data::historical::{BarSize, ToDuration, WhatToShow};
/// use time::macros::datetime;
///
/// let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
/// let contract = Contract::stock("AAPL").build();
///
/// // IBKR-native: amount of data ending at a specific time (or now if `.ending` is unset)
/// let bars = client
/// .historical_data(&contract, BarSize::Hour)
/// .what_to_show(WhatToShow::Trades)
/// .duration(7.days())
/// .fetch()
/// .expect("historical data request failed");
///
/// // Convenience: explicit date range (computes duration internally)
/// 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 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 time::macros::datetime;
/// use ibapi::client::blocking::Client;
/// use ibapi::contracts::Contract;
/// use ibapi::market_data::historical::ToDuration;
///
/// let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
/// let contract = Contract::stock("GM").build();
///
/// // Ending now:
/// let schedule = client
/// .historical_schedules(&contract, 30.days())
/// .fetch()
/// .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()
/// .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::client::blocking::Client;
/// use ibapi::contracts::Contract;
/// use ibapi::market_data::IgnoreSize;
/// use ibapi::market_data::TradingHours;
/// use time::macros::datetime;
///
/// let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
/// let contract = Contract::stock("TSLA").build();
///
/// // Trade ticks anchored at a start date:
/// let trades = client
/// .historical_ticks(&contract, 100)
/// .starting(datetime!(2023-04-15 0:00 UTC))
/// .trading_hours(TradingHours::Regular)
/// .trade()
/// .expect("historical ticks request failed");
///
/// // 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)
/// .expect("historical ticks request failed");
///
/// for tick in trades {
/// println!("{tick:?}");
/// }
/// # let _ = quotes;
/// ```
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 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)?;
Ok(())
}
/// Requests data histogram of specified contract.
///
/// # Arguments
/// * `contract` - [Contract] to retrieve [Histogram Entries](HistogramEntry) 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 time::macros::datetime;
//
/// use ibapi::contracts::Contract;
/// use ibapi::client::blocking::Client;
/// use ibapi::market_data::historical::BarSize;
/// use ibapi::market_data::TradingHours;
///
/// let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
///
/// let contract = Contract::stock("GM").build();
///
/// let histogram = client
/// .histogram_data(&contract, TradingHours::Regular, BarSize::Week)
/// .expect("histogram request failed");
///
/// for item in &histogram {
/// println!("{item:?}");
/// }
/// ```
pub 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 subscription = builder.send_raw(request)?;
match subscription.next() {
Some(Ok(message)) => return decoders::decode_histogram_data(&message),
Some(Err(Error::ConnectionReset)) => continue,
Some(Err(e)) => return Err(e),
None => return Ok(Vec::new()),
}
}
}
}
pub(crate) 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 subscription = builder.send_raw(request)?;
match subscription.next() {
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() {
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(Error::ConnectionReset)) => {}
Some(Err(e)) => return Err(e),
None => return Err(Error::UnexpectedEndOfStream),
}
}
Err(Error::ConnectionReset)
}
pub(crate) 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)
}
// 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) fn historical_ticks<T: TickDecoder<T>>(
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)?;
Ok(TickSubscription::new(subscription, request_id, Arc::clone(&client.message_bus)))
}
pub(crate) 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 subscription = builder.send_raw(request)?;
match subscription.next() {
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(Error::ConnectionReset)) => {}
Some(Err(e)) => return Err(e),
None => return Err(Error::UnexpectedEndOfStream),
}
}
}
// TickSubscription and related types
/// Shared subscription handle that decodes historical tick batches as they arrive.
#[must_use = "TickSubscription must be polled (.next() or .iter()) to receive ticks; dropping it cancels the request"]
pub struct TickSubscription<T: TickDecoder<T>> {
done: AtomicBool,
messages: InternalSubscription,
buffer: Mutex<VecDeque<T>>,
error: Mutex<Option<Error>>,
request_id: i32,
message_bus: Arc<dyn MessageBus>,
cancelled: AtomicBool,
}
impl<T: TickDecoder<T>> TickSubscription<T> {
fn new(messages: InternalSubscription, request_id: i32, message_bus: Arc<dyn MessageBus>) -> Self {
Self {
done: false.into(),
messages,
buffer: Mutex::new(VecDeque::new()),
error: Mutex::new(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 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) {
warn!("error cancelling historical ticks subscription: {e}");
}
self.messages.cancel();
}
Err(e) => error!("error encoding cancel historical ticks: {e}"),
}
}
/// Return an iterator that blocks until each tick batch becomes available.
pub fn iter(&self) -> TickSubscriptionIter<'_, T> {
TickSubscriptionIter { subscription: self }
}
/// Return a non-blocking iterator that yields immediately with cached ticks.
pub fn try_iter(&self) -> TickSubscriptionTryIter<'_, T> {
TickSubscriptionTryIter { subscription: self }
}
/// Return an iterator that waits up to `duration` for each tick batch.
pub fn timeout_iter(&self, duration: std::time::Duration) -> TickSubscriptionTimeoutIter<'_, T> {
TickSubscriptionTimeoutIter {
subscription: self,
timeout: duration,
}
}
/// Block until the next tick batch is available.
pub fn next(&self) -> Option<T> {
self.next_helper(|| self.messages.next())
}
/// Attempt to fetch the next tick batch without blocking.
pub fn try_next(&self) -> Option<T> {
self.next_helper(|| self.messages.try_next())
}
/// Wait up to `duration` for the next tick batch to arrive.
pub fn next_timeout(&self, duration: std::time::Duration) -> Option<T> {
self.next_helper(|| self.messages.next_timeout(duration))
}
fn next_helper<F>(&self, next_response: F) -> Option<T>
where
F: Fn() -> Option<Response>,
{
self.clear_error();
loop {
if let Some(message) = self.next_buffered() {
return Some(message);
}
if self.done.load(Ordering::Relaxed) {
return None;
}
match self.fill_buffer(next_response()) {
Ok(()) => {}
Err(()) => return None,
}
}
}
fn fill_buffer(&self, response: Option<Response>) -> Result<(), ()> {
match response {
Some(Ok(message)) if message.message_type() == T::MESSAGE_TYPE => {
let mut buffer = self.buffer.lock().unwrap();
let (ticks, done) = T::decode(&message).unwrap();
buffer.append(&mut ticks.into());
self.done.store(done, Ordering::Relaxed);
Ok(())
}
Some(Ok(message)) => {
debug!("unexpected message: {message:?}");
Ok(())
}
Some(Err(e)) => {
self.set_error(e);
Err(())
}
None => Err(()),
}
}
fn next_buffered(&self) -> Option<T> {
let mut buffer = self.buffer.lock().unwrap();
buffer.pop_front()
}
fn set_error(&self, e: Error) {
let mut error = self.error.lock().unwrap();
*error = Some(e);
}
fn clear_error(&self) {
let mut error = self.error.lock().unwrap();
*error = None;
}
}
impl<T: TickDecoder<T>> Drop for TickSubscription<T> {
fn drop(&mut self) {
if !self.done.load(Ordering::Relaxed) {
self.cancel();
}
}
}
/// An iterator that yields items as they become available, blocking if necessary.
pub struct TickSubscriptionIter<'a, T: TickDecoder<T>> {
subscription: &'a TickSubscription<T>,
}
impl<T: TickDecoder<T>> Iterator for TickSubscriptionIter<'_, T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.subscription.next()
}
}
impl<'a, T: TickDecoder<T>> IntoIterator for &'a TickSubscription<T> {
type Item = T;
type IntoIter = TickSubscriptionIter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
/// An iterator that yields items as they become available, blocking if necessary.
pub struct TickSubscriptionOwnedIter<T: TickDecoder<T>> {
subscription: TickSubscription<T>,
}
impl<T: TickDecoder<T>> Iterator for TickSubscriptionOwnedIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.subscription.next()
}
}
impl<T: TickDecoder<T>> IntoIterator for TickSubscription<T> {
type Item = T;
type IntoIter = TickSubscriptionOwnedIter<T>;
fn into_iter(self) -> Self::IntoIter {
TickSubscriptionOwnedIter { subscription: self }
}
}
/// An iterator that yields items if they are available, without waiting.
pub struct TickSubscriptionTryIter<'a, T: TickDecoder<T>> {
subscription: &'a TickSubscription<T>,
}
impl<T: TickDecoder<T>> Iterator for TickSubscriptionTryIter<'_, T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.subscription.try_next()
}
}
/// An iterator that waits for the specified timeout duration for available data.
pub struct TickSubscriptionTimeoutIter<'a, T: TickDecoder<T>> {
subscription: &'a TickSubscription<T>,
timeout: std::time::Duration,
}
impl<T: TickDecoder<T>> Iterator for TickSubscriptionTimeoutIter<'_, T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.subscription.next_timeout(self.timeout)
}
}
#[cfg(test)]
#[path = "sync_tests.rs"]
mod tests;