-
Notifications
You must be signed in to change notification settings - Fork 165
/
Copy pathIBTWS.cpp
1936 lines (1682 loc) · 76.1 KB
/
IBTWS.cpp
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
/************************************************************************
* Copyright(c) 2009, One Unified. All rights reserved. *
* email: [email protected] *
* *
* This file is provided as is WITHOUT ANY WARRANTY *
* without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* *
* This software may not be used nor distributed without proper license *
* agreement. *
* *
* See the file LICENSE.txt for redistribution information. *
************************************************************************/
#include <memory>
#include <string>
#include <chrono>
#include <iostream>
//#include <sstream>
#include <stdexcept>
#include <boost/log/trivial.hpp>
#include <boost/regex.hpp>
#include <boost/date_time.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/date_time/local_time_adjustor.hpp>
#include <boost/spirit/include/qi.hpp>
#include <OUCommon/TimeSource.h>
#include <OUCommon/KeyWordMatch.h>
#include <TFTrading/KeyTypes.h>
#include <TFTrading/OrderManager.h>
#include "client/OrderState.h"
#include "client/EClientSocket.h"
#include "client/CommissionReport.h"
#include "IBTWS.h"
namespace {
const unsigned int maxRequestsInTransit( 5 );
// TODO: use spirit to parse? will it be faster?
struct DecodeStatusWord {
enum EStatus{ Unknown, PreSubmitted, PendingSubmit, PendingCancel, Submitted, Cancelled, Filled, Inactive };
DecodeStatusWord( void ): kwm( Unknown, 50 ) {
kwm.AddPattern( "Cancelled", Cancelled );
kwm.AddPattern( "Filled", Filled );
kwm.AddPattern( "Inactive", Inactive );
kwm.AddPattern( "PreSubmitted", PreSubmitted );
kwm.AddPattern( "Submitted", Submitted );
kwm.AddPattern( "PendingSubmit", PendingSubmit );
kwm.AddPattern( "PendingCancel", PendingCancel );
}
EStatus Match( const std::string& status ) { return kwm.FindMatch( status ); };
private:
ou::KeyWordMatch<EStatus> kwm;;
};
DecodeStatusWord dsw;
namespace qi = boost::spirit::qi;
using vString_t = std::vector<std::string>;
template<typename Iterator>
struct ParseStrings: qi::grammar<Iterator, vString_t()> {
ParseStrings(): ParseStrings::base_type( start ) {
ruleString %= +( qi::char_ - qi::char_(",") );
start %= ruleString >> ( *(qi::lit(',') >> ruleString ) );
}
qi::rule<Iterator, std::string()> ruleString;
qi::rule<Iterator, vString_t()> start;
};
} // namespace anonymous
namespace ou { // One Unified
namespace tf { // TradeFrame
namespace ib { // Interactive Brokers
TWS::TWS( const std::string &acctCode, const std::string &address, unsigned int port )
: EWrapper()
, ProviderInterface<TWS,Symbol>()
, m_osSignal( 1000 )
, m_sAccountCode( acctCode ), m_sIPAddress( address ), m_nPort( port ), m_curTickerId( 0 )
, m_idClient( 0 )
, m_nxtReqId( 1 )
, m_bEvictorStarted( false )
{
m_sName = "IB";
m_nID = keytypes::EProviderIB;
pSymbol_t p;
m_vTickerToSymbol.push_back( p ); // first ticker is 1, so preload with nothing at position 0
m_bProvidesQuotes = true;
m_bProvidesTrades = true;
m_bProvidesGreeks = true;
m_bProvidesBrokerInterface = true;
}
TWS::~TWS() {
if ( m_thrdRequestEvictor.joinable() ) {
m_thrdRequestEvictor.join();
}
for ( vRequest_t::value_type& vt: m_vRequestRecycling ) {
delete vt;
vt = nullptr;
}
m_vRequestRecycling.clear();
m_vTickerToSymbol.clear();
m_mapContractToSymbol.clear();
Disconnect( true, false, true );
}
void TWS::ContractExpiryField( Contract& contract, boost::uint16_t nYear, boost::uint16_t nMonth ) {
//std::string month( boost::lexical_cast<std::string,boost::uint16_t>( nMonth ) );
contract.lastTradeDateOrContractMonth
= boost::lexical_cast<std::string,boost::uint16_t>( nYear )
//+ ( ( 1 == month.size() ) ? "0" : "" )
//+ month
+= ( ( 9 < nMonth ) ? "" : "0" ) + boost::lexical_cast<std::string>( nMonth );
;
}
void TWS::ContractExpiryField( Contract& contract, boost::uint16_t nYear, boost::uint16_t nMonth, boost::uint16_t nDay ) {
ContractExpiryField( contract, nYear, nMonth );
contract.lastTradeDateOrContractMonth
//+= boost::lexical_cast<std::string,boost::uint16_t>( nDay )
+= ( ( 9 < nDay ) ? "" : "0" ) + boost::lexical_cast<std::string>( nDay );
;
}
void TWS::Connect() {
if ( m_pTWS ) {
BOOST_LOG_TRIVIAL(info) << "IB EClientSocket exists";
}
else {
m_pTWS = std::make_unique<EClientSocket>( this, &m_osSignal );
}
if ( m_pTWS->isConnected() ) {
assert( m_thrdIBMessages.joinable() );
}
else {
OnConnecting( 0 );
if ( m_thrdIBMessages.joinable() ) { // clean out previous stuff
m_thrdIBMessages.join();
}
//m_pTWS->setConnectOptions( "+PACEAPI" ); // https://www.interactivebrokers.com/en/index.php?f=24356 (needs version >=974)
bool bOk = m_pTWS->eConnect( m_sIPAddress.c_str(), m_nPort, m_idClient );
if ( bOk ) {
m_bConnected = true;
{
std::unique_lock lock( m_mutexThreadSync );
m_bThreadSync = false;
m_thrdIBMessages = std::move( std::thread( std::bind( &TWS::processMessages, this ) ) );
m_cvThreadSync.wait(
lock,
[this](){
if ( m_bThreadSync ) {
//std::cout << "thread notified" << std::endl;
m_pTWS->reqCurrentTime();
usleep( 50000 );
m_pTWS->reqNewsBulletins( true );
// m_pTWS->reqOpenOrders();
//ExecutionFilter filter;
//pTWS->reqExecutions( filter );
usleep( 50000 );
m_pTWS->reqAccountUpdates( true, "" );
OnConnected( 0 );
}
return m_bThreadSync;
} );
}
}
else {
// need to integrate common stuff from Disconnect, most everything but the thread bit
std::cout << "TWS::Connect fail" << std::endl;
Disconnect( false, false, true );
}
}
}
// this is executed in non-main thread, and the events below will be called from the processing here
// so... be aware of cross thread issues
void TWS::processMessages() {
std::unique_ptr<EReader> pReader;
pReader = std::make_unique<EReader>( m_pTWS.get(), &m_osSignal );
pReader->start();
{
std::scoped_lock lock( m_mutexThreadSync );
m_bThreadSync = true;
}
//std::cout << "thread notifying" << std::endl;
m_cvThreadSync.notify_one();
try { // should this be within the while?
while ( m_bConnected ) {
errno = 0;
m_osSignal.waitForSignal();
pReader->processMsgs();
switch ( errno ) {
case 0: // ignore, heartbeat?
break;
case 2: // ignore, per-message signal
//BOOST_LOG_TRIVIAL(debug) << "IB processMessages 2";
errno = 0;
break;
default:
BOOST_LOG_TRIVIAL(error)
<< "IB status id=" << errno << " [" << strerror(errno) << "]"
<< ",connected=" << m_pTWS->isConnected()
;
errno = 0;
}
}
}
catch(...) {
BOOST_LOG_TRIVIAL(error) << "IB socket failure, need to disconnect and restart ...";
// probably need to run Disconnect or DisconnectCommon
m_bConnected = false; // placeholder for debug
}
//BOOST_LOG_TRIVIAL(debug) << "IB pReader.reset()";
pReader.reset(); // NOTE: this deadlocks with connectionClosed()
//BOOST_LOG_TRIVIAL(debug) << "IB processMessages exit";
}
void TWS::Disconnect() {
Disconnect( false, false, true );
}
void TWS::Disconnect( bool bFinal, bool bIBInitiated, bool bUserInitiated ) {
assert( bIBInitiated != bUserInitiated );
// TODO: check to see if there are any watches happening, and get them disconnected
if ( m_pTWS ) { // called by IB, so deadlock when exiting
//BOOST_LOG_TRIVIAL(debug) << "IB Disconnecting";
OnDisconnecting( 0 );
m_bConnected = false;
if ( bUserInitiated ) {
//BOOST_LOG_TRIVIAL(debug) << "IB Disconnect SignalEnd edisconnect pre";
m_pTWS->eDisconnect( false );
//BOOST_LOG_TRIVIAL(debug) << "IB Disconnect SignalEnd edisconnect post";
}
if ( bUserInitiated ) { // can't join in connectionClosed thread, will deadlock pReader.reset()
//BOOST_LOG_TRIVIAL(debug) << "IB Disconnect SignalEnd threadjoin pre";
if ( m_thrdIBMessages.joinable() ) {
m_thrdIBMessages.join(); // wait for message processing to exit
}
//BOOST_LOG_TRIVIAL(debug) << "IB Disconnect delete pre";
m_pTWS.reset(); // NOTE: since it still exists, re-use it when possible (exists with bIBInitiated)
//BOOST_LOG_TRIVIAL(debug) << "IB Disconnect delete post";
}
//BOOST_LOG_TRIVIAL(debug) << "IB Disconnect signal pre";
OnDisconnected( 0 );
}
else {
BOOST_LOG_TRIVIAL(warning) << "IB already disconnected";
}
}
void TWS::connectionClosed() {
BOOST_LOG_TRIVIAL(info) << "IB Initiated Connection Close";
Disconnect( false, true, false );
}
void TWS::RequestContractDetails(
const std::string& sSymbolBaseName
, pInstrument_t& pInstrument
, fOnContractDetail_t&& fProcess, fOnContractDetailDone_t&& fDone
) {
assert( 0 == pInstrument->GetContract() ); // handle this better, ie, return gently, or create exception
Contract contract;
contract.symbol = sSymbolBaseName; // separately, as it may differ from IQFeed or others
contract.currency = pInstrument->GetCurrencyName(); // check if these match
if ( pInstrument->GetExchangeName().empty() ) {
contract.exchange = "SMART";
}
else {
contract.exchange = pInstrument->GetExchangeName();
}
//contract.exchange = pInstrument->GetExchangeName(); // need lookup table from IQFeed exchanges
//std::cout << "Exchange supplied to TWS: " << pInstrument->GetExchangeName() << std::endl;
contract.secType = szSecurityType[ pInstrument->GetInstrumentType() ];
switch ( pInstrument->GetInstrumentType() ) {
case InstrumentType::Stock:
contract.exchange = "SMART"; // override iqfeed supplied value
break;
case InstrumentType::Option:
ContractExpiryField( contract, pInstrument->GetExpiryYear(), pInstrument->GetExpiryMonth(), pInstrument->GetExpiryDay() );
contract.strike = pInstrument->GetStrike();
contract.right = pInstrument->GetOptionSide();
contract.exchange = "SMART"; // override iqfeed supplied value
//contract.multiplier = boost::lexical_cast<std::string>( pInstrument->GetMultiplier() ); // needed for small options
break;
case InstrumentType::Future:
ContractExpiryField( contract, pInstrument->GetExpiryYear(), pInstrument->GetExpiryMonth(), pInstrument->GetExpiryDay() );
contract.tradingClass = sSymbolBaseName;
if ( "COMEX" == pInstrument->GetExchangeName() ) contract.exchange = "NYMEX"; // GC options, IQFeed supplied
if ( "COMEX_GBX" == pInstrument->GetExchangeName() ) contract.exchange = "NYMEX"; // GC options, IQFeed supplied
//if ( "CME" == pInstrument->GetExchangeName() ) contract.exchange = "GLOBEX"; // ES options, IQFeed supplied
break;
case InstrumentType::FuturesOption:
ContractExpiryField( contract, pInstrument->GetExpiryYear(), pInstrument->GetExpiryMonth(), pInstrument->GetExpiryDay() );
contract.tradingClass = sSymbolBaseName;
contract.strike = pInstrument->GetStrike();
contract.right = pInstrument->GetOptionSide();
if ( "COMEX" == pInstrument->GetExchangeName() ) contract.exchange = "NYMEX"; // GC, IQFeed supplied
if ( "COMEX_GBX" == pInstrument->GetExchangeName() ) contract.exchange = "NYMEX"; // GC, IQFeed supplied
//if ( "CME" == pInstrument->GetExchangeName() ) contract.exchange = "GLOBEX"; // ES?, IQFeed supplied
break;
case InstrumentType::Currency:
//contract.exchange = "IDEAL"; // can be IDEAL (paper) or IDEALPRO (real)
contract.secType = "CASH";
contract.symbol = ou::tf::Currency::Name[ pInstrument->GetCurrencyBase() ];
contract.currency = ou::tf::Currency::Name[ pInstrument->GetCurrencyCounter() ];
break;
default:
assert( false );
}
RequestContractDetails( contract, std::move( fProcess ), std::move( fDone ), pInstrument );
}
void TWS::RequestContractDetails( const Contract& contract, fOnContractDetail_t&& fProcess, fOnContractDetailDone_t&& fDone ) {
// results supplied at contractDetails()
pInstrument_t pInstrument; // just allocate, and pass as empty
RequestContractDetails( contract, std::move( fProcess ), std::move( fDone ), pInstrument );
}
void TWS::RequestContractDetails(
const Contract& contract, fOnContractDetail_t&& fProcess, fOnContractDetailDone_t&& fDone, pInstrument_t& pInstrument
) {
// pInstrument can be empty, or can have an instrument
// results supplied at contractDetails()
bool bStartEvictor( false );
Request* pRequest = nullptr;
mapActiveRequests_t::size_type size {};
//std::cout << "Requesting " << pInstrument->GetInstrumentName() << std::endl;
{
std::scoped_lock<std::mutex> lock( m_mutexActiveRequests );
if ( 0 == m_vRequestRecycling.size() ) {
pRequest = new Request();
}
else {
pRequest = m_vRequestRecycling.back();
m_vRequestRecycling.pop_back();
}
pRequest->id = m_nxtReqId++;
pRequest->bIntransit = false;
pRequest->fOnContractDetail = std::move( fProcess );
pRequest->fOnContractDetailDone = std::move( fDone );
pRequest->pInstrument = pInstrument;
pRequest->contract = contract;
pRequest->dtSubmitted = std::chrono::system_clock::now();
m_mapActiveRequests[ pRequest->id ] = pRequest;
if ( !m_bEvictorStarted ) {
bStartEvictor = true;
}
} // end scoped_lock
if ( bStartEvictor ) {
//std::cout << "Evictor starting" << std::endl;
if ( m_thrdRequestEvictor.joinable() ) { // wait for previous thread to complete
m_thrdRequestEvictor.join();
}
m_bEvictorStarted = true;
// TODO: move this into UpdateActiveRequests()?
m_thrdRequestEvictor = std::move( std::thread(
[this](){
bool bContinue( true );
fOnContractDetailDone_t fOnContractDetailDone( nullptr );
do {
using namespace std::chrono_literals;
vRequest_t vRequestsForEvictionNotify;
std::this_thread::sleep_for( 50ms );
{
std::scoped_lock<std::mutex> lock( m_mutexActiveRequests );
for ( mapActiveRequests_t::value_type& vt: m_mapActiveRequests ) {
Request* pRequest = vt.second;
assert( 0 != pRequest->id );
if ( !pRequest->bIntransit ) break;
pRequest->cntEvictionByTimer++;
if ( 20 < pRequest->cntEvictionByTimer ) { // 20 x 50ms is 1 second
std::chrono::time_point<std::chrono::system_clock> finished
= std::chrono::system_clock::now();
std::chrono::duration<double, std::milli> elapsed = finished - pRequest->dtSubmitted;
BOOST_LOG_TRIVIAL(error)
<< "IB details failed (timed) id "
<< pRequest->id
<< "," << pRequest->cntEvictionByTimer
<< "," << pRequest->pInstrument->GetInstrumentName()
<< "," << elapsed.count() << "ms"
;
//m_mapActiveRequests.erase( pRequest->id );
vRequestsForEvictionNotify.push_back( pRequest );
}
}
bContinue = ( 0 < m_mapActiveRequests.size() );
if ( !bContinue ) {
m_bEvictorStarted = false;
}
} // end scoped_lock
for ( vRequest_t::value_type pRequest: vRequestsForEvictionNotify ) {
fOnContractDetailDone = std::move( pRequest->fOnContractDetailDone );
if ( fOnContractDetailDone ) { // need to call endofcontract to clean this up
fOnContractDetailDone( false );
fOnContractDetailDone = nullptr;
}
}
{
std::scoped_lock<std::mutex> lock( m_mutexActiveRequests );
for ( vRequest_t::value_type pRequest: vRequestsForEvictionNotify ) {
m_mapActiveRequests.erase( pRequest->id ); // comes prior to clear
pRequest->Clear();
m_vRequestRecycling.push_back( pRequest );
}
}
if ( bContinue ) {
UpdateActiveRequests();
}
}
while ( bContinue );
//std::cout << "Evictor stopping" << std::endl;
}
)); // end eviction thread definition
} // if bStartEvictor
UpdateActiveRequests();
}
void TWS::UpdateActiveRequests() {
vRequest_t vRequestsToSubmit;
{
std::scoped_lock<std::mutex> lock( m_mutexActiveRequests );
unsigned int cntInTransit {};
for ( mapActiveRequests_t::value_type& vt: m_mapActiveRequests ) {
Request* pRequest = vt.second;
assert( 0 != pRequest->id );
if ( pRequest->bIntransit ) {
cntInTransit++;
}
else {
if ( maxRequestsInTransit > cntInTransit ) {
vRequestsToSubmit.push_back( pRequest );
pRequest->bIntransit = true;
cntInTransit++;
}
else {
break;
}
}
}
}
for ( vRequest_t::value_type pRequest: vRequestsToSubmit ) {
m_pTWS->reqContractDetails( pRequest->id, pRequest->contract );
}
}
//IBSymbol *TWS::NewCSymbol( const std::string &sSymbolName ) {
TWS::pSymbol_t TWS::NewCSymbol( Symbol::pInstrument_t pInstrument ) {
// todo: check that contract doesn't already exist
TickerId ticker = ++m_curTickerId;
// pSymbol_t pSymbol( new Symbol( pInstrument->GetInstrumentName( ou::tf::Instrument::eidProvider_t::EProviderIB ), pInstrument, ticker ) ); // is there someplace with the IB specific symbol name, or is it set already? (this simply creates the object, no additional function here)
pSymbol_t pSymbol( new Symbol( pInstrument->GetInstrumentName( ID() ), pInstrument, ticker ) ); // is there someplace with the IB specific symbol name, or is it set already? (this simply creates the object, no additional function here)
// todo: do an existance check on the instrument/symbol
ProviderInterface<TWS,Symbol>::AddCSymbol( pSymbol );
m_vTickerToSymbol.push_back( pSymbol );
m_mapContractToSymbol.insert( mapContractToSymbol_t::value_type( pInstrument->GetContract(), pSymbol ) );
return pSymbol;
}
void TWS::StartQuoteWatch( pSymbol_t pSymbol ) { // overridden from base class
StartQuoteTradeWatch( pSymbol );
}
void TWS::StopQuoteWatch( pSymbol_t pSymbol ) { // overridden from base class
StopQuoteTradeWatch( pSymbol );
}
void TWS::StartTradeWatch( pSymbol_t pSymbol ) { // overridden from base class
StartQuoteTradeWatch( pSymbol );
}
void TWS::StopTradeWatch( pSymbol_t pSymbol ) { // overridden from base class
StopQuoteTradeWatch( pSymbol );
}
void TWS::StartGreekWatch( pSymbol_t pSymbol ) { // overridden from base class
StartQuoteTradeWatch( pSymbol );
}
void TWS::StopGreekWatch( pSymbol_t pSymbol ) { // overridden from base class
StopQuoteTradeWatch( pSymbol );
}
void TWS::StartQuoteTradeWatch( pSymbol_t pIBSymbol ) {
if ( !pIBSymbol->GetQuoteTradeWatchInProgress() ) {
// start watch
Contract contract;
contract.conId = pIBSymbol->GetInstrument()->GetContract(); // mostly enough to have contract id
contract.exchange = pIBSymbol->GetInstrument()->GetExchangeName();
contract.currency = pIBSymbol->GetInstrument()->GetCurrencyName();
pIBSymbol->SetQuoteTradeWatchInProgress();
//pTWS->reqMktData( pIBSymbol->GetTickerId(), contract, "100,101,104,165,221,225,236", false );
TagValueListSPtr pMktDataOptions;
m_pTWS->reqMktData( pIBSymbol->GetTickerId(), contract, "", false, false, pMktDataOptions );
}
}
void TWS::StopQuoteTradeWatch( pSymbol_t pIBSymbol ) {
if ( pIBSymbol->QuoteWatchNeeded() || pIBSymbol->TradeWatchNeeded() || pIBSymbol->GreekWatchNeeded() ) {
// don't do anything if either a quote or trade or greek watch still in progress
}
else {
// stop watch
m_pTWS->cancelMktData( pIBSymbol->GetTickerId() );
pIBSymbol->ResetQuoteTradeWatchInProgress();
}
}
//void TWS::StartDepthWatch( pSymbol_t pIBSymbol) { // overridden from base class
// if ( !pIBSymbol->GetDepthWatchInProgress() ) {
// // start watch
// pIBSymbol->SetDepthWatchInProgress();
// }
//}
//void TWS::StopDepthWatch( pSymbol_t pIBSymbol) { // overridden from base class
// if ( pIBSymbol->DepthWatchNeeded() ) {
// }
// else {
// // stop watch
// pIBSymbol->ResetDepthWatchInProgress();
// }
//}
// indexed with InstrumentType::EInstrumentType
const char *TWS::szSecurityType[] = {
"NULL", "STK", "OPT", "FUT", "FOP", "CASH", "IND" }; // InsrumentType::EInstrumentType
const char *TWS::szOrderType[] = {
"UNKN", "MKT", "LMT", "STP", "STPLMT", "NULL", // OrderType::enumOrderType
"TRAIL", "TRAILLIMIT", "MKTCLS", "LMTCLS", "SCALE" };
void TWS::PlaceOrder( pOrder_t pOrder ) {
::Order twsorder;
twsorder.orderId = pOrder->GetOrderId();
twsorder.parentId = pOrder->GetParentOrderId();
Contract contract;
contract.conId = pOrder->GetInstrument()->GetContract(); // mostly enough to have contract id
contract.exchange = pOrder->GetInstrument()->GetExchangeName();
contract.currency = pOrder->GetInstrument()->GetCurrencyName();
std::string s;
switch ( pOrder->GetInstrument()->GetInstrumentType() ) {
case InstrumentType::Stock:
contract.exchange = "SMART";
break;
case InstrumentType::Future:
//
// s.Format( "%04d%02d", pOrder->GetInstrument()->GetExpiryYear(), pOrder->GetInstrument()->GetExpiryMonth() );
// contract.lastTradeDateOrContractMonth = s;
//if ( "CBOT" == contract.exchange ) contract.exchange = "ECBOT";
if ( 0 != pOrder->GetInstrument()->GetContract() ) {
}
else {
assert( false ); // need to fix this formatter, use the boost::gregorian date stuff
}
break;
case InstrumentType::Currency:
//twsorder.cashQty = 20000;
//contract.currency = "";
contract.secType = "CASH";
contract.symbol = Currency::Name[pOrder->GetInstrument()->GetCurrencyBase()];
contract.currency = Currency::Name[pOrder->GetInstrument()->GetCurrencyCounter()];
break;
default:
break;
}
twsorder.action = pOrder->GetOrderSideName();
twsorder.totalQuantity = __bid64_from_uint32( pOrder->GetQuanOrdered() );
twsorder.orderType = szOrderType[ pOrder->GetOrderType() ];
twsorder.tif = ou::tf::TimeInForce::Name[ pOrder->GetTimeInForce() ];
switch ( pOrder->GetTimeInForce() ) {
case ou::tf::ETimeInForce::GoodTillDate:
{
//twsorder.goodTillDate = "20080625 16:00:00";
ptime dt( pOrder->GetGoodTillDate() );
std::stringstream ss;
ss << dt.time_of_day() << " UTC";
twsorder.goodTillDate
= ou::tf::Instrument::BuildDate( dt.date() )
+ " "
+ ss.str();
}
break;
default:
break;
}
switch ( pOrder->GetTimeInForce() ) { // will need to confirm how this is signalled
case ou::tf::ETimeInForce::GoodAfterTime:
{
//twsorder.goodAfterTime = "20080625 09:30:00";
ptime dt( pOrder->GetGoodAfterTime() );
std::stringstream ss;
ss << dt.time_of_day();
twsorder.goodAfterTime
= ou::tf::Instrument::BuildDate( dt.date() )
+ " "
+ ss.str();
}
break;
default:
break;
}
switch ( pOrder->GetOrderType() ) {
case OrderType::Limit:
twsorder.lmtPrice = pOrder->GetPrice1();
twsorder.auxPrice = 0;
break;
case OrderType::Stop:
twsorder.lmtPrice = 0;
twsorder.auxPrice = pOrder->GetPrice1();
break;
case OrderType::Trail:
twsorder.lmtPrice = 0;
twsorder.trailStopPrice = pOrder->GetPrice1(); // stop price
twsorder.auxPrice = pOrder->GetPrice2(); // trail amount
break;
case OrderType::StopLimit:
twsorder.lmtPrice = pOrder->GetPrice1();
twsorder.auxPrice = pOrder->GetPrice2();
break;
default:
twsorder.lmtPrice = 0;
twsorder.auxPrice = 0;
}
twsorder.transmit = pOrder->GetTransmit();
twsorder.outsideRth = pOrder->GetOutsideRTH();
//twsorder.whatIf = true;
ProviderInterface<TWS,Symbol>::PlaceOrder( pOrder ); // any underlying initialization
m_pTWS->placeOrder( twsorder.orderId, contract, twsorder );
}
void TWS::PlaceComboOrder( pOrder_t pOrderEntry, pOrder_t pOrderStop ) {
pOrderEntry->SetTransmit( false );
PlaceOrder( pOrderEntry );
pOrderStop->SetParentOrderId( pOrderEntry->GetOrderId() );
PlaceOrder( pOrderStop );
}
void TWS::PlaceBracketOrder( pOrder_t pOrderEntry, pOrder_t pOrderProfit, pOrder_t pOrderStop ) {
pOrderEntry->SetTransmit( false );
PlaceOrder( pOrderEntry ); // limit or market
pOrderProfit->SetParentOrderId( pOrderEntry->GetOrderId() );
pOrderProfit->SetTransmit( false );
PlaceOrder( pOrderProfit ); // limit
pOrderStop->SetParentOrderId( pOrderEntry->GetOrderId() );
PlaceOrder( pOrderStop ); // stop or trail
}
void TWS::CancelOrder( pOrder_t pOrder ) {
ProviderInterface<TWS,Symbol>::CancelOrder( pOrder );
m_pTWS->cancelOrder( pOrder->GetOrderId() );
}
void TWS::tickPrice( TickerId tickerId, TickType tickType, double price, const TickAttrib& attrib ) {
// we seem to get ticks even though we havn't requested them, so ensure we only accept
// when a valid symbol has been defined
if ( ( tickerId > 0 ) && ( tickerId <= m_curTickerId ) ) {
Symbol::pSymbol_t pSym( m_vTickerToSymbol[ tickerId ] );
//std::cout << "tickPrice " << pSym->Name() << ", " << TickTypeStrings[tickType] << ", " << price << std::endl;
pSym->AcceptTickPrice( tickType, price );
}
}
void TWS::tickSize( TickerId tickerId, TickType tickType, Decimal size ) {
// we seem to get ticks even though we havn't requested them, so ensure we only accept
// when a valid symbol has been defined
if ( ( tickerId > 0 ) && ( tickerId <= m_curTickerId ) ) {
Symbol::pSymbol_t pSym( m_vTickerToSymbol[ tickerId ] );
//std::cout << "tickSize " << pSym->Name() << ", " << TickTypeStrings[tickType] << ", " << size << std::endl;
pSym->AcceptTickSize( tickType, size );
}
}
void TWS::tickOptionComputation( TickerId tickerId, TickType tickType, int tickAttrib, double impliedVol, double delta,
double optPrice, double pvDividend, double gamma, double vega, double theta, double undPrice ) {
Symbol::pSymbol_t pSym( m_vTickerToSymbol[ tickerId ] );
switch ( tickType ) {
case MODEL_OPTION:
pSym->Greeks( optPrice, undPrice, pvDividend, impliedVol, delta, gamma, vega, theta );
break;
case BID_OPTION_COMPUTATION:
break;
case ASK_OPTION_COMPUTATION:
break;
case LAST_OPTION_COMPUTATION:
break;
default:
break;
}
}
void TWS::tickGeneric(TickerId tickerId, TickType tickType, double value) {
// std::cout << "tickGeneric " << m_vTickerToSymbol[ tickerId ]->Name() << ", " << TickTypeStrings[tickType] << ", " << value << std::endl;
}
void TWS::tickString(TickerId tickerId, TickType tickType, const std::string& value) {
// we seem to get ticks even though we havn't requested them, so ensure we only accept
// when a valid symbol has been defined
if ( ( tickerId > 0 ) && ( tickerId <= m_curTickerId ) ) {
Symbol::pSymbol_t pSym( m_vTickerToSymbol[ tickerId ] );
//std::cout << "tickString " << pSym->Name() << ", "
// << TickTypeStrings[tickType] << ", " << value;
//std::cout << std::endl;
pSym->AcceptTickString( tickType, value );
}
}
void TWS::tickEFP(TickerId tickerId, TickType tickType, double basisPoints, const std::string& formattedBasisPoints,
double totalDividends, int holdDays, const std::string& futureExpiry, double dividendImpact, double dividendsToExpiry ) {
m_ss.str("");
m_ss << "tickEFP" << std::endl;
// OutputDebugString( m_ss.str().c_str() );
}
void TWS::openOrder( ::OrderId orderId, const ::Contract& contract, const ::Order& order, const ::OrderState& state) {
if ( order.whatIf ) {
m_ss.str("");
m_ss
<< "WhatIf: ordid=" << orderId << ", cont.sym=" << contract.symbol
<< ", state.commission=" << state.commission
<< " " << state.commissionCurrency
<< ", state.equityWithLoanBefore=" << state.equityWithLoanBefore
<< ", state.equityWithLoanChange=" << state.equityWithLoanChange
<< ", state.equityWithLoanAfter=" << state.equityWithLoanAfter
<< ", state.initMarginBefore=" << state.initMarginBefore
<< ", state.initMarginChange=" << state.initMarginChange
<< ", state.initMarginAfter=" << state.initMarginAfter
<< ", state.maintMarginBefore=" << state.maintMarginBefore
<< ", state.maintMarginChange=" << state.maintMarginChange
<< ", state.maintMarginAfter=" << state.maintMarginAfter
<< ", state.maxcom=" << state.maxCommission
<< ", state.mincom=" << state.minCommission
<< std::endl;
// OutputDebugString( m_ss.str().c_str() );
}
else {
m_ss.str("");
m_ss
<< "OpenOrder: ordid=" << orderId
<< ", state.stat=" << state.status
<< ", cont.sym=" << contract.symbol
<< ", order.action=" << order.action
<< ", state.commission=" << state.commission
<< " " << state.commissionCurrency
//<< ", ord.id=" << order.orderId
//<< ", ord.ref=" << order.orderRef
//<< ", state.warning=" << state.warningText
<< std::endl;
// std::cout << m_ss.str(); // ****
//OutputDebugString( m_ss.str().c_str() );
//if ( std::numeric_limits<double>::max(0) != state.commission )
if ( 1e308 > state.commission )
// reports total commission for order rather than increment
OrderManager::GlobalInstance().ReportCommission( orderId, state.commission );
// use spirit to do this to make it faster with a trie, or use keyword match
DecodeStatusWord::EStatus status = dsw.Match( state.status );
switch ( status ) {
case DecodeStatusWord::Submitted:
break;
case DecodeStatusWord::Filled:
break;
case DecodeStatusWord::Cancelled:
OrderManager::GlobalInstance().ReportCancellation( order.orderId );
break;
case DecodeStatusWord::Inactive:
break;
case DecodeStatusWord::PreSubmitted:
break;
case DecodeStatusWord::PendingSubmit: // coincides with popup in TWS, can't remember what the message was, probably trading outside of regular hours, or due to something similar as described in next comment
break;
case DecodeStatusWord::PendingCancel: // pendingsubmit, pendingcancel happened for order to short, but IB didn't have anything to loan for shorting
break;
case DecodeStatusWord::Unknown:
assert( false );
break;
}
}
if ( state.warningText != "" ) {
m_ss.str("");
m_ss << "Open Order Warning: " << state.warningText << std::endl;
// OutputDebugString( m_ss.str().c_str() );
}
}
void TWS::orderStatus( OrderId orderId, const std::string& status, Decimal filled,
Decimal remaining, double avgFillPrice, int permId, int parentId,
double lastFillPrice, int clientId, const std::string& whyHeld, double mktCapPrice )
{
if ( false ) {
m_ss.str("");
m_ss
<< "OrderStatus: ordid=" << orderId
<< ", stat=" << status
<< ", filled=" << decimalStringToDisplay( filled )
<< ", rem=" << decimalStringToDisplay( remaining )
<< ", avgfillprc=" << avgFillPrice
<< ", permid=" << permId
//<< ", parentid=" << parentId
<< ", lfp=" << lastFillPrice
//<< ", clid=" << clientId
//<< ", yh=" << whyHeld
<< std::endl;
//std::cout << m_ss.str(); // ****
// OutputDebugString( m_ss.str().c_str() );
}
DecodeStatusWord::EStatus status_ = dsw.Match( status );
switch ( status_ ) {
case DecodeStatusWord::Cancelled:
OrderManager::GlobalInstance().ReportCancellation( orderId );
break;
case DecodeStatusWord::Submitted:
case DecodeStatusWord::Filled:
break;
case DecodeStatusWord::PreSubmitted:
break;
case DecodeStatusWord::PendingCancel:
break;
default:
std::cout << "TWS::orderStatus: " << orderId << "," << status << std::endl;
}
}
void TWS::execDetails( int reqId, const ::Contract& contract, const ::Execution& execution ) {
m_ss.str("");
m_ss
<< "execDetails: "
<< " sym=" << contract.localSymbol
// << ", oid=" << orderId
<< ", reqId=" << reqId
<< ", ex.oid=" << execution.orderId
<< ", ex.pr=" << execution.price
<< ", ex.sh=" << execution.shares
<< ", ex.sd=" << execution.side
<< ", ex.ti=" << execution.time
<< ", ex.ex=" << execution.exchange
//<< ", ex.liq=" << execution.liquidation
<< ", ex.pid=" << execution.permId
<< ", ex.acct=" << execution.acctNumber
//<< ", ex.clid=" << execution.clientId
<< ", ex.xid=" << execution.execId
<< std::endl;
// std::cout << m_ss.str(); // ****
// OutputDebugString( m_ss.str().c_str() );
OrderSide::EOrderSide side = OrderSide::Unknown;
if ( "BOT" == execution.side ) side = OrderSide::Buy; // could try just first character for fast comparison
if ( "SLD" == execution.side ) side = OrderSide::Sell;
if ( OrderSide::Unknown == side ) {
m_ss.str("");
m_ss << "Unknown execution side: " << execution.side << std::endl;
// OutputDebugString( m_ss.str().c_str() );
}
else {
ou::tf::Execution exec( execution.price, execution.shares, side, execution.exchange, execution.execId );
OrderManager::GlobalInstance().ReportExecution( execution.orderId, exec );
}
}
void TWS::execDetailsEnd( int reqId) {}
/*
OrderStatus: ordid=1057, stat=Filled, fild=200, rem=0, avgfillprc=117, permid=2147126208, parentid=0, lfp=117, clid=0, yh=
OpenOrder: ordid=1057, cont.sym=ICE, ord.id=1057, ord.ref=, state.stat=Filled, state.warning=, order.action=BUY, state.commission=1 USD
OrderStatus: ordid=1057, stat=Filled, fild=200, rem=0, avgfillprc=117, permid=2147126208, parentid=0, lfp=117, clid=0, yh=
OpenOrder: ordid=1057, cont.sym=ICE, ord.id=1057, ord.ref=, state.stat=Filled, state.warning=, order.action=BUY, state.commission=1 USD
execDetails: sym=ICE, oid=1057, ex.oid=1057, ex.pr=117, ex.sh=100, ex.sd=BOT, ex.ti=20080607 12:39:55, ex.ex=NYSE, ex.liq=0, ex.pid=2147126208, ex.acct=DU15067, ex.clid=0, ex.xid=0000ea6a.44f438e4.01.01
OrderStatus: ordid=1057, stat=Submitted, fild=100, rem=100, avgfillprc=117, permid=2147126208, parentid=0, lfp=117, clid=0, yh=
OpenOrder: ordid=1057, cont.sym=ICE, ord.id=1057, ord.ref=, state.stat=Submitted, state.warning=, order.action=BUY, state.commission=1 USD
OrderStatus: ordid=1057, stat=Submitted, fild=100, rem=100, avgfillprc=117, permid=2147126208, parentid=0, lfp=117, clid=0, yh=
OpenOrder: ordid=1057, cont.sym=ICE, ord.id=1057, ord.ref=, state.stat=Submitted, state.warning=, order.action=BUY, state.commission=1.79769e+308 USD
execDetails: sym=ICE, oid=1057, ex.oid=1057, ex.pr=117, ex.sh=100, ex.sd=BOT, ex.ti=20080607 12:39:14, ex.ex=NYSE, ex.liq=0, ex.pid=2147126208, ex.acct=DU15067, ex.clid=0, ex.xid=0000ea6a.44f438d5.01.01
current time 1212851947
*/
// check for symbol existance and return, else exeption
TWS::pSymbol_t TWS::GetSymbol( long ContractId ) {
mapContractToSymbol_t::iterator iterId = m_mapContractToSymbol.find( ContractId );
if ( m_mapContractToSymbol.end() == iterId ) {
throw std::out_of_range( "can't find contract" );
}
return iterId->second;
}
// check for symbol existance, and return, else add and return
TWS::pSymbol_t TWS::GetSymbol( pInstrument_t instrument ) {
long contractId;
contractId = instrument->GetContract();
//assert( 0 != contractId );
if ( 0 == contractId ) {
throw std::runtime_error( "TWS::GetSymbol: contract id not supplied" );
}
pSymbol_t pSymbol;
mapContractToSymbol_t::iterator iterId = m_mapContractToSymbol.find( contractId );
if ( m_mapContractToSymbol.end() == iterId ) {
pSymbol = NewCSymbol( instrument );
}
else {
pSymbol = iterId->second;
}
return pSymbol;
}
void TWS::error(const int id, const int errorCode, const std::string& errorString) {
switch ( errorCode ) {
case 103: // Duplicate order id
// id is the order number
BOOST_LOG_TRIVIAL(error) << "IB error (1) " << id << ", " << errorCode << ", " << errorString;
break;
case 110: // The price does not conform to the minimum price variation for this contract.
// id is the order number
// TODO something like: OrderManager::GlobalInstance().ReportCancellation( orderId );
BOOST_LOG_TRIVIAL(error) << "IB error (2)" << id << ", " << errorCode << ", " << errorString;
break;