ibapi 3.0.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
//! Builders for position-related response messages.
//!
//! Produces wire-format payloads for `Position` (61), `PositionEnd` (62),
//! `PositionMulti` (71), and `PositionMultiEnd` (72) at the message version
//! consumed by the current decoders.

use super::{RequestEncoder, ResponseEncoder, ResponseProtoEncoder};
use crate::common::test_utils::helpers::constants::{TEST_ACCOUNT, TEST_CONTRACT_ID, TEST_TICKER_ID};
use crate::messages::OutgoingMessages;
use crate::proto;
use crate::proto::encoders::{some_f64_ne, some_i32_ne, some_str};

const POSITION_VERSION: i32 = 3;
const POSITION_END_VERSION: i32 = 1;
const POSITION_MULTI_VERSION: i32 = 3;

#[derive(Clone, Debug)]
pub struct PositionResponse {
    pub account: String,
    pub contract_id: i32,
    pub symbol: String,
    pub security_type: String,
    pub last_trade_date_or_contract_month: String,
    pub strike: f64,
    pub right: String,
    pub multiplier: String,
    pub exchange: String,
    pub currency: String,
    pub local_symbol: String,
    pub trading_class: String,
    pub position: f64,
    pub average_cost: f64,
}

impl Default for PositionResponse {
    fn default() -> Self {
        Self {
            account: TEST_ACCOUNT.to_string(),
            contract_id: TEST_CONTRACT_ID,
            symbol: "TSLA".to_string(),
            security_type: "STK".to_string(),
            last_trade_date_or_contract_month: String::new(),
            strike: 0.0,
            right: String::new(),
            multiplier: String::new(),
            exchange: "NASDAQ".to_string(),
            currency: "USD".to_string(),
            local_symbol: "TSLA".to_string(),
            trading_class: "NMS".to_string(),
            position: 500.0,
            average_cost: 196.77,
        }
    }
}

impl PositionResponse {
    pub fn account(mut self, v: impl Into<String>) -> Self {
        self.account = v.into();
        self
    }
    pub fn contract_id(mut self, v: i32) -> Self {
        self.contract_id = v;
        self
    }
    pub fn symbol(mut self, v: impl Into<String>) -> Self {
        self.symbol = v.into();
        self
    }
    pub fn security_type(mut self, v: impl Into<String>) -> Self {
        self.security_type = v.into();
        self
    }
    pub fn last_trade_date_or_contract_month(mut self, v: impl Into<String>) -> Self {
        self.last_trade_date_or_contract_month = v.into();
        self
    }
    pub fn strike(mut self, v: f64) -> Self {
        self.strike = v;
        self
    }
    pub fn right(mut self, v: impl Into<String>) -> Self {
        self.right = v.into();
        self
    }
    pub fn multiplier(mut self, v: impl Into<String>) -> Self {
        self.multiplier = v.into();
        self
    }
    pub fn exchange(mut self, v: impl Into<String>) -> Self {
        self.exchange = v.into();
        self
    }
    pub fn currency(mut self, v: impl Into<String>) -> Self {
        self.currency = v.into();
        self
    }
    pub fn local_symbol(mut self, v: impl Into<String>) -> Self {
        self.local_symbol = v.into();
        self
    }
    pub fn trading_class(mut self, v: impl Into<String>) -> Self {
        self.trading_class = v.into();
        self
    }
    pub fn position(mut self, v: f64) -> Self {
        self.position = v;
        self
    }
    pub fn average_cost(mut self, v: f64) -> Self {
        self.average_cost = v;
        self
    }
}

impl ResponseEncoder for PositionResponse {
    fn fields(&self) -> Vec<String> {
        vec![
            "61".to_string(),
            POSITION_VERSION.to_string(),
            self.account.clone(),
            self.contract_id.to_string(),
            self.symbol.clone(),
            self.security_type.clone(),
            self.last_trade_date_or_contract_month.clone(),
            self.strike.to_string(),
            self.right.clone(),
            self.multiplier.clone(),
            self.exchange.clone(),
            self.currency.clone(),
            self.local_symbol.clone(),
            self.trading_class.clone(),
            self.position.to_string(),
            self.average_cost.to_string(),
        ]
    }
}

impl ResponseProtoEncoder for PositionResponse {
    type Proto = proto::Position;

    fn to_proto(&self) -> Self::Proto {
        proto::Position {
            account: Some(self.account.clone()),
            contract: Some(proto::Contract {
                con_id: some_i32_ne(self.contract_id, 0),
                symbol: some_str(&self.symbol),
                sec_type: some_str(&self.security_type),
                last_trade_date_or_contract_month: some_str(&self.last_trade_date_or_contract_month),
                strike: some_f64_ne(self.strike, 0.0),
                right: some_str(&self.right),
                multiplier: self.multiplier.parse::<f64>().ok(),
                exchange: some_str(&self.exchange),
                currency: some_str(&self.currency),
                local_symbol: some_str(&self.local_symbol),
                trading_class: some_str(&self.trading_class),
                ..Default::default()
            }),
            position: Some(self.position.to_string()),
            avg_cost: Some(self.average_cost),
        }
    }
}

