ibapi 3.0.0

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
use super::super::{ComboLeg, Contract, Currency, DeltaNeutralContract, Exchange, OptionRight, SecurityIdType, SecurityType, Symbol};
use crate::Error;

/// Builder for creating and validating [Contract] instances
///
/// The [ContractBuilder] provides a fluent interface for constructing contracts with validation.
/// It ensures that contracts are properly configured for their security type and prevents
/// common errors through compile-time and runtime validation.
///
/// # Examples
///
/// ## Creating a Stock Contract
///
/// ```no_run
/// use ibapi::contracts::{ContractBuilder, SecurityType};
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// // Using the builder pattern
/// let contract = ContractBuilder::new()
///     .symbol("AAPL")
///     .security_type(SecurityType::Stock)
///     .exchange("SMART")
///     .currency("USD")
///     .build()?;
///
/// // Using the convenience method
/// let contract = ContractBuilder::stock("AAPL", "SMART", "USD").build()?;
/// # Ok(())
/// # }
/// ```
///
/// ## Creating an Option Contract
///
/// ```no_run
/// use ibapi::contracts::{ContractBuilder, OptionRight, SecurityType};
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let contract = ContractBuilder::option("AAPL", "SMART", "USD")
///     .strike(150.0)
///     .right(OptionRight::Call)
///     .last_trade_date_or_contract_month("20241220")
///     .build()?;
/// # Ok(())
/// # }
/// ```
///
/// ## Creating a Futures Contract
///
/// ```no_run
/// use ibapi::contracts::{ContractBuilder, SecurityType};
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let contract = ContractBuilder::futures("ES", "CME", "USD")
///     .last_trade_date_or_contract_month("202412")
///     .build()?;
/// # Ok(())
/// # }
/// ```
///
/// ## Creating a Crypto Contract
///
/// ```no_run
/// use ibapi::contracts::{ContractBuilder, SecurityType};
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let contract = ContractBuilder::crypto("BTC", "PAXOS", "USD").build()?;
/// # Ok(())
/// # }
/// ```
///
/// # Validation
///
/// The builder performs validation when [build](ContractBuilder::build) is called:
/// - Symbol is always required
/// - Option contracts require strike, right, and expiration date
/// - Futures contracts require contract month
/// - Strike prices cannot be negative
#[derive(Clone, Debug, Default)]
#[must_use = "ContractBuilder does nothing until you call .build()"]
pub struct ContractBuilder {
    pub(crate) contract_id: Option<i32>,
    pub(crate) symbol: Option<String>,
    pub(crate) security_type: Option<SecurityType>,
    pub(crate) last_trade_date_or_contract_month: Option<String>,
    pub(crate) strike: Option<f64>,
    pub(crate) right: Option<OptionRight>,
    pub(crate) multiplier: Option<String>,
    pub(crate) exchange: Option<String>,
    pub(crate) currency: Option<String>,
    pub(crate) local_symbol: Option<String>,
    pub(crate) primary_exchange: Option<String>,
    pub(crate) trading_class: Option<String>,
    pub(crate) include_expired: Option<bool>,
    pub(crate) security_id_type: Option<SecurityIdType>,
    pub(crate) security_id: Option<String>,
    pub(crate) combo_legs_description: Option<String>,
    pub(crate) combo_legs: Option<Vec<ComboLeg>>,
    pub(crate) delta_neutral_contract: Option<DeltaNeutralContract>,
    pub(crate) last_trade_date: Option<time::Date>,
    pub(crate) issuer_id: Option<String>,
    pub(crate) description: Option<String>,
}

impl ContractBuilder {
    /// Creates a new [ContractBuilder]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ibapi::contracts::{ContractBuilder, SecurityType};
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let contract = ContractBuilder::new()
    ///     .symbol("MSFT")
    ///     .security_type(SecurityType::Stock)
    ///     .exchange("SMART")
    ///     .currency("USD")
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the contract ID
    ///
    /// The unique IB contract identifier. When specified, other contract details may be optional.
    pub fn contract_id(mut self, contract_id: i32) -> Self {
        self.contract_id = Some(contract_id);
        self
    }

    /// Sets the underlying asset symbol
    ///
    /// Required field for all contracts.
    ///
    /// # Examples
    /// - Stocks: "AAPL", "MSFT", "TSLA"
    /// - Futures: "ES", "NQ", "CL"
    /// - Crypto: "BTC", "ETH"
    pub fn symbol<S: Into<String>>(mut self, symbol: S) -> Self {
        self.symbol = Some(symbol.into());
        self
    }

    /// Sets the security type
    ///
    /// Defines what type of instrument this contract represents.
    /// See [SecurityType] for available options.
    pub fn security_type(mut self, security_type: SecurityType) -> Self {
        self.security_type = Some(security_type);
        self
    }

    /// Sets the last trade date or contract month
    ///
    /// For futures and options, this field is required:
    /// - Format YYYYMM for contract month (e.g., "202412")
    /// - Format YYYYMMDD for specific expiration date (e.g., "20241220")
    pub fn last_trade_date_or_contract_month<S: Into<String>>(mut self, date: S) -> Self {
        self.last_trade_date_or_contract_month = Some(date.into());
        self
    }

