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
//! Stream Retry example
//!
//! # Usage
//!
//! ```bash
//! cargo run --features sync --example stream_retry
//! ```
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
use ibapi::market_data::TradingHours;
fn main() {
env_logger::init();
let connection_url = "127.0.0.1:4002";
let client = Client::connect(connection_url, 100).expect("connection to TWS failed!");
let contract = Contract::stock("AAPL").build();
'retry: loop {
// Request real-time bars data with 5-second intervals
let subscription = client
.realtime_bars(&contract)
.trading_hours(TradingHours::Extended)
.subscribe()
.expect("realtime bars request failed!");
for bar in subscription.iter_data() {
match bar {
Ok(bar) => println!("bar: {bar:?}"),
Err(e) if e.is_connection_lost() => {
eprintln!("Connection lost. Retrying stream...");
continue 'retry;
}
// Everything else — including terminal ConnectionFailed (reconnect
// exhausted, client shut down) — is not recoverable here, so give up.
Err(e) => {
eprintln!("error: {e}");
break 'retry;
}
}
}
break;
}
}