ibapi 2.11.1

A Rust implementation of the Interactive Brokers TWS API, providing a reliable and user friendly interface for TWS and IB Gateway. Designed with a focus on simplicity and performance.
Documentation
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
//! Type-safe builders for different contract types.

use super::types::*;
use super::{ComboLeg, Contract, SecurityType};
use crate::Error;

/// Stock contract builder with type-safe API
#[derive(Debug, Clone)]
pub struct StockBuilder<S = Missing> {
    symbol: S,
    exchange: Exchange,
    currency: Currency,
    primary_exchange: Option<Exchange>,
    trading_class: Option<String>,
}

impl StockBuilder<Missing> {
    /// Start building a stock contract for the provided symbol.
    pub fn new(symbol: impl Into<Symbol>) -> StockBuilder<Symbol> {
        StockBuilder {
            symbol: symbol.into(),
            exchange: "SMART".into(),
            currency: "USD".into(),
            primary_exchange: None,
            trading_class: None,
        }
    }
}

impl StockBuilder<Symbol> {
    /// Route the order to the specified exchange instead of the default.
    pub fn on_exchange(mut self, exchange: impl Into<Exchange>) -> Self {
        self.exchange = exchange.into();
        self
    }

    /// Quote the contract in a different currency.
    pub fn in_currency(mut self, currency: impl Into<Currency>) -> Self {
        self.currency = currency.into();
        self
    }

    /// Prefer a specific primary exchange when resolving the contract.
    pub fn primary(mut self, exchange: impl Into<Exchange>) -> Self {
        self.primary_exchange = Some(exchange.into());
        self
    }

    /// Hint the trading class for venues that require it.
    pub fn trading_class(mut self, class: impl Into<String>) -> Self {
        self.trading_class = Some(class.into());
        self
    }

    /// Build the contract - cannot fail for stocks
    pub fn build(self) -> Contract {
        Contract {
            symbol: self.symbol,
            security_type: SecurityType::Stock,
            exchange: self.exchange,
            currency: self.currency,
            primary_exchange: self.primary_exchange.unwrap_or_else(|| Exchange::from("")),
            trading_class: self.trading_class.unwrap_or_default(),
            ..Default::default()
        }
    }
}

/// Option contract builder with type states for required fields
#[derive(Debug, Clone)]
pub struct OptionBuilder<Symbol = Missing, Strike = Missing, Expiry = Missing> {
    symbol: Symbol,
    right: OptionRight,
    strike: Strike,
    expiry: Expiry,
    exchange: Exchange,
    currency: Currency,
    multiplier: u32,
    primary_exchange: Option<Exchange>,
    trading_class: Option<String>,
}

impl OptionBuilder<Missing, Missing, Missing> {
    /// Begin constructing a call option contract for the provided symbol.
    pub fn call(symbol: impl Into<Symbol>) -> OptionBuilder<Symbol, Missing, Missing> {
        OptionBuilder {
            symbol: symbol.into(),
            right: OptionRight::Call,
            strike: Missing,
            expiry: Missing,
            exchange: "SMART".into(),
            currency: "USD".into(),
            multiplier: 100,
            primary_exchange: None,
            trading_class: None,
        }
    }

    /// Begin constructing a put option contract for the provided symbol.
    pub fn put(symbol: impl Into<Symbol>) -> OptionBuilder<Symbol, Missing, Missing> {
        OptionBuilder {
            symbol: symbol.into(),
            right: OptionRight::Put,
            strike: Missing,
            expiry: Missing,
            exchange: "SMART".into(),
            currency: "USD".into(),
            multiplier: 100,
            primary_exchange: None,
            trading_class: None,
        }
    }
}

// Can only set strike when symbol is present
impl<E> OptionBuilder<Symbol, Missing, E> {
    /// Specify the option strike price.
    pub fn strike(self, price: f64) -> OptionBuilder<Symbol, Strike, E> {
        OptionBuilder {
            symbol: self.symbol,
            right: self.right,
            strike: Strike::new_unchecked(price),
            expiry: self.expiry,
            exchange: self.exchange,
            currency: self.currency,
            multiplier: self.multiplier,
            primary_exchange: self.primary_exchange,
            trading_class: self.trading_class,
        }
    }
}