    /// Sets the option's strike price
    ///
    /// Required for option contracts. Must be a positive value.
    ///
    /// # Examples
    /// ```no_run
    /// use ibapi::contracts::{ContractBuilder, OptionRight};
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let contract = ContractBuilder::option("AAPL", "SMART", "USD")
    ///     .strike(150.0)
    ///     .right(OptionRight::Call)
    ///     .last_trade_date_or_contract_month("20241220")
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn strike(mut self, strike: f64) -> Self {
        self.strike = Some(strike);
        self
    }

    /// Sets the option right (Call or Put).
    ///
    /// Required for option contracts.
    pub fn right(mut self, right: OptionRight) -> Self {
        self.right = Some(right);
        self
    }

    /// Sets the contract multiplier
    ///
    /// For example, options on futures often have a multiplier that differs from
    /// the underlying future's multiplier.
    pub fn multiplier<S: Into<String>>(mut self, multiplier: S) -> Self {
        self.multiplier = Some(multiplier.into());
        self
    }

    /// Sets the exchange for routing orders
    ///
    /// Common values include:
    /// - "SMART" for IB's smart routing
    /// - "NASDAQ", "NYSE", "AMEX" for US equities
    /// - "CME", "NYMEX" for futures
    pub fn exchange<S: Into<String>>(mut self, exchange: S) -> Self {
        self.exchange = Some(exchange.into());
        self
    }

    /// Sets the contract's currency
    ///
    /// Typically "USD" for US markets, "EUR" for European markets, etc.
    pub fn currency<S: Into<String>>(mut self, currency: S) -> Self {
        self.currency = Some(currency.into());
        self
    }

    /// Sets the local symbol
    ///
    /// The symbol within the exchange. Often the same as symbol but can differ
    /// for futures and options contracts.
    pub fn local_symbol<S: Into<String>>(mut self, local_symbol: S) -> Self {
        self.local_symbol = Some(local_symbol.into());
        self
    }

    /// Sets the primary exchange
    ///
    /// The primary listing exchange. Used with SMART routing to define
    /// the contract unambiguously.
    pub fn primary_exchange<S: Into<String>>(mut self, primary_exchange: S) -> Self {
        self.primary_exchange = Some(primary_exchange.into());
        self
    }

    /// Sets the trading class
    ///
    /// For example, options traded on different exchanges may have different
    /// trading class names despite being otherwise identical.
    pub fn trading_class<S: Into<String>>(mut self, trading_class: S) -> Self {
        self.trading_class = Some(trading_class.into());
        self
    }

    /// Sets whether to include expired contracts
    ///
    /// If true, contract details requests can return expired contracts.
    pub fn include_expired(mut self, include_expired: bool) -> Self {
        self.include_expired = Some(include_expired);
        self
    }

    /// Sets the security ID scheme paired with [`security_id`](Self::security_id).
    pub fn security_id_type(mut self, security_id_type: SecurityIdType) -> Self {
        self.security_id_type = Some(security_id_type);
        self
    }

    /// Sets the security ID
    ///
    /// The actual security identifier value corresponding to the security_id_type.
    pub fn security_id<S: Into<String>>(mut self, security_id: S) -> Self {
        self.security_id = Some(security_id.into());
        self
    }

    /// Sets the combo legs description
    ///
    /// For combo orders, provides a human-readable description of the legs.
    pub fn combo_legs_description<S: Into<String>>(mut self, combo_legs_description: S) -> Self {
        self.combo_legs_description = Some(combo_legs_description.into());
        self
    }

    /// Sets the combo legs
    ///
    /// Defines the individual legs for combo/spread contracts.
    pub fn combo_legs(mut self, combo_legs: Vec<ComboLeg>) -> Self {
        self.combo_legs = Some(combo_legs);
        self
    }

    /// Sets the delta neutral contract
    ///
    /// Used for delta-neutral combo orders.
    pub fn delta_neutral_contract(mut self, delta_neutral_contract: DeltaNeutralContract) -> Self {
        self.delta_neutral_contract = Some(delta_neutral_contract);
        self
    }

    /// Sets the last trade date.
    ///
    /// Server responses overwrite this on contract-details round-trips,
    /// so most callers can leave it unset.
    pub fn last_trade_date(mut self, date: time::Date) -> Self {
        self.last_trade_date = Some(date);
        self
    }

    /// Sets the issuer ID
    ///
    /// Primarily used for bond contracts.
    pub fn issuer_id<S: Into<String>>(mut self, issuer_id: S) -> Self {
        self.issuer_id = Some(issuer_id.into());
        self
    }

    /// Sets the contract description
    ///
    /// Human-readable description of the contract.
    pub fn description<S: Into<String>>(mut self, description: S) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Creates a stock contract builder with common defaults
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ibapi::contracts::ContractBuilder;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let contract = ContractBuilder::stock("AAPL", "SMART", "USD")
    ///     .primary_exchange("NASDAQ")
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn stock<S: Into<String>>(symbol: S, exchange: S, currency: S) -> Self {
        Self::new()
            .symbol(symbol)
            .security_type(SecurityType::Stock)
            .exchange(exchange)
            .currency(currency)
    }

