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
use std::time::Duration;
use crate::contracts::Contract;
use crate::market_data::realtime::TickTypes;
use crate::Error;
#[cfg(test)]
mod tests;
/// Builder for creating market data subscriptions with a fluent interface
#[must_use = "MarketDataBuilder does nothing until you call .subscribe()"]
pub struct MarketDataBuilder<'a, C> {
client: &'a C,
contract: &'a Contract,
generic_ticks: Vec<String>,
snapshot: bool,
regulatory_snapshot: bool,
}
impl<'a, C> MarketDataBuilder<'a, C> {
/// Creates a new MarketDataBuilder
pub fn new(client: &'a C, contract: &'a Contract) -> Self {
Self {
client,
contract,
generic_ticks: Vec::new(),
snapshot: false,
regulatory_snapshot: false,
}
}
/// Replace the generic tick list to subscribe to
///
/// Each value is a numeric IB *generic tick request ID* (the
/// `genericTickList` parameter on `reqMktData`). To add ticks one at a
/// time, use [`Self::add_generic_tick`] instead.
///
/// # Arguments
/// * `ticks` - Slice of generic tick request IDs. Prefer the named
/// constants in
/// [`crate::market_data::realtime::generic_tick`] over raw numeric
/// strings.
///
/// # Examples
///
/// ```no_run
/// # #[cfg(feature = "sync")]
/// # {
/// use ibapi::client::blocking::Client;
/// use ibapi::contracts::Contract;
/// use ibapi::market_data::realtime::generic_tick;
///
/// let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
/// let contract = Contract::stock("AAPL").build();
///
/// let subscription = client
/// .market_data(&contract)
/// .generic_ticks(&[generic_tick::RT_VOLUME, generic_tick::SHORTABLE])
/// .subscribe()
/// .expect("subscription failed");
/// # let _ = subscription;
/// # }
/// ```
///
/// See: <https://interactivebrokers.github.io/tws-api/tick_types.html>
pub fn generic_ticks(mut self, ticks: &[&str]) -> Self {
self.generic_ticks = ticks.iter().map(|s| s.to_string()).collect();
self
}
/// Append a single generic tick ID to the subscription
///
/// Multiple calls accumulate; use [`Self::generic_ticks`] to replace the
/// list in one shot. Pairs naturally with conditional composition (e.g.
/// only add [`generic_tick::SHORTABLE`] for stocks). Prefer the named
/// constants over raw numeric strings.
///
/// See [`Self::subscribe`] for a runnable end-to-end example.
///
/// [`generic_tick::SHORTABLE`]: crate::market_data::realtime::generic_tick::SHORTABLE
pub fn add_generic_tick(mut self, tick: impl AsRef<str>) -> Self {
self.generic_ticks.push(tick.as_ref().to_string());
self
}
/// Request a one-time snapshot of market data
///
/// When enabled, the subscription will receive current market data once
/// and then automatically end with a SnapshotEnd tick type.
pub fn snapshot(mut self) -> Self {
self.snapshot = true;
self
}
/// Request regulatory snapshot
///
/// For U.S. stocks, a regulatory snapshot request requires the
/// subscription of Market Data for US Securities and Futures Snapshot Bundle.
pub fn regulatory_snapshot(mut self) -> Self {
self.regulatory_snapshot = true;
self
}
/// Enable real-time streaming data (default)
///
/// This is the default behavior - data will stream continuously
/// until the subscription is cancelled.
pub fn streaming(mut self) -> Self {
self.snapshot = false;
self
}
}
// Sync implementation
#[cfg(feature = "sync")]
impl<'a> MarketDataBuilder<'a, crate::client::sync::Client> {
/// Subscribe to market data
///
/// Returns a subscription that yields TickTypes as market data arrives.
///
/// # Examples
///
/// ```no_run
/// use ibapi::client::blocking::Client;
/// use ibapi::contracts::Contract;
/// use ibapi::market_data::realtime::{generic_tick, TickTypes};
///
/// let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
/// let contract = Contract::stock("AAPL").build();
///
/// let subscription = client.market_data(&contract)
/// .add_generic_tick(generic_tick::RT_VOLUME)
/// .add_generic_tick(generic_tick::SHORTABLE)
/// .subscribe()
/// .expect("subscription failed");
///
/// for tick in &subscription {
/// println!("{tick:?}");
/// }
/// ```
pub fn subscribe(self) -> Result<crate::subscriptions::sync::Subscription<TickTypes>, Error> {
let generic_ticks: Vec<&str> = self.generic_ticks.iter().map(|s| s.as_str()).collect();
crate::market_data::realtime::sync::market_data(self.client, self.contract, &generic_ticks, self.snapshot, self.regulatory_snapshot)
}
/// Request a one-shot snapshot and collect the resulting ticks.
///
/// Forces [`snapshot`](Self::snapshot) mode, subscribes, and collects every
/// tick until the snapshot completes (or `timeout` elapses), returning the
/// accumulated [`TickTypes`] for the caller to map into a domain struct.
/// This replaces the hand-written collect-with-timeout loop. See
/// [`Subscription::collect_for`](crate::subscriptions::sync::Subscription::collect_for)
/// for the underlying terminal and its stop conditions.
///
/// # Examples
///
/// ```no_run
/// use ibapi::client::blocking::Client;
/// use ibapi::contracts::Contract;
/// use std::time::Duration;
///
/// let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
/// let contract = Contract::stock("AAPL").build();
///
/// let ticks = client.market_data(&contract).snapshot_once(Duration::from_secs(5)).expect("snapshot failed");
/// println!("collected {} ticks", ticks.len());
/// ```
pub fn snapshot_once(mut self, timeout: Duration) -> Result<Vec<TickTypes>, Error> {
self.snapshot = true;
let subscription = self.subscribe()?;
Ok(subscription.collect_for(timeout))
}
}
// Async implementation
#[cfg(feature = "async")]
impl<'a> MarketDataBuilder<'a, crate::client::r#async::Client> {
/// Subscribe to market data
///
/// Returns a subscription that yields TickTypes as market data arrives.
///
/// # Examples
///
/// ```no_run
/// use ibapi::market_data::realtime::generic_tick;
/// 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("AAPL").build();
///
/// let mut subscription = client.market_data(&contract)
/// .add_generic_tick(generic_tick::RT_VOLUME)
/// .add_generic_tick(generic_tick::SHORTABLE)
/// .subscribe()
/// .await
/// .expect("subscription failed");
///
/// while let Some(tick) = subscription.next().await {
/// println!("{tick:?}");
/// }
/// }
/// ```
pub async fn subscribe(self) -> Result<crate::subscriptions::Subscription<TickTypes>, Error> {
let generic_ticks: Vec<&str> = self.generic_ticks.iter().map(|s| s.as_str()).collect();
self.client
.subscribe_market_data(self.contract, &generic_ticks, self.snapshot, self.regulatory_snapshot)
.await
}
/// Request a one-shot snapshot and collect the resulting ticks.
///
/// Forces [`snapshot`](Self::snapshot) mode, subscribes, and collects every
/// tick until the snapshot completes (or `timeout` elapses), returning the
/// accumulated [`TickTypes`] for the caller to map into a domain struct.
/// This replaces the hand-written collect-with-timeout loop. See
/// [`Subscription::collect_for`](crate::subscriptions::Subscription::collect_for)
/// for the underlying terminal and its stop conditions.
///
/// # Examples
///
/// ```no_run
/// use ibapi::prelude::*;
/// use std::time::Duration;
///
/// #[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();
///
/// let ticks = client.market_data(&contract).snapshot_once(Duration::from_secs(5)).await.expect("snapshot failed");
/// println!("collected {} ticks", ticks.len());
/// }
/// ```
pub async fn snapshot_once(mut self, timeout: Duration) -> Result<Vec<TickTypes>, Error> {
self.snapshot = true;
let mut subscription = self.subscribe().await?;
Ok(subscription.collect_for(timeout).await)
}
}