// Can only set expiry when symbol is present
impl<S> OptionBuilder<Symbol, S, Missing> {
    /// Provide an explicit expiration date.
    pub fn expires(self, date: ExpirationDate) -> OptionBuilder<Symbol, S, ExpirationDate> {
        OptionBuilder {
            symbol: self.symbol,
            right: self.right,
            strike: self.strike,
            expiry: date,
            exchange: self.exchange,
            currency: self.currency,
            multiplier: self.multiplier,
            primary_exchange: self.primary_exchange,
            trading_class: self.trading_class,
        }
    }

    /// Convenience helper to set a specific calendar date.
    pub fn expires_on(self, year: u16, month: u8, day: u8) -> OptionBuilder<Symbol, S, ExpirationDate> {
        self.expires(ExpirationDate::new(year, month, day))
    }

    /// Set the expiry to the next Friday weekly contract.
    pub fn expires_weekly(self) -> OptionBuilder<Symbol, S, ExpirationDate> {
        self.expires(ExpirationDate::next_friday())
    }

    /// Set the expiry to the standard monthly contract.
    pub fn expires_monthly(self) -> OptionBuilder<Symbol, S, ExpirationDate> {
        self.expires(ExpirationDate::third_friday_of_month())
    }
}

// Optional setters available at any stage when symbol is present
impl<S, E> OptionBuilder<Symbol, S, E> {
    /// Route the option to a specific exchange.
    pub fn on_exchange(mut self, exchange: impl Into<Exchange>) -> Self {
        self.exchange = exchange.into();
        self
    }

    /// Quote the option in a different currency.
    pub fn in_currency(mut self, currency: impl Into<Currency>) -> Self {
        self.currency = currency.into();
        self
    }

    /// Override the contract multiplier (defaults to 100).
    pub fn multiplier(mut self, multiplier: u32) -> Self {
        self.multiplier = multiplier;
        self
    }

    /// Prefer a specific primary exchange when resolving the option.
    pub fn primary(mut self, exchange: impl Into<Exchange>) -> Self {
        self.primary_exchange = Some(exchange.into());
        self
    }

    /// Hint the trading class used by this contract.
    pub fn trading_class(mut self, class: impl Into<String>) -> Self {
        self.trading_class = Some(class.into());
        self
    }
}

// Build only available when all required fields are set
impl OptionBuilder<Symbol, Strike, ExpirationDate> {
    /// Finalize the option contract once symbol, strike, and expiry are set.
    pub fn build(self) -> Contract {
        Contract {
            symbol: self.symbol,
            security_type: SecurityType::Option,
            strike: self.strike.value(),
            right: self.right.to_string(),
            last_trade_date_or_contract_month: self.expiry.to_string(),
            exchange: self.exchange,
            currency: self.currency,
            multiplier: self.multiplier.to_string(),
            primary_exchange: self.primary_exchange.unwrap_or_else(|| Exchange::from("")),
            trading_class: self.trading_class.unwrap_or_default(),
            ..Default::default()
        }
    }
}

/// Futures contract builder with type states
#[derive(Debug, Clone)]
pub struct FuturesBuilder<Symbol = Missing, Month = Missing> {
    symbol: Symbol,
    contract_month: Month,
    exchange: Exchange,
    currency: Currency,
    multiplier: Option<u32>,
}

impl FuturesBuilder<Missing, Missing> {
    /// Start building a futures contract for the given symbol.
    pub fn new(symbol: impl Into<Symbol>) -> FuturesBuilder<Symbol, Missing> {
        FuturesBuilder {
            symbol: symbol.into(),
            contract_month: Missing,
            exchange: "GLOBEX".into(),
            currency: "USD".into(),
            multiplier: None,
        }
    }
}

impl FuturesBuilder<Symbol, Missing> {
    /// Specify the contract month to target for the future.
    pub fn expires_in(self, month: ContractMonth) -> FuturesBuilder<Symbol, ContractMonth> {
        FuturesBuilder {
            symbol: self.symbol,
            contract_month: month,
            exchange: self.exchange,
            currency: self.currency,
            multiplier: self.multiplier,
        }
    }

    /// Shortcut for selecting the current front-month contract.
    pub fn front_month(self) -> FuturesBuilder<Symbol, ContractMonth> {
        self.expires_in(ContractMonth::front())
    }

    /// Shortcut for selecting the next quarterly contract.
    pub fn next_quarter(self) -> FuturesBuilder<Symbol, ContractMonth> {
        self.expires_in(ContractMonth::next_quarter())
    }
}

