forked from sparkstartconsulting/IBKR-API-Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.rs
4511 lines (3853 loc) · 175 KB
/
client.rs
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! EClient and supporting structs. Responsible for connecting to Trader Workstation or IB Gatway and sending requests
use std::io::Write;
use std::marker::Sync;
use std::net::Shutdown;
use std::net::TcpStream;
use std::ops::Deref;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::channel;
use std::sync::{Arc, Mutex};
use std::{fmt::Debug, thread};
use from_ascii::FromAscii;
use log::*;
use num_derive::FromPrimitive;
use super::streamer::{Streamer, TcpStreamer};
use crate::core::common::*;
use crate::core::contract::Contract;
use crate::core::decoder::Decoder;
use crate::core::errors::{IBKRApiLibError, TwsApiReportableError, TwsError};
use crate::core::execution::ExecutionFilter;
use crate::core::messages::make_field;
use crate::core::messages::{make_field_handle_empty, read_msg};
use crate::core::messages::{make_message, read_fields, OutgoingMessageIds};
use crate::core::order::Order;
use crate::core::order_condition::Condition;
use crate::core::reader::Reader;
use crate::core::scanner::ScannerSubscription;
use crate::core::server_versions::*;
use crate::core::wrapper::Wrapper;
pub(crate) static POISONED_MUTEX: &str = "Mutex was poisoned";
//==================================================================================================
/// Connection status
#[repr(i32)]
#[derive(FromPrimitive, Copy, Clone, Debug)]
pub enum ConnStatus {
DISCONNECTED,
CONNECTING,
CONNECTED,
REDIRECT,
}
//==================================================================================================
/// Struct for sending requests
//#[derive(Debug)]
pub struct EClient<T>
where
T: Wrapper,
{
wrapper: Arc<Mutex<T>>,
pub(crate) stream: Option<Box<dyn Streamer>>,
host: String,
port: u32,
extra_auth: bool,
client_id: i32,
pub(crate) server_version: i32,
conn_time: String,
pub conn_state: Arc<Mutex<ConnStatus>>,
opt_capab: String,
disconnect_requested: Arc<AtomicBool>,
}
impl<T> EClient<T>
where
T: Wrapper + Send + Sync + 'static,
{
pub fn new(wrapper: Arc<Mutex<T>>) -> Self {
EClient {
wrapper: wrapper,
stream: None,
host: "".to_string(),
port: 0,
extra_auth: false,
client_id: 0,
server_version: 0,
conn_time: "".to_string(),
conn_state: Arc::new(Mutex::new(ConnStatus::DISCONNECTED)),
opt_capab: "".to_string(),
disconnect_requested: Arc::new(AtomicBool::new(false)),
}
}
fn send_request(&mut self, request: &str) -> Result<(), IBKRApiLibError> {
let bytes = make_message(request)?;
self.send_bytes(bytes.as_slice())?;
Ok(())
}
fn send_bytes(&mut self, bytes: &[u8]) -> Result<usize, IBKRApiLibError> {
let return_val = self.stream.as_mut().unwrap().write(bytes)?;
Ok(return_val)
}
pub(crate) fn set_streamer(&mut self, streamer: Option<Box<dyn Streamer>>) {
self.stream = streamer;
}
//----------------------------------------------------------------------------------------------
/// Establishes a connection to TWS or IB Gateway
pub fn connect(
&mut self,
host: &str,
port: u32,
client_id: i32,
) -> Result<(), IBKRApiLibError> {
if self.is_connected() {
info!("Already connected...");
return Err(IBKRApiLibError::ApiError(TwsApiReportableError::new(
-1,
TwsError::AlreadyConnected.code().to_string(),
TwsError::AlreadyConnected.message().to_string(),
)));
}
self.host = host.to_string();
self.port = port;
self.client_id = client_id;
info!("Connecting");
self.disconnect_requested.store(false, Ordering::Release);
*self.conn_state.lock().expect(POISONED_MUTEX) = ConnStatus::CONNECTING;
let tcp_stream = TcpStream::connect(format!("{}:{}", self.host, port))?;
let streamer = TcpStreamer::new(tcp_stream);
self.set_streamer(Option::from(Box::new(streamer.clone()) as Box<dyn Streamer>));
let (tx, rx) = channel::<String>();
let mut reader = Reader::new(
Box::new(streamer.clone()),
tx.clone(),
self.disconnect_requested.clone(),
);
let mut fields: Vec<String> = Vec::new();
let v_100_prefix = "API\0";
let v_100_version = format!("v{}..{}", MIN_CLIENT_VER, MAX_CLIENT_VER);
let msg = make_message(v_100_version.as_str())?;
let mut bytearray: Vec<u8> = Vec::new();
bytearray.extend_from_slice(v_100_prefix.as_bytes());
bytearray.extend_from_slice(msg.as_slice());
self.send_bytes(bytearray.as_slice())?;
let mut decoder = Decoder::new(
self.wrapper.clone(),
rx,
self.server_version,
self.conn_state.clone(),
);
//An Interactive Broker's developer's note: "sometimes I get news before the server version, thus the loop"
while fields.len() != 2 {
if fields.len() > 0 {
decoder.interpret(fields.as_slice())?;
}
let buf = reader.recv_packet()?;
if buf.len() > 0 {
let (_size, msg, _remaining_messages) = read_msg(buf.as_slice())?;
fields.clear();
fields.extend_from_slice(read_fields(msg.as_ref()).as_slice());
} else {
fields.clear();
}
}
self.server_version = i32::from_ascii(fields.get(0).unwrap().as_bytes()).unwrap();
info!("Server version: {}", self.server_version);
self.conn_time = fields.get(1).unwrap().to_string();
decoder.server_version = self.server_version;
thread::spawn(move || {
reader.run();
});
thread::spawn(move || {
if decoder.run().is_err() {
panic!("decoder.run() failed!!");
}
});
*self.conn_state.lock().expect(POISONED_MUTEX) = ConnStatus::CONNECTED;
info!("Connected");
self.start_api()?;
Ok(())
}
//----------------------------------------------------------------------------------------------
/// Checks connection status
pub fn is_connected(&self) -> bool {
let connected = match *self.conn_state.lock().unwrap().deref() {
ConnStatus::DISCONNECTED => false,
ConnStatus::CONNECTED => true,
ConnStatus::CONNECTING => false,
ConnStatus::REDIRECT => false,
};
//debug!("finished checking connected...");
connected
}
//----------------------------------------------------------------------------------------------
/// Get the server version (important for checking feature flags for different versions)
pub fn server_version(&self) -> i32 {
self.server_version
}
//----------------------------------------------------------------------------------------------
/// Sets server logging level
pub fn set_server_log_level(&mut self, log_evel: i32) -> Result<(), IBKRApiLibError> {
//The pub default detail level is ERROR. For more details, see API
// Logging.
//TODO Make log_level an enum
debug!("set_server_log_level -- log_evel: {}", log_evel);
self.check_connected(NO_VALID_ID)?;
let version = 1;
let _log_level = log_evel;
let mut msg = "".to_string();
let message_id = OutgoingMessageIds::SetServerLoglevel as i32;
let _x = message_id.to_be_bytes();
msg.push_str(&make_field(&message_id)?);
msg.push_str(&make_field(&version)?);
msg.push_str(&make_field(&_log_level)?);
self.send_request(msg.as_str())?;
Ok(())
}
//----------------------------------------------------------------------------------------------
/// Gets the connection time
pub fn tws_connection_time(&mut self) -> String {
//"""Returns the time the API client made a connection to TWS."""
self.conn_time.clone()
}
//----------------------------------------------------------------------------------------------
/// Request the current time according to TWS or IB Gateway
pub fn req_current_time(&mut self) -> Result<(), IBKRApiLibError> {
let version = 2;
let message_id: i32 = OutgoingMessageIds::ReqCurrentTime as i32;
let mut msg = "".to_string();
msg.push_str(&make_field(&message_id)?);
msg.push_str(&make_field(&version)?);
debug!("Requesting current time: {}", msg.as_str());
self.send_request(msg.as_str())
}
//----------------------------------------------------------------------------------------------
/// Disconnect from TWS
pub fn disconnect(&mut self) -> Result<(), IBKRApiLibError> {
if !self.is_connected() {
info!("Already disconnected...");
return Ok(());
}
info!("Disconnect requested. Shutting down stream...");
self.disconnect_requested.store(true, Ordering::Release);
self.stream.as_mut().unwrap().shutdown(Shutdown::Both)?;
*self.conn_state.lock().expect(POISONED_MUTEX) = ConnStatus::DISCONNECTED;
Ok(())
}
//----------------------------------------------------------------------------------------------
/// Initiates the message exchange between the client application and the TWS/IB Gateway
fn start_api(&mut self) -> Result<(), IBKRApiLibError> {
self.check_connected(NO_VALID_ID)?;
let version = 2;
let mut opt_capab = "".to_string();
if self.server_version >= MIN_SERVER_VER_OPTIONAL_CAPABILITIES as i32 {
opt_capab = make_field(&self.opt_capab)?;
}
let msg = format!(
"{}{}{}{}",
make_field(&mut (Some(OutgoingMessageIds::StartApi).unwrap() as i32))?,
make_field(&mut version.to_string())?,
make_field(&mut self.client_id.to_string())?,
opt_capab
);
self.send_request(msg.as_str())?;
Ok(())
}
//##############################################################################################
//################################### Market Data
//##############################################################################################
/// Call this function to request market data. The market data
/// will be returned by the tick_price and tick_size wrapper events.
///
/// # Arguments
/// * req_id - The request id. Must be a unique value. When the
/// market data returns, it will be identified by this tag. This is
/// also used when canceling the market data.
/// * contract - This structure contains a description of the
/// Contract for which market data is being requested.
/// * generic_tick_list - A commma delimited list of generic tick types.
/// Tick types can be found in the Generic Tick Types page.
/// Prefixing w/ 'mdoff' indicates that top mkt data shouldn't tick.
/// You can specify the news source by postfixing w/ ':<source>.
/// Example: "mdoff, 292: FLY + BRF"
/// * snapshot - Check to return a single snapshot of Market data and
/// have the market data subscription cancel. Do not enter any
/// generic_tick_list values if you use snapshots.
/// * regulatory_snapshot - With the US Value Snapshot Bundle for stocks,
/// regulatory snapshots are available for 0.01 USD each.
/// * mkt_data_options - For internal use only. Use default value XYZ.
pub fn req_mkt_data(
&mut self,
req_id: i32,
contract: &Contract,
generic_tick_list: &str,
snapshot: bool,
regulatory_snapshot: bool,
mkt_data_options: Vec<TagValue>,
) -> Result<(), IBKRApiLibError> {
self.check_connected(req_id)?;
if self.server_version() < MIN_SERVER_VER_DELTA_NEUTRAL {
if let Some(_value) = &contract.delta_neutral_contract {
let err = IBKRApiLibError::ApiError(TwsApiReportableError::new(
req_id,
TwsError::UpdateTws.code().to_string(),
format!(
"{}{}",
TwsError::UpdateTws.message(),
" It does not support delta-neutral orders."
),
));
return Err(err);
}
}
if self.server_version() < MIN_SERVER_VER_REQ_MKT_DATA_CONID && contract.con_id > 0 {
let err = IBKRApiLibError::ApiError(TwsApiReportableError::new(
req_id,
TwsError::NotConnected.code().to_string(),
TwsError::NotConnected.message().to_string(),
));
return Err(err);
}
if self.server_version() < MIN_SERVER_VER_TRADING_CLASS && "" != contract.trading_class {
let err = IBKRApiLibError::ApiError(TwsApiReportableError::new(
req_id,
TwsError::UpdateTws.code().to_string(),
format!(
"{}{}",
TwsError::UpdateTws.message(),
" It does not support trading_class parameter in req_mkt_data."
),
));
return Err(err);
}
let version = 11;
let message_id: i32 = OutgoingMessageIds::ReqMktData as i32;
let mut msg = "".to_string();
// send req mkt data msg
msg.push_str(&make_field(&message_id)?);
msg.push_str(&make_field(&version)?);
msg.push_str(&make_field(&req_id)?);
// send contract fields
if self.server_version() >= MIN_SERVER_VER_REQ_MKT_DATA_CONID {
msg.push_str(&make_field(&contract.con_id)?);
msg.push_str(&make_field(&contract.symbol)?);
msg.push_str(&make_field(&contract.sec_type)?);
msg.push_str(&make_field(&contract.last_trade_date_or_contract_month)?);
msg.push_str(&make_field(&contract.strike)?);
msg.push_str(&make_field(&contract.right)?);
msg.push_str(&make_field(&contract.multiplier)?); // srv v15 and above
msg.push_str(&make_field(&contract.exchange)?);
msg.push_str(&make_field(&contract.primary_exchange)?); // srv v14 and above
msg.push_str(&make_field(&contract.currency)?);
msg.push_str(&make_field(&contract.local_symbol)?); // srv v2 and above
}
if self.server_version() >= MIN_SERVER_VER_TRADING_CLASS {
msg.push_str(&make_field(&contract.trading_class)?);
}
// Send combo legs for BAG requests(srv v8 and above)
if contract.sec_type == "BAG" {
let combo_legs_count = contract.combo_legs.len();
msg.push_str(&make_field(&combo_legs_count)?);
for combo_leg in &contract.combo_legs {
msg.push_str(&make_field(&combo_leg.con_id)?);
msg.push_str(&make_field(&combo_leg.ratio)?);
msg.push_str(&make_field(&combo_leg.action)?);
msg.push_str(&make_field(&combo_leg.exchange)?);
}
}
if self.server_version() >= MIN_SERVER_VER_DELTA_NEUTRAL {
if contract.delta_neutral_contract.is_some() {
msg.push_str(&make_field(&true)?);
msg.push_str(&make_field(
&contract.delta_neutral_contract.as_ref().unwrap().con_id,
)?);
msg.push_str(&make_field(
&contract.delta_neutral_contract.as_ref().unwrap().delta,
)?);
msg.push_str(&make_field(
&contract.delta_neutral_contract.as_ref().unwrap().price,
)?);
} else {
msg.push_str(&make_field(&false)?);
}
msg.push_str(&make_field(&String::from(generic_tick_list))?); // srv v31 and above
msg.push_str(&make_field(&snapshot)?); // srv v35 and above
}
if self.server_version() >= MIN_SERVER_VER_REQ_SMART_COMPONENTS {
msg.push_str(&make_field(®ulatory_snapshot)?);
}
// send mktDataOptions parameter
if self.server_version() >= MIN_SERVER_VER_LINKING {
// current doc says this part is for "internal use only" -> won't support it
if mkt_data_options.len() > 0 {
let err = IBKRApiLibError::ApiError(TwsApiReportableError::new(
req_id,
TwsError::UpdateTws.code().to_string(),
format!(
"{}{}",
TwsError::UpdateTws.message(),
" Internal use only. mkt_data_options not supported."
),
));
return Err(err);
}
let mkt_data_options_str = "";
msg.push_str(&make_field(&mkt_data_options_str)?);
}
self.send_request(msg.as_str())?;
Ok(())
}
//----------------------------------------------------------------------------------------------
/// After calling this function, market data for the specified id will stop flowing.
///
/// # Arguments
/// * req_id - The ID that was specified in the call to req_mkt_data()
pub fn cancel_mkt_data(&mut self, req_id: i32) -> Result<(), IBKRApiLibError> {
self.check_connected(req_id)?;
let version = 2;
let message_id: i32 = OutgoingMessageIds::CancelMktData as i32;
let mut msg = "".to_string();
msg.push_str(&make_field(&message_id)?);
msg.push_str(&make_field(&version)?);
msg.push_str(&make_field(&req_id)?);
self.send_request(msg.as_str())?;
Ok(())
}
//----------------------------------------------------------------------------------------------
/// The API can receive frozen market data from Trader
/// Workstation. Frozen market data is the last data recorded in our system.
/// During normal trading hours, the API receives real-time market data. If
/// you use this function, you are telling TWS to automatically switch to
/// frozen market data after the close. Then, before the opening of the next
/// trading day, market data will automatically switch back to real-time
/// market data.
///
/// # Arguments
/// * market_data_type
/// * 1 for real-time streaming market data
/// * 2 for frozen market data
pub fn req_market_data_type(&mut self, market_data_type: i32) -> Result<(), IBKRApiLibError> {
self.check_connected(NO_VALID_ID)?;
if self.server_version() < MIN_SERVER_VER_REQ_MARKET_DATA_TYPE {
let err = IBKRApiLibError::ApiError(TwsApiReportableError::new(
NO_VALID_ID,
TwsError::UpdateTws.code().to_string(),
format!(
"{}{}",
TwsError::UpdateTws.message(),
" It does not support market data type requests."
),
));
return Err(err);
}
let mut msg = "".to_string();
let version = 1;
let message_id = OutgoingMessageIds::ReqMarketDataType as i32;
msg.push_str(&make_field(&message_id)?);
msg.push_str(&make_field(&version)?);
msg.push_str(&make_field(&market_data_type)?);
self.send_request(msg.as_str())?;
Ok(())
}
//----------------------------------------------------------------------------------------------
/// Returns the mapping of single letter codes to exchange names given the mapping identifier.
/// # Arguments
/// * req_id - The request id. Must be a unique value. When the
/// market data returns, it will be identified by this tag. This is
/// also used when canceling the market data.
/// * bbo_exchange - mapping identifier received from Wrapper::tick_req_params
pub fn req_smart_components(
&mut self,
req_id: i32,
bbo_exchange: &str,
) -> Result<(), IBKRApiLibError> {
self.check_connected(req_id)?;
if self.server_version() < MIN_SERVER_VER_REQ_SMART_COMPONENTS {
let err = IBKRApiLibError::ApiError(TwsApiReportableError::new(
req_id,
TwsError::UpdateTws.code().to_string(),
format!(
"{}{}",
TwsError::UpdateTws.message(),
" It does not support smart components request."
),
));
return Err(err);
}
let mut msg = "".to_string();
let message_id = OutgoingMessageIds::ReqSmartComponents as i32;
msg.push_str(&make_field(&message_id)?);
msg.push_str(&make_field(&req_id)?);
msg.push_str(&make_field(&String::from(bbo_exchange))?);
self.send_request(msg.as_str())?;
Ok(())
}
//----------------------------------------------------------------------------------------------
/// Requests details about a given market rule
/// The market rule for an instrument on a particular exchange provides details about how the
/// minimum price increment changes with price
///
/// A list of market rule ids can be obtained by invoking req_contract_details on a particular contract.
/// The returned market rule ID list will provide the market rule ID for the instrument in the correspond valid exchange list in contractDetails.
/// # Arguments
/// * market_rule_id - the id of market rule
pub fn req_market_rule(&mut self, market_rule_id: i32) -> Result<(), IBKRApiLibError> {
self.check_connected(NO_VALID_ID)?;
if self.server_version() < MIN_SERVER_VER_MARKET_RULES {
let err = IBKRApiLibError::ApiError(TwsApiReportableError::new(
NO_VALID_ID,
TwsError::UpdateTws.code().to_string(),
format!(
"{}{}",
TwsError::UpdateTws.message(),
" It does not support market rule requests."
),
));
return Err(err);
}
let mut msg = "".to_string();
let message_id = OutgoingMessageIds::ReqMarketRule as i32;
msg.push_str(&make_field(&message_id)?);
msg.push_str(&make_field(&market_rule_id)?);
self.send_request(msg.as_str())?;
Ok(())
}
//----------------------------------------------------------------------------------------------
/// Request tick by tick data
///
/// # Arguments
/// * req_id - unique identifier of the request.
/// * contract - the contract for which tick-by-tick data is requested.
/// * tick_type - TickByTickType data type: "Last", "AllLast", "BidAsk" or "MidPoint".
/// * number_of_ticks - number of ticks.
/// * ignore_size - ignore size flag.
pub fn req_tick_by_tick_data(
&mut self,
req_id: i32,
contract: &Contract,
tick_type: TickByTickType,
number_of_ticks: i32,
ignore_size: bool,
) -> Result<(), IBKRApiLibError> {
self.check_connected(NO_VALID_ID)?;
if self.server_version() < MIN_SERVER_VER_TICK_BY_TICK {
let err = IBKRApiLibError::ApiError(TwsApiReportableError::new(
req_id,
TwsError::UpdateTws.code().to_string(),
format!(
"{}{}",
TwsError::UpdateTws.message(),
" It does not support tick-by-tick data requests."
),
));
return Err(err);
}
if self.server_version() < MIN_SERVER_VER_TICK_BY_TICK_IGNORE_SIZE {
let err = IBKRApiLibError::ApiError(TwsApiReportableError::new(
req_id,
TwsError::UpdateTws.code().to_string(),
format!(
"{}{}",
TwsError::UpdateTws.message(),
" It does not support ignore_size and number_of_ticks parameters in tick-by-tick data requests."
),
));
return Err(err);
}
let mut msg = "".to_string();
let message_id = OutgoingMessageIds::ReqTickByTickData as i32;
msg.push_str(&make_field(&message_id)?);
// msg.push_str(&make_field(&OUT.REQ_TICK_BY_TICK_DATA)\
msg.push_str(&make_field(&req_id)?);
msg.push_str(&make_field(&contract.con_id)?);
msg.push_str(&make_field(&contract.symbol)?);
msg.push_str(&make_field(&contract.sec_type)?);
msg.push_str(&make_field(&contract.last_trade_date_or_contract_month)?);
msg.push_str(&make_field(&contract.strike)?);
msg.push_str(&make_field(&contract.right)?);
msg.push_str(&make_field(&contract.multiplier)?);
msg.push_str(&make_field(&contract.exchange)?);
msg.push_str(&make_field(&contract.primary_exchange)?);
msg.push_str(&make_field(&contract.currency)?);
msg.push_str(&make_field(&contract.local_symbol)?);
msg.push_str(&make_field(&contract.trading_class)?);
msg.push_str(&make_field(&(tick_type.to_string()))?);
if self.server_version() >= MIN_SERVER_VER_TICK_BY_TICK_IGNORE_SIZE {
msg.push_str(&make_field(&number_of_ticks)?);
msg.push_str(&make_field(&ignore_size)?);
}
self.send_request(msg.as_str())?;
Ok(())
}
//----------------------------------------------------------------------------------------------
/// Cancel tick by tick data
///
/// # Arguments
/// * req_id - The identifier of the original request.
pub fn cancel_tick_by_tick_data(&mut self, req_id: i32) -> Result<(), IBKRApiLibError> {
self.check_connected(req_id)?;
if self.server_version() < MIN_SERVER_VER_TICK_BY_TICK {
let err = IBKRApiLibError::ApiError(TwsApiReportableError::new(
req_id,
TwsError::UpdateTws.code().to_string(),
format!(
"{}{}",
TwsError::UpdateTws.message(),
" It does not support tick-by-tick data requests."
),
));
return Err(err);
}
let mut msg = "".to_string();
let message_id = OutgoingMessageIds::CancelTickByTickData as i32;
msg.push_str(&make_field(&message_id)?);
msg.push_str(&make_field(&req_id)?);
self.send_request(msg.as_str())?;
Ok(())
}
//##########################################################################
//################## Options
//##########################################################################
/// Call this function to calculate volatility for a supplied
/// option price and underlying price. Result will be delivered
/// via Wrapper::tick_option_computation
///
/// # Arguments
/// * req_id - The request id.
/// * contract - Describes the contract.
/// * option_price - The price of the option.
/// * under_price - Price of the underlying.
/// * impl_vol_options - Implied volatility options.
pub fn calculate_implied_volatility(
&mut self,
req_id: i32,
contract: &Contract,
option_price: f64,
under_price: f64,
impl_vol_options: Vec<TagValue>,
) -> Result<(), IBKRApiLibError> {
self.check_connected(req_id)?;
if self.server_version() < MIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT {
let err = IBKRApiLibError::ApiError(TwsApiReportableError::new(
req_id,
TwsError::UpdateTws.code().to_string(),
format!(
"{}{}",
TwsError::UpdateTws.message(),
" It does not support calculate_implied_volatility req."
),
));
return Err(err);
}
if self.server_version() < MIN_SERVER_VER_TRADING_CLASS && "" != contract.trading_class {
let err = IBKRApiLibError::ApiError(TwsApiReportableError::new(
req_id,
TwsError::UpdateTws.code().to_string(),
format!(
"{}{}",
TwsError::UpdateTws.message(),
" It does not support trading_class parameter in calculate_implied_volatility."
),
));
return Err(err);
}
let version = 3;
let mut msg = "".to_string();
let message_id = OutgoingMessageIds::ReqCalcImpliedVolat as i32;
msg.push_str(&make_field(&message_id)?);
msg.push_str(&make_field(&version)?);
msg.push_str(&make_field(&req_id)?);
// send contract fields
msg.push_str(&make_field(&contract.con_id)?);
msg.push_str(&make_field(&contract.symbol)?);
msg.push_str(&make_field(&contract.sec_type)?);
msg.push_str(&make_field(&contract.last_trade_date_or_contract_month)?);
msg.push_str(&make_field(&contract.strike)?);
msg.push_str(&make_field(&contract.right)?);
msg.push_str(&make_field(&contract.multiplier)?);
msg.push_str(&make_field(&contract.exchange)?);
msg.push_str(&make_field(&contract.primary_exchange)?);
msg.push_str(&make_field(&contract.currency)?);
msg.push_str(&make_field(&contract.local_symbol)?);
if self.server_version() >= MIN_SERVER_VER_TRADING_CLASS {
msg.push_str(&make_field(&contract.trading_class)?);
}
msg.push_str(&make_field(&option_price)?);
msg.push_str(&make_field(&under_price)?);
if self.server_version() >= MIN_SERVER_VER_LINKING {
let mut impl_vol_opt_str = "".to_string();
let tag_values_count = impl_vol_options.len();
if tag_values_count > 0 {
impl_vol_opt_str = impl_vol_options
.iter()
.map(|x| format!("{}={};", x.tag, x.value))
.collect::<String>();
}
msg.push_str(&make_field(&tag_values_count)?);
msg.push_str(&make_field(&impl_vol_opt_str)?);
}
error!("sending calculate_implied_volatility");
error!("{}", msg);
self.send_request(msg.as_str())?;
Ok(())
}
//----------------------------------------------------------------------------------------------
/// Call this function to calculate option price and greek values for a supplied volatility and underlying price.
///
/// # Arguments
/// * req_id - The request id.
/// * contract - Describes the contract.
/// * volatility - The volatility.
/// * under_price - Price of the underlying.
pub fn calculate_option_price(
&mut self,
req_id: i32,
contract: &Contract,
volatility: f64,
under_price: f64,
opt_prc_options: Vec<TagValue>,
) -> Result<(), IBKRApiLibError> {
self.check_connected(req_id)?;
if self.server_version() < MIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT {
let err = IBKRApiLibError::ApiError(TwsApiReportableError::new(
req_id,
TwsError::UpdateTws.code().to_string(),
format!(
"{}{}",
TwsError::UpdateTws.message(),
" It does not support calculateImpliedVolatility req."
),
));
return Err(err);
}
if self.server_version() < MIN_SERVER_VER_TRADING_CLASS {
if "" != contract.trading_class {
let err = IBKRApiLibError::ApiError(TwsApiReportableError::new(
req_id,
TwsError::UpdateTws.code().to_string(),
format!(
"{}{}",
TwsError::UpdateTws.message(),
" It does not support trading_class parameter in calculateImpliedVolatility."
),
));
return Err(err);
}
}
let version = 3;
// send req mkt data msg
let mut msg = "".to_string();
let message_id = OutgoingMessageIds::ReqCalcOptionPrice as i32;
msg.push_str(&make_field(&message_id)?);
msg.push_str(&make_field(&version)?);
msg.push_str(&make_field(&req_id)?);
// send contract fields
msg.push_str(&make_field(&contract.con_id)?);
msg.push_str(&make_field(&contract.symbol)?);
msg.push_str(&make_field(&contract.sec_type)?);
msg.push_str(&make_field(&contract.last_trade_date_or_contract_month)?);
msg.push_str(&make_field(&contract.strike)?);
msg.push_str(&make_field(&contract.right)?);
msg.push_str(&make_field(&contract.multiplier)?);
msg.push_str(&make_field(&contract.exchange)?);
msg.push_str(&make_field(&contract.primary_exchange)?);
msg.push_str(&make_field(&contract.currency)?);
msg.push_str(&make_field(&contract.local_symbol)?);
if self.server_version() >= MIN_SERVER_VER_TRADING_CLASS {
msg.push_str(&make_field(&contract.trading_class)?);
}
msg.push_str(&make_field(&volatility)?);
msg.push_str(&make_field(&under_price)?);
if self.server_version() >= MIN_SERVER_VER_LINKING {
let _opt_prc_opt_str = "".to_string();
let tag_values_count = opt_prc_options.len();
if tag_values_count > 0 {
let opt_prc_opt_str = opt_prc_options
.iter()
.map(|x| format!("{}={};", x.tag, x.value))
.collect::<String>();
msg.push_str(&make_field(&tag_values_count)?);
msg.push_str(&make_field(&opt_prc_opt_str)?);
}
}
self.send_request(msg.as_str())?;
Ok(())
}
//----------------------------------------------------------------------------------------------
/// Call this function to cancel a request to calculate the option
/// price and greek values for a supplied volatility and underlying price.
///
/// # Arguments
/// * req_id - The original request id.
pub fn cancel_calculate_option_price(&mut self, req_id: i32) -> Result<(), IBKRApiLibError> {
self.check_connected(req_id)?;
if self.server_version() < MIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT {
let err = IBKRApiLibError::ApiError(TwsApiReportableError::new(
req_id,
TwsError::UpdateTws.code().to_string(),
format!(
"{}{}",
TwsError::UpdateTws.message(),
" It does not support calculateImpliedVolatility req."
),
));
return Err(err);
}
let version = 1;
let mut msg = "".to_string();
let message_id = OutgoingMessageIds::CancelCalcOptionPrice as i32;
msg.push_str(&make_field(&message_id)?);
msg.push_str(&make_field(&version)?);
msg.push_str(&make_field(&req_id)?);
self.send_request(msg.as_str())?;
Ok(())
}
//----------------------------------------------------------------------------------------------
/// Call this function to cancel a request to calculate the option implied volatility.
///
/// # Arguments
/// * req_id - The original request id.
pub fn cancel_calculate_implied_volatility(
&mut self,
req_id: i32,
) -> Result<(), IBKRApiLibError> {
self.check_connected(req_id)?;
if self.server_version() < MIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT {
let err = IBKRApiLibError::ApiError(TwsApiReportableError::new(
req_id,
TwsError::UpdateTws.code().to_string(),
format!(
"{}{}",
TwsError::UpdateTws.message(),
" It does not support calculateImpliedVolatility req."
),
));
return Err(err);
}
let version = 1;
let mut msg = "".to_string();
let message_id = OutgoingMessageIds::CancelCalcImpliedVolat as i32;
msg.push_str(&make_field(&message_id)?);
msg.push_str(&make_field(&version)?);
msg.push_str(&make_field(&req_id)?);
self.send_request(msg.as_str())?;
Ok(())
}
//----------------------------------------------------------------------------------------------
/// Call this function to excercise options
///
/// # Arguments
/// * req_id - The ticker id. multipleust be a unique value.
/// * contract - This structure contains a description of the contract to be exercised
/// * exercise_action - Specifies whether you want the option to lapse or be exercised. Values are:
/// * 1 = exercise
/// * 2 = lapse.
/// * exercise_quantity - The quantity you want to exercise.
/// * account - destination account
/// * override - Specifies whether your setting will override the system's
/// natural action. For example, if your action is "exercise" and the
/// option is not in-the-money, by natural action the option would not
/// exercise. If you have override set to "yes" the natural action would
/// be overridden and the out-of-the money option would be exercised.
/// Values are:
/// * 0 = no
/// * 1 = yes.
pub fn exercise_options(
&mut self,