#[derive(Clone, Debug, Default)]
pub struct PositionEndResponse;

impl ResponseEncoder for PositionEndResponse {
    fn fields(&self) -> Vec<String> {
        vec!["62".to_string(), POSITION_END_VERSION.to_string()]
    }
}

impl ResponseProtoEncoder for PositionEndResponse {
    type Proto = proto::PositionEnd;

    fn to_proto(&self) -> Self::Proto {
        proto::PositionEnd {}
    }
}

#[derive(Clone, Debug)]
pub struct PositionMultiResponse {
    pub request_id: i32,
    pub account: String,
    pub contract_id: i32,
    pub symbol: String,
    pub security_type: String,
    pub last_trade_date_or_contract_month: String,
    pub strike: f64,
    pub right: String,
    pub multiplier: String,
    pub exchange: String,
    pub currency: String,
    pub local_symbol: String,
    pub trading_class: String,
    pub position: f64,
    pub average_cost: f64,
    pub model_code: String,
}

impl Default for PositionMultiResponse {
    fn default() -> Self {
        Self {
            request_id: TEST_TICKER_ID,
            account: TEST_ACCOUNT.to_string(),
            contract_id: TEST_CONTRACT_ID,
            symbol: "TSLA".to_string(),
            security_type: "STK".to_string(),
            last_trade_date_or_contract_month: String::new(),
            strike: 0.0,
            right: String::new(),
            multiplier: String::new(),
            exchange: "NASDAQ".to_string(),
            currency: "USD".to_string(),
            local_symbol: "TSLA".to_string(),
            trading_class: "NMS".to_string(),
            position: 500.0,
            average_cost: 196.77,
            model_code: String::new(),
        }
    }
}

impl PositionMultiResponse {
    pub fn request_id(mut self, v: i32) -> Self {
        self.request_id = v;
        self
    }
    pub fn account(mut self, v: impl Into<String>) -> Self {
        self.account = v.into();
        self
    }
    pub fn contract_id(mut self, v: i32) -> Self {
        self.contract_id = v;
        self
    }
    pub fn symbol(mut self, v: impl Into<String>) -> Self {
        self.symbol = v.into();
        self
    }
    pub fn security_type(mut self, v: impl Into<String>) -> Self {
        self.security_type = v.into();
        self
    }
    pub fn last_trade_date_or_contract_month(mut self, v: impl Into<String>) -> Self {
        self.last_trade_date_or_contract_month = v.into();
        self
    }
    pub fn strike(mut self, v: f64) -> Self {
        self.strike = v;
        self
    }
    pub fn right(mut self, v: impl Into<String>) -> Self {
        self.right = v.into();
        self
    }
    pub fn multiplier(mut self, v: impl Into<String>) -> Self {
        self.multiplier = v.into();
        self
    }
    pub fn exchange(mut self, v: impl Into<String>) -> Self {
        self.exchange = v.into();
        self
    }
    pub fn currency(mut self, v: impl Into<String>) -> Self {
        self.currency = v.into();
        self
    }
    pub fn local_symbol(mut self, v: impl Into<String>) -> Self {
        self.local_symbol = v.into();
        self
    }
    pub fn trading_class(mut self, v: impl Into<String>) -> Self {
        self.trading_class = v.into();
        self
    }
    pub fn position(mut self, v: f64) -> Self {
        self.position = v;
        self
    }
    pub fn average_cost(mut self, v: f64) -> Self {
        self.average_cost = v;
        self
    }
    pub fn model_code(mut self, v: impl Into<String>) -> Self {
        self.model_code = v.into();
        self
    }
}

impl ResponseEncoder for PositionMultiResponse {
    fn fields(&self) -> Vec<String> {
        vec![
            "71".to_string(),
            POSITION_MULTI_VERSION.to_string(),
            self.request_id.to_string(),
            self.account.clone(),
            self.contract_id.to_string(),
            self.symbol.clone(),
            self.security_type.clone(),
            self.last_trade_date_or_contract_month.clone(),
            self.strike.to_string(),
            self.right.clone(),
            self.multiplier.clone(),
            self.exchange.clone(),
            self.currency.clone(),
            self.local_symbol.clone(),
            self.trading_class.clone(),
            self.position.to_string(),
            self.average_cost.to_string(),
            self.model_code.clone(),
        ]
    }
}

impl ResponseProtoEncoder for PositionMultiResponse {
    type Proto = proto::PositionMulti;