impl<M> FuturesBuilder<Symbol, M> {
    /// Route the futures contract to a specific exchange.
    pub fn on_exchange(mut self, exchange: impl Into<Exchange>) -> Self {
        self.exchange = exchange.into();
        self
    }

    /// Quote the future in a different currency.
    pub fn in_currency(mut self, currency: impl Into<Currency>) -> Self {
        self.currency = currency.into();
        self
    }

    /// Set a custom multiplier value for the contract.
    pub fn multiplier(mut self, value: u32) -> Self {
        self.multiplier = Some(value);
        self
    }
}

impl FuturesBuilder<Symbol, ContractMonth> {
    /// Finalize the futures contract once the contract month is chosen.
    pub fn build(self) -> Contract {
        Contract {
            symbol: self.symbol,
            security_type: SecurityType::Future,
            last_trade_date_or_contract_month: self.contract_month.to_string(),
            exchange: self.exchange,
            currency: self.currency,
            multiplier: self.multiplier.map(|m| m.to_string()).unwrap_or_default(),
            ..Default::default()
        }
    }
}

/// Continuous futures contract builder with type states
#[derive(Debug, Clone)]
pub struct ContinuousFuturesBuilder<Symbol = Missing> {
    symbol: Symbol,
    exchange: Exchange,
    currency: Currency,
    multiplier: Option<u32>,
}

impl ContinuousFuturesBuilder<Missing> {
    /// Create a continuous future contract for the given symbol.
    pub fn new(symbol: impl Into<Symbol>) -> ContinuousFuturesBuilder<Symbol> {
        ContinuousFuturesBuilder {
            symbol: symbol.into(),
            exchange: "GLOBEX".into(),
            currency: "USD".into(),
            multiplier: None,
        }
    }
}

impl ContinuousFuturesBuilder<Symbol> {
    /// Route the continuous future to a specific exchange.
    pub fn on_exchange(mut self, exchange: impl Into<Exchange>) -> Self {
        self.exchange = exchange.into();
        self
    }

    /// Quote the continuous future in a different currency.
    pub fn in_currency(mut self, currency: impl Into<Currency>) -> Self {
        self.currency = currency.into();
        self
    }

    /// Set a custom multiplier value for the continuous future.
    pub fn multiplier(mut self, value: u32) -> Self {
        self.multiplier = Some(value);
        self
    }

    /// Finalize the continuous future contract definition.
    pub fn build(self) -> Contract {
        Contract {
            symbol: self.symbol,
            security_type: SecurityType::ContinuousFuture,
            exchange: self.exchange,
            currency: self.currency,
            multiplier: self.multiplier.map(|m| m.to_string()).unwrap_or_default(),
            ..Default::default()
        }
    }
}

/// Forex pair builder
#[derive(Debug, Clone)]
pub struct ForexBuilder {
    base: Currency,
    quote: Currency,
    exchange: Exchange,
}

impl ForexBuilder {
    /// Create a forex contract using the given base and quote currencies.
    pub fn new(base: impl Into<Currency>, quote: impl Into<Currency>) -> Self {
        ForexBuilder {
            base: base.into(),
            quote: quote.into(),
            exchange: "IDEALPRO".into(),
        }
    }

    /// Route the trade to a different forex venue.
    pub fn on_exchange(mut self, exchange: impl Into<Exchange>) -> Self {
        self.exchange = exchange.into();
        self
    }

    /// Complete the forex contract definition.
    pub fn build(self) -> Contract {
        Contract {
            symbol: Symbol::new(self.base.0),
            security_type: SecurityType::ForexPair,
            exchange: self.exchange,
            currency: self.quote,
            ..Default::default()
        }
    }
}

/// Crypto currency builder
#[derive(Debug, Clone)]
pub struct CryptoBuilder {
    symbol: Symbol,
    exchange: Exchange,
    currency: Currency,
}

impl CryptoBuilder {
    /// Create a crypto contract for the specified symbol (e.g. `BTC`).
    pub fn new(symbol: impl Into<Symbol>) -> Self {
        CryptoBuilder {
            symbol: symbol.into(),
            exchange: "PAXOS".into(),
            currency: "USD".into(),
        }
    }

    /// Route the trade to a specific crypto venue.
    pub fn on_exchange(mut self, exchange: impl Into<Exchange>) -> Self {
        self.exchange = exchange.into();
        self
    }