    /// Creates an option contract builder with common defaults
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ibapi::contracts::{ContractBuilder, OptionRight};
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let contract = ContractBuilder::option("AAPL", "SMART", "USD")
    ///     .strike(150.0)
    ///     .right(OptionRight::Call)
    ///     .last_trade_date_or_contract_month("20241220")
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn option<S: Into<String>>(symbol: S, exchange: S, currency: S) -> Self {
        Self::new()
            .symbol(symbol)
            .security_type(SecurityType::Option)
            .exchange(exchange)
            .currency(currency)
    }

    /// Creates a futures contract builder with common defaults
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ibapi::contracts::ContractBuilder;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let contract = ContractBuilder::futures("ES", "CME", "USD")
    ///     .last_trade_date_or_contract_month("202412")
    ///     .multiplier("50")
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn futures<S: Into<String>>(symbol: S, exchange: S, currency: S) -> Self {
        Self::new()
            .symbol(symbol)
            .security_type(SecurityType::Future)
            .exchange(exchange)
            .currency(currency)
    }

    /// Creates a continuous futures contract builder with common defaults
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ibapi::contracts::ContractBuilder;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let contract = ContractBuilder::continuous_futures("ES", "CME", "USD")
    ///     .multiplier("50")
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn continuous_futures<S: Into<String>>(symbol: S, exchange: S, currency: S) -> Self {
        Self::new()
            .symbol(symbol)
            .security_type(SecurityType::ContinuousFuture)
            .exchange(exchange)
            .currency(currency)
    }

    /// Creates a crypto contract builder with common defaults
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ibapi::contracts::ContractBuilder;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let contract = ContractBuilder::crypto("BTC", "PAXOS", "USD").build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn crypto<S: Into<String>>(symbol: S, exchange: S, currency: S) -> Self {
        Self::new()
            .symbol(symbol)
            .security_type(SecurityType::Crypto)
            .exchange(exchange)
            .currency(currency)
    }

    /// Builds the final [Contract] instance with validation
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Symbol is not provided
    /// - Option contracts are missing required fields (strike, right, expiration)
    /// - Futures contracts are missing contract month
    /// - Strike price is negative
    pub fn build(self) -> Result<Contract, Error> {
        // Symbol is required unless local_symbol or contract_id is provided
        if self.symbol.is_none() && self.local_symbol.is_none() && self.contract_id.is_none() {
            return Err(Error::InvalidArgument("Symbol, local_symbol, or contract_id is required".into()));
        }

        let security_type = self.security_type.clone().unwrap_or_default();

        // Validate option-specific requirements
        if security_type == SecurityType::Option || security_type == SecurityType::FuturesOption {
            if self.strike.is_none() {
                return Err(Error::InvalidArgument("Strike price is required for options".into()));
            }

            if let Some(strike) = self.strike {
                if strike < 0.0 {
                    return Err(Error::InvalidArgument("Strike price cannot be negative".into()));
                }
            }

            if self.right.is_none() {
                return Err(Error::InvalidArgument(
                    "Right (OptionRight::Call or OptionRight::Put) is required for options".into(),
                ));
            }

            if self.last_trade_date_or_contract_month.is_none() {
                return Err(Error::InvalidArgument("Expiration date is required for options".into()));
            }
        }

        // Validate futures-specific requirements
        if (security_type == SecurityType::Future || security_type == SecurityType::FuturesOption) && self.last_trade_date_or_contract_month.is_none()
        {
            return Err(Error::InvalidArgument("Contract month is required for futures".into()));
        }

        Ok(Contract {
            contract_id: self.contract_id.unwrap_or(0),
            symbol: Symbol::from(self.symbol.unwrap_or_default()),
            security_type,
            last_trade_date_or_contract_month: self.last_trade_date_or_contract_month.unwrap_or_default(),
            strike: self.strike.unwrap_or(0.0),
            right: self.right,
            multiplier: self.multiplier.unwrap_or_default(),
            exchange: Exchange::from(self.exchange.unwrap_or_default()),
            currency: Currency::from(self.currency.unwrap_or_default()),
            local_symbol: self.local_symbol.unwrap_or_default(),
            primary_exchange: Exchange::from(self.primary_exchange.unwrap_or_default()),
            trading_class: self.trading_class.unwrap_or_default(),
            include_expired: self.include_expired.unwrap_or(false),
            security_id_type: self.security_id_type,
            security_id: self.security_id.unwrap_or_default(),
            combo_legs_description: self.combo_legs_description.unwrap_or_default(),
            combo_legs: self.combo_legs.unwrap_or_default(),
            delta_neutral_contract: self.delta_neutral_contract,
            last_trade_date: self.last_trade_date,
            issuer_id: self.issuer_id.unwrap_or_default(),
            description: self.description.unwrap_or_default(),
        })
    }
}

#[cfg(test)]
mod tests;