-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathib.go
2391 lines (2083 loc) · 72.5 KB
/
ib.go
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
package ibsync
import (
"context"
"errors"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/scmhub/ibapi"
)
const MaxSyncedSubAccounts = 50
// A CancelFunc tells an operation to abandon its work. A CancelFunc does not wait for the work to stop.
// A CancelFunc may be called by multiple goroutines simultaneously. After the first call, subsequent calls to a CancelFunc do nothing.
type CancelFunc func()
// IB struct offers direct access to the current state, such as orders, executions, positions, tickers etc.
// This state is automatically kept in sync with the TWS/IBG application.
// IB has most request methods of EClient, with the same names and parameters (except for the reqId parameter which is not needed anymore).
type IB struct {
eClient *ibapi.EClient
wrapper *WrapperSync
config *Config
}
func NewIB(config ...*Config) *IB {
wrapper := NewWrapperSync()
c := ibapi.NewEClient(wrapper)
ib := &IB{eClient: c, wrapper: wrapper}
if len(config) > 0 {
ib.config = config[0]
}
return ib
}
// SetClientLogLevel sets the log level of the client.
// logLevel can be:
// -1 = trace // zerolog.TraceLevel
//
// 0 = debug // zerolog.DebugLevel
// 1 = info // zerolog.InfoLevel
// 2 = warn // zerolog.WarnLevel
// 3 = error // zerolog.ErrorLevel
// 4 = fatal // zerolog.FatalLevel
// 5 = panic // zerolog.PanicLevel
func (ib *IB) SetClientLogLevel(logLevel int64) {
SetLogLevel(int(logLevel))
}
// SetConsoleWriter will set pretty log to the console.
func (in *IB) SetConsoleWriter() {
SetConsoleWriter()
}
// Connect must be called before any other.
// There is no feedback for a successful connection, but a subsequent attempt to connect will return the message "Already connected."
func (ib *IB) Connect(config ...*Config) error {
if len(config) > 0 {
ib.config = config[0] // override config
}
if ib.config == nil {
return ErrNoConfigProvided
}
err := ib.eClient.Connect(ib.config.Host, ib.config.Port, ib.config.ClientID)
if err != nil {
return err
}
time.Sleep(1 * time.Second)
// bind manual orders
if ib.config.ClientID == 0 {
ib.ReqAutoOpenOrders(true)
}
accounts := ib.ManagedAccounts()
if ib.config.Account == "" && len(accounts) == 1 {
ib.config.Account = accounts[0]
}
if !ib.config.InSync {
log.Warn().Msg("this client will not be kept in sync with the TWS/IBG application")
return nil
}
// Start sync
if !ib.config.ReadOnly {
// Get and sync open orders
openOrdersChan, _ := Subscribe("OpenOrdersEnd")
// defer unsubscribe()
ib.ReqOpenOrders()
<-openOrdersChan
// Get and sync completed orders
completedOrdersChan, _ := Subscribe("CompletedOrdersEnd")
// defer unsubscribe()
ib.ReqCompletedOrders(false)
<-completedOrdersChan
}
if ib.config.Account != "" {
accountUpdatesChan, _ := Subscribe("AccountDownloadEnd")
// defer unsubscribe()
ib.ReqAccountUpdates(true, ib.config.Account)
<-accountUpdatesChan
}
log.Info().Msg("client in sync with the TWS/IBG application")
return nil
}
// Disconnect terminates the connections with TWS.
// Calling this function does not cancel orders that have already been sent.
func (ib *IB) Disconnect() error {
return ib.eClient.Disconnect()
}
// IsConnected checks if there is a connection to TWS or GateWay
func (ib *IB) IsConnected() bool {
return ib.eClient.IsConnected()
}
// Context returns the ibsync Context
func (ib *IB) Context() context.Context {
return ib.eClient.Ctx
}
// SetTimeout sets the timeout for receiving messages from TWS/IBG.
// Default timeout duration is TIMEOUT = 30 * time.Second
func (ib *IB) SetTimeout(Timeout time.Duration) {
ib.config.Timeout = Timeout
}
// ManagedAccounts returns a list of account names.
func (ib *IB) ManagedAccounts() []string {
state.mu.Lock()
defer state.mu.Unlock()
return append(state.accounts[:0:0], state.accounts...)
}
// IsPaperAccount checks if the accounts are paper accounts
func (ib *IB) IsPaperAccount() bool {
return strings.HasPrefix(ib.ManagedAccounts()[0], "D")
}
// IsFinancialAdvisorAccount checks if the accounts is a financial advisor account.
func (ib *IB) IsFinancialAdvisorAccount() bool {
return strings.HasPrefix(ib.ManagedAccounts()[0], "F")
}
// NextID returns a local next ID. It is initialised at connection.
// NextID = -1 if non initialised.
func (ib *IB) NextID() int64 {
state.mu.Lock()
defer state.mu.Unlock()
currentID := state.nextValidID
state.nextValidID++
return currentID
}
// AccountValues returns a slice of account values for the given accounts.
//
// If no account is provided it will return values of all accounts.
// Account values need to be subscribed by ReqAccountUpdates. This is done at start up unless WithoutSync option is used.
func (ib *IB) AccountValues(account ...string) AccountValues {
state.mu.Lock()
defer state.mu.Unlock()
var avs AccountValues
for _, v := range state.updateAccountValues {
if len(account) == 0 || slices.Contains(account, v.Account) {
avs = append(avs, v)
}
}
return avs
}
// AccountSumary returns a slice of account values for the given accounts.
//
// If no account is provided it will return values of all accounts.
// On the first run it is calling ReqAccountSummary and is blocking, after it returns the last summary requested.
// To request a new summary call ReqAccountSummary.
func (ib *IB) AccountSummary(account ...string) AccountSummary {
state.mu.Lock()
var as AccountSummary
for _, v := range state.accountSummary {
if len(account) == 0 || slices.Contains(account, v.Account) {
as = append(as, v)
}
}
state.mu.Unlock()
if len(as) != 0 {
return as
}
tags := []string{"AccountType", "NetLiquidation", "TotalCashValue", "SettledCash", "AccruedCash", "BuyingPower", "EquityWithLoanValue",
"PreviousDayEquityWithLoanValue", "GrossPositionValue", "RegTEquity", "RegTMargin", "SMA", "InitMarginReq", "MaintMarginReq", "AvailableFunds",
"ExcessLiquidity", "Cushion", "FullInitMarginReq", "FullMaintMarginReq", "FullAvailableFunds", "FullExcessLiquidity", "LookAheadNextChange",
"LookAheadInitMarginReq", "LookAheadMaintMarginReq", "LookAheadAvailableFunds", "LookAheadExcessLiquidity", "HighestSeverity", "DayTradesRemaining",
"DayTradesRemainingT+1", "DayTradesRemainingT+2", "DayTradesRemainingT+3", "DayTradesRemainingT+4", "Leverage,$LEDGER:ALL"}
tagsString := strings.Join(tags, ",")
ras, err := ib.ReqAccountSummary("All", tagsString)
if err != nil {
return nil
}
for _, v := range ras {
if len(account) == 0 || slices.Contains(account, v.Account) {
as = append(as, v)
}
}
return as
}
// Portfolio returns a slice of portfolio item for the given accounts.
//
// If no account is provided it will return items of all accounts.
// Portfolios need to be subscribed by ReqAccountUpdates. This is done at start up unless WithoutSync option is used.
func (ib *IB) Portfolio(account ...string) []PortfolioItem {
state.mu.Lock()
defer state.mu.Unlock()
var pis []PortfolioItem
for acc, piMap := range state.portfolio {
if len(account) == 0 || slices.Contains(account, acc) {
for _, pi := range piMap {
pis = append(pis, pi)
}
}
}
return pis
}
// ReqPositions subscribes to real-time position stream for all accounts.
func (ib *IB) ReqPositions() {
ib.eClient.ReqPositions()
}
// CancelPositions cancels real-time position subscription.
func (ib *IB) CancelPositions() {
ib.eClient.CancelPositions()
}
// Position returns a slice of the last positions received for the given accounts.
//
// If no account is provided it will return positions of all accounts.
// Positions need to be subscribed with ReqPositions first.
func (ib *IB) Positions(account ...string) []Position {
state.mu.Lock()
defer state.mu.Unlock()
var ps []Position
for acc, pMap := range state.positions {
if len(account) == 0 || slices.Contains(account, acc) {
for _, p := range pMap {
ps = append(ps, p)
}
}
}
return ps
}
// PositionChan returns a channel that receives a continuous feed of Position updates.
//
// You need to subscribe to positions by calling ReqPositions.
// Do NOT close the channel.
func (ib *IB) PositionChan(account ...string) chan Position {
ctx := ib.eClient.Ctx
positionChan := make(chan Position)
ch, unsubscribe := Subscribe("Position")
var once sync.Once
go func() {
defer func() {
unsubscribe()
once.Do(func() { close(positionChan) })
}()
for {
select {
case <-ctx.Done():
return
case msg, ok := <-ch:
if !ok {
return
}
var pos Position
if err := Decode(&pos, msg); err != nil {
return
}
if len(account) == 0 || slices.Contains(account, pos.Account) {
positionChan <- pos
}
}
}
}()
return positionChan
}
// ReqPnL requests and subscribe the PnL of assigned account.
func (ib *IB) ReqPnL(account string, modelCode string) {
reqID := ib.NextID()
key := Key(account, modelCode)
state.mu.Lock()
_, ok := state.pnlKey2ReqID[key]
if ok {
log.Warn().Str("account", account).Str("modelCode", modelCode).Msg("Pnl request already made")
return
}
state.pnlKey2ReqID[key] = reqID
state.reqID2Pnl[reqID] = &Pnl{Account: account, ModelCode: modelCode}
state.mu.Unlock()
ib.eClient.ReqPnL(reqID, account, modelCode)
}
// CancelPnL cancels the PnL update of assigned account.
func (ib *IB) CancelPnL(account string, modelCode string) {
state.mu.Lock()
reqID, ok := state.pnlKey2ReqID[Key(account, modelCode)]
if !ok {
log.Warn().Str("account", account).Str("modelCode", modelCode).Msg("No pnl request to cancel")
return
}
state.mu.Unlock()
ib.eClient.CancelPnL(reqID)
}
// Pnl returns a slice of Pnl values based on the specified account and model code.
//
// If account is an empty string, it returns Pnls for all accounts.
// If modelCode is an empty string, it returns Pnls for all model codes.
func (ib *IB) Pnl(account string, modelCode string) []Pnl {
state.mu.Lock()
defer state.mu.Unlock()
var pnls []Pnl
for _, pnl := range state.reqID2Pnl {
if (account == "" || account == pnl.Account) && (modelCode == "" || modelCode == pnl.ModelCode) {
pnls = append(pnls, *pnl)
}
}
return pnls
}
// PnlChan returns a channel that receives a continuous feed of Pnl updates.
//
// Do NOT close the channel.
func (ib *IB) PnlChan(account string, modelCode string) chan Pnl {
ctx := ib.eClient.Ctx
pnlChan := make(chan Pnl)
ch, unsubscribe := Subscribe("Pnl")
var once sync.Once
go func() {
defer func() {
unsubscribe()
once.Do(func() { close(pnlChan) })
}()
for {
select {
case <-ctx.Done():
return
case msg, ok := <-ch:
if !ok {
return
}
var pnl Pnl
if err := Decode(&pnl, msg); err != nil {
return
}
if (account == "" || account == pnl.Account) && (modelCode == "" || modelCode == pnl.ModelCode) {
pnlChan <- pnl
}
}
}
}()
return pnlChan
}
// ReqPnLSingle requests and subscribe the single contract PnL of assigned account.
func (ib *IB) ReqPnLSingle(account string, modelCode string, contractID int64) {
reqID := ib.NextID()
key := Key(account, modelCode, contractID)
state.mu.Lock()
_, ok := state.pnlSingleKey2ReqID[key]
if ok {
log.Warn().Str("account", account).Str("modelCode", modelCode).Int64("contractID", contractID).Msg("Pnl single request already made")
return
}
state.pnlSingleKey2ReqID[key] = reqID
state.reqID2PnlSingle[reqID] = &PnlSingle{Account: account, ModelCode: modelCode, ConID: contractID}
state.mu.Unlock()
ib.eClient.ReqPnLSingle(reqID, account, modelCode, contractID)
}
// CancelPnLSingle cancels the single contract PnL update of assigned account.
func (ib *IB) CancelPnLSingle(account string, modelCode string, contractID int64) {
state.mu.Lock()
reqID, ok := state.pnlSingleKey2ReqID[Key(account, modelCode, contractID)]
if !ok {
log.Warn().Str("account", account).Str("modelCode", modelCode).Int64("contractID", contractID).Msg("No pnl single request to cancel")
return
}
state.mu.Unlock()
ib.eClient.CancelPnLSingle(reqID)
}
// PnlSingle returns a slice of PnlSingle values based on the specified account, model code, and contract ID.
//
// If account is an empty string, it returns PnlSingles for all accounts.
// If modelCode is an empty string, it returns PnlSingles for all model codes.
// If contractID is zero, it returns PnlSingles for all contracts.
func (ib *IB) PnlSingle(account string, modelCode string, contractID int64) []PnlSingle {
state.mu.Lock()
defer state.mu.Unlock()
var pnlSingles []PnlSingle
for _, pnlSingle := range state.reqID2PnlSingle {
if (account == "" || account == pnlSingle.Account) && (modelCode == "" || modelCode == pnlSingle.ModelCode) && (contractID == 0 || contractID == pnlSingle.ConID) {
pnlSingles = append(pnlSingles, *pnlSingle)
}
}
return pnlSingles
}
// PnlSingleChan returns a channel that receives a continuous feed of PnlSingle updates.
//
// Do NOT close the channel.
func (ib *IB) PnlSingleChan(account string, modelCode string, contractID int64) chan PnlSingle {
ctx := ib.eClient.Ctx
pnlSingleChan := make(chan PnlSingle)
ch, unsubscribe := Subscribe("PnlSingle")
var once sync.Once
go func() {
defer unsubscribe()
defer func() { once.Do(func() { close(pnlSingleChan) }) }()
for {
select {
case <-ctx.Done():
return
case msg, ok := <-ch:
if !ok {
return
}
var pnlSingle PnlSingle
if err := Decode(&pnlSingle, msg); err != nil {
return
}
if (account == "" || account == pnlSingle.Account) && (modelCode == "" || modelCode == pnlSingle.ModelCode) && (contractID == 0 || contractID == pnlSingle.ConID) {
pnlSingleChan <- pnlSingle
}
}
}
}()
return pnlSingleChan
}
// Trades returns a slice of all trades from this session
func (ib *IB) Trades() []*Trade {
state.mu.Lock()
defer state.mu.Unlock()
var ts []*Trade
for _, t := range state.trades {
ts = append(ts, t)
}
return ts
}
// OpenTrades returns a slice of copies of all open trades from this session
func (ib *IB) OpenTrades() []*Trade {
state.mu.Lock()
defer state.mu.Unlock()
var ts []*Trade
for _, t := range state.trades {
if !t.IsDone() {
ts = append(ts, t)
}
}
return ts
}
// Orders returns a slice of all orders from this session
func (ib *IB) Orders() []Order {
state.mu.Lock()
defer state.mu.Unlock()
var ts []Order
for _, t := range state.trades {
ts = append(ts, *t.Order)
}
return ts
}
// OpenOrders returns a slice of all open orders from this session
func (ib *IB) OpenOrders() []Order {
state.mu.Lock()
defer state.mu.Unlock()
var ts []Order
for _, t := range state.trades {
if !t.IsDone() {
ts = append(ts, *t.Order)
}
}
return ts
}
// Ticker returns a *Ticker for the provided and contract and a bool to tell if the ticker exists.
func (ib *IB) Ticker(contract *Contract) (*Ticker, bool) {
state.mu.Lock()
defer state.mu.Unlock()
val, exists := state.tickers[contract]
return val, exists
}
// Tickers returns a slice of all Tickers
func (ib *IB) Tickers() []*Ticker {
state.mu.Lock()
defer state.mu.Unlock()
var ts []*Ticker
for _, t := range state.tickers {
ts = append(ts, t)
}
return ts
}
// NewTick returns the list of NewsTick
func (ib *IB) NewsTick() []NewsTick {
state.mu.Lock()
defer state.mu.Unlock()
return append(state.newsTicks[:0:0], state.newsTicks...)
}
// ReqCurrentTime asks the current system time on the server side.
func (ib *IB) ReqCurrentTime() (currentTime time.Time, err error) {
ctx, cancel := context.WithTimeout(ib.eClient.Ctx, ib.config.Timeout)
defer cancel()
ch, unsubscribe := Subscribe("CurrentTime")
defer unsubscribe()
ib.eClient.ReqCurrentTime()
select {
case <-ctx.Done():
return time.Time{}, ctx.Err()
case msg := <-ch:
if err = Decode(¤tTime, msg); err != nil {
return time.Time{}, err
}
return currentTime, nil
}
}
// ReqCurrentTime asks the current system time on the server side.
func (ib *IB) ReqCurrentTimeInMillis() (int64, error) {
ctx, cancel := context.WithTimeout(ib.eClient.Ctx, ib.config.Timeout)
defer cancel()
ch, unsubscribe := Subscribe("CurrentTimeInMillis")
defer unsubscribe()
ib.eClient.ReqCurrentTimeInMillis()
select {
case <-ctx.Done():
return 0, ctx.Err()
case msg := <-ch:
var ctim int64
if err := Decode(&ctim, msg); err != nil {
return 0, err
}
return ctim, nil
}
}
// ServerVersion returns the version of the TWS instance to which the API application is connected.
func (ib *IB) ServerVersion() int {
return ib.eClient.ServerVersion()
}
// SetServerLogLevel sets the log level of the server.
// logLevel can be:
// 1 = SYSTEM
// 2 = ERROR (default)
// 3 = WARNING
// 4 = INFORMATION
// 5 = DETAIL
func (ib *IB) SetServerLogLevel(logLevel int64) {
ib.eClient.SetServerLogLevel(logLevel)
}
// ConnectionTime is the time the API application made a connection to TWS.
func (ib *IB) TWSConnectionTime() string {
return ib.eClient.TWSConnectionTime()
}
// SetServerLogLevel setups the log level of server.
// The default detail level is ERROR. For more details, see API Logging.
func (ib *IB) SetLogLevel(logLevel int64) {
ib.eClient.SetServerLogLevel(logLevel)
}
// ReqMktData request market data stream. It returns a *Ticker that will be updated.
//
// contract contains a description of the Contract for which market data is being requested.
// genericTickList is 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"
// For snapshots requests use Snapshot().
// mktDataOptions is for internal use only.Use default value XYZ.
func (ib *IB) ReqMktData(contract *Contract, genericTickList string, mktDataOptions ...TagValue) *Ticker {
reqID := ib.NextID()
state.mu.Lock()
ticker := state.startTicker(reqID, contract, "mktData")
state.mu.Unlock()
ib.eClient.ReqMktData(reqID, contract, genericTickList, false, false, mktDataOptions)
return ticker
}
// CancelMktData stops the market data stream for the specified contract.
//
// Do not use CancelMktData for Snapshot() calls
func (ib *IB) CancelMktData(contract *Contract) {
state.mu.Lock()
ticker := state.tickers[contract]
reqID, ok := state.endTicker(ticker, "mktData")
state.mu.Unlock()
if !ok {
log.Error().Err(errUnknowReqID).Int64("conID", contract.ConID).Msg("<CancelMktData>")
}
ib.eClient.CancelMktData(reqID)
log.Debug().Int64("reqID", reqID).Msg("<CancelMktData>")
}
// Snapshot return a market data snapshot.
//
// contract contains a description of the Contract for which market data is being requested.
// regulatorySnapshot: With the US Value Snapshot Bundle for stocks, regulatory snapshots are available for 0.01 USD each.
func (ib *IB) Snapshot(contract *Contract, regulatorySnapshot ...bool) (*Ticker, error) {
ctx, cancel := context.WithTimeout(ib.eClient.Ctx, ib.config.Timeout)
defer cancel()
reqID := ib.NextID()
ch, unsubscribe := Subscribe(reqID)
defer unsubscribe()
state.mu.Lock()
ticker := state.startTicker(reqID, contract, "snapshot")
state.mu.Unlock()
defer func() {
state.mu.Lock()
state.endTicker(ticker, "snapshot")
state.mu.Unlock()
}()
regulatory := false
if len(regulatorySnapshot) > 0 {
regulatory = regulatorySnapshot[0]
}
ib.eClient.ReqMktData(reqID, contract, "", true, regulatory, nil)
var err error
for {
select {
case <-ctx.Done():
return ticker, ctx.Err()
case msg := <-ch:
if isErrorMsg(msg) {
err = msg2Error(msg)
if err != WarnDelayedMarketData && err != ErrPartlyNotSubsribed {
return ticker, msg2Error(msg)
}
break
}
switch msg {
case "TickSnapshotEnd":
return ticker, err
default:
return ticker, errors.New(msg)
}
}
}
}
// ReqMarketDataType changes the market data type.
//
// 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.
// marketDataType:
//
// 1 -> realtime streaming market data
// 2 -> frozen market data
// 3 -> delayed market data
// 4 -> delayed frozen market data
func (ib *IB) ReqMarketDataType(marketDataType int64) {
log.Debug().Int64("marketDataType", marketDataType).Msg("<ReqMarketDataType>")
ib.eClient.ReqMarketDataType(marketDataType)
}
// ReqSmartComponents requests the smartComponents.
//
// SmartComponents provide mapping from single letter codes to exchange names.
// Note: The exchanges must be open when using this request, otherwise an empty list is returned.
func (ib *IB) ReqSmartComponents(bboExchange string) ([]SmartComponent, error) {
ctx, cancel := context.WithTimeout(ib.eClient.Ctx, ib.config.Timeout)
defer cancel()
reqID := ib.NextID()
ch, unsubscribe := Subscribe(reqID)
defer unsubscribe()
ib.eClient.ReqSmartComponents(reqID, bboExchange)
select {
case <-ctx.Done():
return nil, ctx.Err()
case msg := <-ch:
var scs []SmartComponent
if isErrorMsg(msg) {
return scs, msg2Error(msg)
}
if err := Decode(&scs, msg); err != nil {
return nil, err
}
return scs, nil
}
}
// ReqMarketRule requests the price increments rules.
//
// Note: market rule ids can be obtained by invoking reqContractDetails on a particular contract
func (ib *IB) ReqMarketRule(marketRuleID int64) ([]PriceIncrement, error) {
ctx, cancel := context.WithTimeout(ib.eClient.Ctx, ib.config.Timeout)
defer cancel()
topic := Key("MarketRule", marketRuleID)
ch, unsubscribe := Subscribe(topic)
defer unsubscribe()
ib.eClient.ReqMarketRule(marketRuleID)
select {
case <-ctx.Done():
return nil, ctx.Err()
case msg := <-ch:
var pis []PriceIncrement
if err := Decode(&pis, msg); err != nil {
return nil, err
}
return pis, nil
}
}
// ReqTickByTickData subscribe to tick-by-tick data stream and returns the *Ticker.
//
// contract is the *Contract you want subsciption for.
// tickType is one of "Last", "AllLast", "BidAsk" or "MidPoint".
// numberOfTicks is the number of ticks or 0 for unlimited.
// ignoreSize ignores bid/ask ticks that only update the size.
func (ib *IB) ReqTickByTickData(contract *Contract, tickType string, numberOfTicks int64, ignoreSize bool) *Ticker {
reqID := ib.NextID()
state.mu.Lock()
ticker := state.startTicker(reqID, contract, tickType)
state.mu.Unlock()
ib.eClient.ReqTickByTickData(reqID, contract, tickType, numberOfTicks, ignoreSize)
return ticker
}
// CancelTickByTickData unsubscribes from tick-by-tick for given contract and tick type.
func (ib *IB) CancelTickByTickData(contract *Contract, tickType string) error {
state.mu.Lock()
ticker := state.tickers[contract]
reqID, ok := state.endTicker(ticker, tickType)
state.mu.Unlock()
if !ok {
log.Error().Err(errUnknowReqID).Int64("conID", contract.ConID).Msg("<CancelTickByTickData>")
return errUnknowReqID
}
ib.eClient.CancelTickByTickData(reqID)
log.Debug().Int64("reqID", reqID).Msg("<CancelTickByTickData>")
return nil
}
// MidPoint requests and returns the last Mid Point
func (ib *IB) MidPoint(contract *Contract) (TickByTickMidPoint, error) {
ctx, cancel := context.WithTimeout(ib.eClient.Ctx, ib.config.Timeout)
defer cancel()
reqID := ib.NextID()
ch, unsubscribe := Subscribe(reqID)
defer unsubscribe()
ib.eClient.ReqTickByTickData(reqID, contract, "MidPoint", 0, true)
defer ib.eClient.CancelTickByTickData(reqID)
select {
case <-ctx.Done():
return TickByTickMidPoint{}, ctx.Err()
case msg := <-ch:
var tbtmp TickByTickMidPoint
if isErrorMsg(msg) {
return tbtmp, msg2Error(msg)
}
if err := Decode(&tbtmp, msg); err != nil {
return TickByTickMidPoint{}, err
}
return tbtmp, nil
}
}
// CalculateImpliedVolatility calculates the implied volatility given the option price.
func (ib *IB) CalculateImpliedVolatility(contract *Contract, optionPrice float64, underPrice float64, impVolOptions ...TagValue) (*TickOptionComputation, error) {
ctx, cancel := context.WithTimeout(ib.eClient.Ctx, ib.config.Timeout)
defer cancel()
reqID := ib.NextID()
ch, unsubscribe := Subscribe(reqID)
defer unsubscribe()
ib.eClient.CalculateImpliedVolatility(reqID, contract, optionPrice, underPrice, impVolOptions)
select {
case <-ctx.Done():
ib.eClient.CancelCalculateImpliedVolatility(reqID)
return nil, ctx.Err()
case msg := <-ch:
if isErrorMsg(msg) {
return nil, msg2Error(msg)
}
items := Split(msg)
switch items[0] {
case "OptionComputation":
var toc *TickOptionComputation
if err := Decode(&toc, items[1]); err != nil {
return toc, err
}
return toc, nil
default:
log.Error().Err(errUnknowItemType).Int64("reqID", reqID).Str("Type", items[0]).Msg("<CalculateImpliedVolatility>")
return nil, errUnknowItemType
}
}
}
// CalculateOptionPrice calculates the price of the option given the volatility.
func (ib *IB) CalculateOptionPrice(contract *Contract, volatility float64, underPrice float64, optPrcOptions ...TagValue) (*TickOptionComputation, error) {
ctx, cancel := context.WithTimeout(ib.eClient.Ctx, ib.config.Timeout)
defer cancel()
reqID := ib.NextID()
ch, unsubscribe := Subscribe(reqID)
defer unsubscribe()
ib.eClient.CalculateOptionPrice(reqID, contract, volatility, underPrice, optPrcOptions)
select {
case <-ctx.Done():
ib.eClient.CancelCalculateOptionPrice(reqID)
return nil, ctx.Err()
case msg := <-ch:
if isErrorMsg(msg) {
return nil, msg2Error(msg)
}
items := Split(msg)
switch items[0] {
case "OptionComputation":
var toc *TickOptionComputation
if err := Decode(&toc, items[1]); err != nil {
return toc, err
}
return toc, nil
default:
log.Error().Err(errUnknowItemType).Int64("reqID", reqID).Str("Type", items[0]).Msg("<CalculateOptionPrice>")
return nil, errUnknowItemType
}
}
}
// PlaceOrder places a new order or modify an existing order.
// It returns a *Trade that is kept live updated with status changes, fils, etc.
//
// contract is the *Contract to use for order.
// order contains the details of the order to be placed.
func (ib *IB) PlaceOrder(contract *Contract, order *Order) *Trade {
if order.OrderID == 0 {
order.OrderID = ib.NextID()
}
ib.eClient.PlaceOrder(order.OrderID, contract, order)
key := orderKey(order.ClientID, order.OrderID, order.PermID)
state.mu.Lock()
defer state.mu.Unlock()
trade, ok := state.trades[key]
if ok {
// modification of an existing order
if trade.IsDone() {
panic("try to modify a done trade")
}
logEntry := TradeLogEntry{
Time: time.Now().UTC(),
Status: trade.OrderStatus.Status,
Message: "Modify",
}
trade.addLog(logEntry)
log.Debug().Int64("orderID", order.OrderID).Str("message", "modify order").Msg("<PlaceOrder>")
} else {
// new order
order.ClientID = ib.config.ClientID
trade = NewTrade(contract, order)
key = orderKey(order.ClientID, order.OrderID, order.PermID) // clientID is updated
state.trades[key] = trade
log.Debug().Int64("orderID", order.OrderID).Str("message", "open order").Msg("<PlaceOrder>")
}
return trade
}
// CancelOrder cancels the given order.
// orderCancel is an OrderCancel struct. You can pass NewOrderCancel()
func (ib *IB) CancelOrder(order *Order, orderCancel OrderCancel) {
log.Debug().Int64("orderID", order.OrderID).Msg("<CancelOrder>")
ib.eClient.CancelOrder(order.OrderID, orderCancel)
}
// ReqGlobalCancel cancels all open orders globally. It cancels both API and TWS open orders.
func (ib *IB) ReqGlobalCancel() {
log.Debug().Msg("<ReqGlobalCancel>")
ib.eClient.ReqGlobalCancel(NewOrderCancel())
}
// ReqOpenOrders requests the open orders that were placed from this client.
// The client with a clientId of 0 will also receive the TWS-owned open orders.
// These orders will be associated with the client and a new orderId will be generated.
// This association will persist over multiple API and TWS sessions.
func (ib *IB) ReqOpenOrders() {
log.Debug().Msg("<ReqOpenOrders>")
ib.eClient.ReqOpenOrders()
}
// ReqAutoOpenOrders requests that newly created TWS orders be implicitly associated with the client.
// This request can only be made from a client with clientId of 0.
// if autoBind is set to TRUE, newly created TWS orders will be implicitly associated with the client.
// If set to FALSE, no association will be made.
func (ib *IB) ReqAutoOpenOrders(autoBind bool) {
log.Debug().Msg("<ReqAutoOpenOrders>")
ib.eClient.ReqAutoOpenOrders(autoBind)
}
// ReqAllOpenOrders requests the open orders placed from all clients and also from TWS.
// Each open order will be fed back through the openOrder() and orderStatus() functions on the EWrapper.
// No association is made between the returned orders and the requesting client.
func (ib *IB) ReqAllOpenOrders() {
log.Debug().Msg("<ReqAllOpenOrders>")
ib.eClient.ReqAllOpenOrders()
}
// ReqAccountUpdates will start getting account values, portfolio, and last update time information.
func (ib *IB) ReqAccountUpdates(subscribe bool, accountName string) {
ib.eClient.ReqAccountUpdates(subscribe, accountName)
}
// ReqAccountSummary requests and keep up to date the data that appears
// on the TWS Account Window Summary tab. The data is returned by
// accountSummary().
// This request is designed for an FA managed account but can be
// used for any multi-account structure.
// reqId is the ID of the data request. it Ensures that responses are matched
// to requests If several requests are in process.
// groupName sets to All to return account summary data for all
//
// accounts, or set to a specific Advisor Account Group name that has
// already been created in TWS Global Configuration.
//
// tags:str - A comma-separated list of account tags. Available tags are:
//
// accountountType
// NetLiquidation,
// TotalCashValue - Total cash including futures pnl
// SettledCash - For cash accounts, this is the same as
// TotalCashValue
// AccruedCash - Net accrued interest
// BuyingPower - The maximum amount of marginable US stocks the account can buy
// EquityWithLoanValue - Cash + stocks + bonds + mutual funds
// PreviousDayEquityWithLoanValue,
// GrossPositionValue - The sum of the absolute value of all stock and equity option positions