    /// Quote the pair in an alternate fiat or stablecoin.
    pub fn in_currency(mut self, currency: impl Into<Currency>) -> Self {
        self.currency = currency.into();
        self
    }

    /// Finish building the crypto contract.
    pub fn build(self) -> Contract {
        Contract {
            symbol: self.symbol,
            security_type: SecurityType::Crypto,
            exchange: self.exchange,
            currency: self.currency,
            ..Default::default()
        }
    }
}

/// Spread/Combo builder
#[derive(Debug, Clone)]
pub struct SpreadBuilder {
    legs: Vec<Leg>,
    currency: Currency,
    exchange: Exchange,
}

/// Internal representation of a spread leg used by [SpreadBuilder].
#[derive(Debug, Clone)]
pub struct Leg {
    contract_id: i32,
    action: LegAction,
    ratio: i32,
    exchange: Option<Exchange>,
}

impl SpreadBuilder {
    /// Create an empty spread builder ready to accept legs.
    pub fn new() -> Self {
        SpreadBuilder {
            legs: Vec::new(),
            currency: "USD".into(),
            exchange: "SMART".into(),
        }
    }
}

impl Default for SpreadBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl SpreadBuilder {
    /// Begin configuring a new leg for the spread.
    pub fn add_leg(self, contract_id: i32, action: LegAction) -> LegBuilder {
        LegBuilder {
            parent: self,
            leg: Leg {
                contract_id,
                action,
                ratio: 1,
                exchange: None,
            },
        }
    }

    /// Calendar spread convenience method
    pub fn calendar(self, near_id: i32, far_id: i32) -> Self {
        self.add_leg(near_id, LegAction::Buy).done().add_leg(far_id, LegAction::Sell).done()
    }

    /// Vertical spread convenience method
    pub fn vertical(self, long_id: i32, short_id: i32) -> Self {
        self.add_leg(long_id, LegAction::Buy).done().add_leg(short_id, LegAction::Sell).done()
    }

    /// Iron condor spread convenience method
    pub fn iron_condor(self, long_put_id: i32, short_put_id: i32, short_call_id: i32, long_call_id: i32) -> Self {
        self.add_leg(long_put_id, LegAction::Buy)
            .done()
            .add_leg(short_put_id, LegAction::Sell)
            .done()
            .add_leg(short_call_id, LegAction::Sell)
            .done()
            .add_leg(long_call_id, LegAction::Buy)
            .done()
    }

    /// Override the spread currency, useful for non-USD underlyings.
    pub fn in_currency(mut self, currency: impl Into<Currency>) -> Self {
        self.currency = currency.into();
        self
    }

    /// Route the spread order to a specific exchange.
    pub fn on_exchange(mut self, exchange: impl Into<Exchange>) -> Self {
        self.exchange = exchange.into();
        self
    }

    /// Finalize the spread contract, returning an error if no legs were added.
    pub fn build(self) -> Result<Contract, Error> {
        if self.legs.is_empty() {
            return Err(Error::Simple("Spread must have at least one leg".into()));
        }

        let combo_legs: Vec<ComboLeg> = self
            .legs
            .into_iter()
            .map(|leg| ComboLeg {
                contract_id: leg.contract_id,
                ratio: leg.ratio,
                action: leg.action.to_string(),
                exchange: leg.exchange.map(|e| e.to_string()).unwrap_or_default(),
                ..Default::default()
            })
            .collect();

        Ok(Contract {
            security_type: SecurityType::Spread,
            currency: self.currency,
            exchange: self.exchange,
            combo_legs,
            ..Default::default()
        })
    }
}

/// Builder for individual spread legs
pub struct LegBuilder {
    parent: SpreadBuilder,
    leg: Leg,
}

impl LegBuilder {
    /// Set the contract ratio for the current leg.
    pub fn ratio(mut self, ratio: i32) -> Self {
        self.leg.ratio = ratio;
        self
    }

    /// Target a specific exchange for the leg.
    pub fn on_exchange(mut self, exchange: impl Into<Exchange>) -> Self {
        self.leg.exchange = Some(exchange.into());
        self
    }

    /// Finish the leg and return control to the parent spread builder.
    pub fn done(mut self) -> SpreadBuilder {
        self.parent.legs.push(self.leg);
        self.parent
    }
}

#[cfg(test)]
mod tests;