    fn to_proto(&self) -> Self::Proto {
        proto::PositionMulti {
            req_id: Some(self.request_id),
            account: Some(self.account.clone()),
            contract: Some(proto::Contract {
                con_id: some_i32_ne(self.contract_id, 0),
                symbol: some_str(&self.symbol),
                sec_type: some_str(&self.security_type),
                last_trade_date_or_contract_month: some_str(&self.last_trade_date_or_contract_month),
                strike: some_f64_ne(self.strike, 0.0),
                right: some_str(&self.right),
                multiplier: self.multiplier.parse::<f64>().ok(),
                exchange: some_str(&self.exchange),
                currency: some_str(&self.currency),
                local_symbol: some_str(&self.local_symbol),
                trading_class: some_str(&self.trading_class),
                ..Default::default()
            }),
            position: Some(self.position.to_string()),
            avg_cost: Some(self.average_cost),
            model_code: some_str(&self.model_code),
        }
    }
}

request_id_response_builder!(PositionMultiEndResponse, "72", PositionMultiEnd);

// === Request builders ===

#[derive(Clone, Copy, Debug, Default)]
pub struct PositionsRequestBuilder;

impl RequestEncoder for PositionsRequestBuilder {
    type Proto = proto::PositionsRequest;
    const MSG_ID: OutgoingMessages = OutgoingMessages::RequestPositions;

    fn to_proto(&self) -> Self::Proto {
        proto::PositionsRequest {}
    }
}

#[derive(Clone, Copy, Debug, Default)]
pub struct CancelPositionsRequestBuilder;

impl RequestEncoder for CancelPositionsRequestBuilder {
    type Proto = proto::CancelPositions;
    const MSG_ID: OutgoingMessages = OutgoingMessages::CancelPositions;

    fn to_proto(&self) -> Self::Proto {
        proto::CancelPositions {}
    }
}

#[derive(Clone, Debug)]
pub struct PositionsMultiRequestBuilder {
    pub request_id: i32,
    pub account: String,
    pub model_code: Option<String>,
}

impl Default for PositionsMultiRequestBuilder {
    fn default() -> Self {
        Self {
            request_id: TEST_TICKER_ID,
            account: TEST_ACCOUNT.to_string(),
            model_code: None,
        }
    }
}

impl PositionsMultiRequestBuilder {
    pub fn request_id(mut self, v: i32) -> Self {
        self.request_id = v;
        self
    }
    pub fn account(mut self, v: impl Into<String>) -> Self {
        self.account = v.into();
        self
    }
    pub fn model_code(mut self, v: impl Into<String>) -> Self {
        self.model_code = Some(v.into());
        self
    }
}

impl RequestEncoder for PositionsMultiRequestBuilder {
    type Proto = proto::PositionsMultiRequest;
    const MSG_ID: OutgoingMessages = OutgoingMessages::RequestPositionsMulti;

    fn to_proto(&self) -> Self::Proto {
        proto::PositionsMultiRequest {
            req_id: Some(self.request_id),
            account: Some(self.account.clone()),
            model_code: self.model_code.clone(),
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub struct CancelPositionsMultiRequestBuilder {
    pub request_id: i32,
}

impl Default for CancelPositionsMultiRequestBuilder {
    fn default() -> Self {
        Self { request_id: TEST_TICKER_ID }
    }
}

impl CancelPositionsMultiRequestBuilder {
    pub fn request_id(mut self, v: i32) -> Self {
        self.request_id = v;
        self
    }
}

impl RequestEncoder for CancelPositionsMultiRequestBuilder {
    type Proto = proto::CancelPositionsMulti;
    const MSG_ID: OutgoingMessages = OutgoingMessages::CancelPositionsMulti;

    fn to_proto(&self) -> Self::Proto {
        proto::CancelPositionsMulti {
            req_id: Some(self.request_id),
        }
    }
}

pub fn position() -> PositionResponse {
    PositionResponse::default()
}

pub fn position_end() -> PositionEndResponse {
    PositionEndResponse
}

pub fn position_multi() -> PositionMultiResponse {
    PositionMultiResponse::default()
}

pub fn position_multi_end() -> PositionMultiEndResponse {
    PositionMultiEndResponse::default()
}

pub fn request_positions() -> PositionsRequestBuilder {
    PositionsRequestBuilder
}

pub fn cancel_positions() -> CancelPositionsRequestBuilder {
    CancelPositionsRequestBuilder
}

pub fn request_positions_multi() -> PositionsMultiRequestBuilder {
    PositionsMultiRequestBuilder::default()
}

pub fn cancel_positions_multi() -> CancelPositionsMultiRequestBuilder {
    CancelPositionsMultiRequestBuilder::default()
}

#[cfg(test)]
#[path = "positions_tests.rs"]
mod tests;