-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.go
3491 lines (2765 loc) · 109 KB
/
client.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
/*
EClient is the main struct to use from API user's point of view.
It takes care of almost everything:
- implementing the requests
- creating the answer decoder
- creating the connection to TWS/IBGW
The user just needs to override EWrapper methods to receive the answers.
*/
package ibapi
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"fmt"
"os"
"os/signal"
"strconv"
"sync"
"syscall"
)
type ConnState int
const (
DISCONNECTED ConnState = iota
CONNECTING
CONNECTED
REDIRECT
)
func (cs ConnState) String() string {
switch cs {
case DISCONNECTED:
return "disconnected"
case CONNECTING:
return "connecting"
case CONNECTED:
return "connected"
case REDIRECT:
return "redirect"
default:
return "unknown connection state"
}
}
// EClient is the main struct to use from API user's point of view.
type EClient struct {
host string
port int
clientID int64
connectOptions string
conn *Connection
serverVersion Version
connTime string
connState ConnState
writer *bufio.Writer
scanner *bufio.Scanner
wrapper EWrapper
decoder *EDecoder
reqChan chan []byte
Ctx context.Context
Cancel context.CancelFunc
extraAuth bool
wg sync.WaitGroup
err error
}
// NewEClient returns a new Eclient.
func NewEClient(wrapper EWrapper) *EClient {
if wrapper == nil {
wrapper = &Wrapper{}
}
c := &EClient{wrapper: wrapper}
c.reset()
return c
}
func (c *EClient) reset() {
c.host = ""
c.port = -1
c.clientID = -1
c.extraAuth = false
c.conn = &Connection{}
c.serverVersion = -1
c.connTime = ""
// writer
c.writer = bufio.NewWriter(c.conn)
// init scanner
c.scanner = bufio.NewScanner(c.conn)
c.scanner.Split(scanFields)
c.scanner.Buffer(make([]byte, 4096), MAX_MSG_LEN)
c.reqChan = make(chan []byte, 10)
c.Ctx, c.Cancel = context.WithCancel(context.Background())
c.wg = sync.WaitGroup{}
c.err = nil
c.setConnState(DISCONNECTED)
c.connectOptions = ""
}
func (c *EClient) setConnState(state ConnState) {
cs := c.connState
c.connState = state
log.Debug().Stringer("from", cs).Stringer("to", c.connState).Msg("connection state changed")
}
// request is a goroutine that will get the req from reqChan and send it to TWS.
func (c *EClient) request() {
log.Debug().Msg("requester started")
defer log.Debug().Msg("requester ended")
c.wg.Add(1)
defer c.wg.Done()
for {
select {
case <-c.Ctx.Done():
return
case req := <-c.reqChan:
if !c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
break
}
nn, err := c.writer.Write(req)
if err != nil {
log.Error().Err(err).Int("nbytes", nn).Bytes("reqMsg", req).Msg("requester write error")
break
}
err = c.writer.Flush()
if err != nil {
log.Error().Err(err).Bytes("reqMsg", req).Msg("requester flush error")
c.writer.Reset(c.conn)
}
}
}
}
// startAPI initiates the message exchange between the client application and the TWS/IB Gateway.
func (c *EClient) startAPI() error {
if !c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return NOT_CONNECTED
}
var msg []byte
const VERSION = 2
if c.serverVersion >= MIN_SERVER_VER_OPTIONAL_CAPABILITIES {
msg = makeFields(START_API, VERSION, c.clientID, "")
} else {
msg = makeFields(START_API, VERSION, c.clientID)
}
if _, err := c.writer.Write(msg); err != nil {
return err
}
if err := c.writer.Flush(); err != nil {
return err
}
return nil
}
// 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 (c *EClient) Connect(host string, port int, clientID int64) error {
c.host = host
c.port = port
c.clientID = clientID
log.Info().Str("host", host).Int("port", port).Int64("clientID", clientID).Msg("Connecting to IB server")
if err := c.conn.connect(c.host, c.port); err != nil {
log.Error().Err(CONNECT_FAIL).Msg("Connection fail")
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), CONNECT_FAIL.Code, CONNECT_FAIL.Msg, "")
c.reset()
return CONNECT_FAIL
}
// HandShake with the TWS or GateWay to ensure the version,
log.Debug().Msg("HandShake with TWS or GateWay")
head := []byte("API\x00")
connectOptions := ""
if c.connectOptions != "" {
connectOptions = " " + c.connectOptions
}
sizeofCV := make([]byte, 4)
clientVersion := []byte(fmt.Sprintf("v%d..%d%s", MIN_CLIENT_VER, MAX_CLIENT_VER, connectOptions))
binary.BigEndian.PutUint32(sizeofCV, uint32(len(clientVersion)))
var msg bytes.Buffer
msg.Write(head)
msg.Write(sizeofCV)
msg.Write(clientVersion)
log.Debug().Bytes("header", msg.Bytes()).Msg("send handShake header")
if _, err := c.writer.Write(msg.Bytes()); err != nil {
return err
}
if err := c.writer.Flush(); err != nil {
return err
}
log.Debug().Msg("recv handShake Info")
// scan once to get server info
if !c.scanner.Scan() {
return c.scanner.Err()
}
// Init server info
msgBytes := c.scanner.Bytes()
serverInfo := splitMsgBytes(msgBytes)
v, _ := strconv.Atoi(string(serverInfo[0]))
c.serverVersion = Version(v)
c.connTime = string(serverInfo[1])
log.Info().Int("serverVersion", v).Str("connectionTime", c.connTime).Msg("Handshake completed")
// init decoder
c.decoder = &EDecoder{wrapper: c.wrapper, serverVersion: c.serverVersion}
//start Ereader
go EReader(c.Ctx, c.scanner, c.decoder, &c.wg)
// start requester
go c.request()
c.setConnState(CONNECTED)
c.wrapper.ConnectAck()
// startAPI
if err := c.startAPI(); err != nil {
return err
}
log.Debug().Msg("API started")
// graceful shutdown
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigChan
log.Info().Msg("detected KeyboardInterrupt, SystemExit")
c.Disconnect()
os.Exit(1)
}()
log.Debug().Msg("IB Client Connected!")
return nil
}
// Disconnect terminates the connections with TWS.
// Calling this function does not cancel orders that have already been sent.
func (c *EClient) Disconnect() error {
if !c.IsConnected() {
return nil
}
c.Cancel()
if err := c.conn.disconnect(); err != nil {
return err
}
c.wg.Wait()
defer c.reset()
defer c.wrapper.ConnectionClosed()
defer log.Debug().Msg("IB Client Disconnected!")
return c.err
}
// IsConnected checks connection to TWS or GateWay.
func (c *EClient) IsConnected() bool {
return c.conn.IsConnected() && c.connState == CONNECTED
}
// SetConnectionOptions setup the Connection Options.
func (c *EClient) SetConnectionOptions(opts string) {
c.connectOptions = opts
}
// ReqCurrentTime asks the current system time on the server side.
func (c *EClient) ReqCurrentTime() {
if !c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
const VERSION int64 = 1
msg := makeFields(REQ_CURRENT_TIME, VERSION)
c.reqChan <- msg
}
// ServerVersion returns the version of the TWS instance to which the API application is connected.
func (c *EClient) ServerVersion() Version {
return c.serverVersion
}
// SetServerLogLevel sets the log level of the server.
// logLevel can be:
// 1 = SYSTEM
// 2 = ERROR (default)
// 3 = WARNING
// 4 = INFORMATION
// 5 = DETAIL
func (c *EClient) SetServerLogLevel(logLevel int64) {
if !c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
const VERSION = 1
msg := makeFields(SET_SERVER_LOGLEVEL, VERSION, logLevel)
c.reqChan <- msg
}
// ConnectionTime is the time the API application made a connection to TWS.
func (c *EClient) TWSConnectionTime() string {
return c.connTime
}
// ##########################################################################
// # Market Data
// ##########################################################################
// ReqMktData Call this function to request market data.
// The market data will be returned by the tickPrice and tickSize events.
// reqID, the ticker 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 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"
// snapshot checks to return a single snapshot of Market data and have the market data subscription cancel.
// Do not enter any genericTicklist values if you use snapshots.
// regulatorySnapshot: With the US Value Snapshot Bundle for stocks, regulatory snapshots are available for 0.01 USD each.
// mktDataOptions is for internal use only.Use default value XYZ.
func (c *EClient) ReqMktData(reqID TickerID, contract *Contract, genericTickList string, snapshot bool, regulatorySnapshot bool, mktDataOptions []TagValue) {
if !c.IsConnected() {
c.wrapper.Error(reqID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
if c.serverVersion < MIN_SERVER_VER_DELTA_NEUTRAL && contract.DeltaNeutralContract != nil {
c.wrapper.Error(reqID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support delta-neutral orders.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_REQ_MKT_DATA_CONID && contract.ConID > 0 {
c.wrapper.Error(reqID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support conId parameter.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_TRADING_CLASS && contract.TradingClass != "" {
c.wrapper.Error(reqID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support tradingClass parameter in reqMktData.", "")
return
}
const VERSION = 11
fields := make([]interface{}, 0, 30)
fields = append(fields,
REQ_MKT_DATA,
VERSION,
reqID,
)
if c.serverVersion >= MIN_SERVER_VER_REQ_MKT_DATA_CONID {
fields = append(fields, contract.ConID)
}
fields = append(fields,
contract.Symbol,
contract.SecType,
contract.LastTradeDateOrContractMonth,
contract.Strike,
contract.Right,
contract.Multiplier, // srv v15 and above
contract.Exchange,
contract.PrimaryExchange, // srv v14 and above
contract.Currency,
contract.LocalSymbol) // srv v2 and above
if c.serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
fields = append(fields, contract.TradingClass)
}
// Send combo legs for BAG requests (srv v8 and above)
if contract.SecType == "BAG" {
comboLegsCount := len(contract.ComboLegs)
fields = append(fields, comboLegsCount)
for _, comboLeg := range contract.ComboLegs {
fields = append(fields,
comboLeg.ConID,
comboLeg.Ratio,
comboLeg.Action,
comboLeg.Exchange)
}
}
if c.serverVersion >= MIN_SERVER_VER_DELTA_NEUTRAL {
if contract.DeltaNeutralContract != nil {
fields = append(fields,
true,
contract.DeltaNeutralContract.ConID,
contract.DeltaNeutralContract.Delta,
contract.DeltaNeutralContract.Price)
} else {
fields = append(fields, false)
}
}
fields = append(fields,
genericTickList, // srv v31 and above
snapshot) // srv v35 and above
if c.serverVersion >= MIN_SERVER_VER_REQ_SMART_COMPONENTS {
fields = append(fields, regulatorySnapshot)
}
// send mktDataOptions parameter
if c.serverVersion >= MIN_SERVER_VER_LINKING {
// current doc says this part if for "internal use only" -> won't support it
if len(mktDataOptions) > 0 {
log.Panic().Msg("not supported")
}
fields = append(fields, "")
}
msg := makeFields(fields...)
c.reqChan <- msg
}
// CancelMktData stops the market data flow for the specified TickerId.
func (c *EClient) CancelMktData(reqID TickerID) {
if !c.IsConnected() {
c.wrapper.Error(reqID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
const VERSION = 2
msg := makeFields(CANCEL_MKT_DATA, VERSION, reqID)
c.reqChan <- 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 (c *EClient) ReqMarketDataType(marketDataType int64) {
if !c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
if !c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
if c.serverVersion < MIN_SERVER_VER_REQ_MARKET_DATA_TYPE {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support market data type requests.", "")
return
}
const VERSION = 1
msg := makeFields(REQ_MARKET_DATA_TYPE, VERSION, marketDataType)
c.reqChan <- msg
}
// ReqSmartComponents request the smartComponents.
func (c *EClient) ReqSmartComponents(reqID int64, bboExchange string) {
if !c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
if c.serverVersion < MIN_SERVER_VER_REQ_SMART_COMPONENTS {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support smart components request.", "")
return
}
msg := makeFields(REQ_SMART_COMPONENTS, reqID, bboExchange)
c.reqChan <- msg
}
// ReqMarketRule requests the market rule.
func (c *EClient) ReqMarketRule(marketRuleID int64) {
if !c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
if c.serverVersion < MIN_SERVER_VER_MARKET_RULES {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support market rule requests.", "")
return
}
msg := makeFields(REQ_MARKET_RULE, marketRuleID)
c.reqChan <- msg
}
// ReqTickByTickData request the tick-by-tick data.
// tickType is "Last", "AllLast", "BidAsk" or "MidPoint".
// numberOfTicks is the number of ticks or 0 for unlimited.
// ignoreSize will ignore bid/ask ticks that only update the size if true.
// Result will be delivered via wrapper.TickByTickAllLast() wrapper.TickByTickBidAsk() wrapper.TickByTickMidPoint().
func (c *EClient) ReqTickByTickData(reqID int64, contract *Contract, tickType string, numberOfTicks int64, ignoreSize bool) {
if !c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
if c.serverVersion < MIN_SERVER_VER_TICK_BY_TICK {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support tick-by-tick data requests.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_TICK_BY_TICK_IGNORE_SIZE {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support ignoreSize and numberOfTicks parameters in tick-by-tick data requests.", "")
return
}
fields := make([]interface{}, 0, 17)
fields = append(fields, REQ_TICK_BY_TICK_DATA,
reqID,
contract.ConID,
contract.Symbol,
contract.SecType,
contract.LastTradeDateOrContractMonth,
contract.Strike,
contract.Right,
contract.Multiplier,
contract.Exchange,
contract.PrimaryExchange,
contract.Currency,
contract.LocalSymbol,
contract.TradingClass,
tickType)
if c.serverVersion >= MIN_SERVER_VER_TICK_BY_TICK_IGNORE_SIZE {
fields = append(fields, numberOfTicks, ignoreSize)
}
msg := makeFields(fields...)
c.reqChan <- msg
}
// CancelTickByTickData cancel the tick-by-tick data
func (c *EClient) CancelTickByTickData(reqID int64) {
if !c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
if c.serverVersion < MIN_SERVER_VER_TICK_BY_TICK {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support tick-by-tick data requests.", "")
return
}
msg := makeFields(CANCEL_TICK_BY_TICK_DATA, reqID)
c.reqChan <- msg
}
// ##########################################################################
// # Options
// ##########################################################################
// CalculateImpliedVolatility calculates the implied volatility of the option.
// Result will be delivered via wrapper.TickOptionComputation().
func (c *EClient) CalculateImpliedVolatility(reqID int64, contract *Contract, optionPrice float64, underPrice float64, impVolOptions []TagValue) {
if !c.IsConnected() {
c.wrapper.Error(reqID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
if c.serverVersion < MIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support calculateImpliedVolatility req.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_TRADING_CLASS && contract.TradingClass != "" {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support tradingClass parameter in calculateImpliedVolatility.", "")
return
}
const VERSION = 3
fields := make([]interface{}, 0, 19)
fields = append(fields,
REQ_CALC_IMPLIED_VOLAT,
VERSION,
reqID,
contract.ConID,
contract.Symbol,
contract.SecID,
contract.LastTradeDateOrContractMonth,
contract.Strike,
contract.Right,
contract.Multiplier,
contract.Exchange,
contract.PrimaryExchange,
contract.Currency,
contract.LocalSymbol)
if c.serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
fields = append(fields, contract.TradingClass)
}
fields = append(fields, optionPrice, underPrice)
if c.serverVersion >= MIN_SERVER_VER_LINKING {
var implVolOptBuffer bytes.Buffer
tagValuesCount := len(impVolOptions)
fields = append(fields, tagValuesCount)
for _, tv := range impVolOptions {
implVolOptBuffer.WriteString(tv.Tag)
implVolOptBuffer.WriteString("=")
implVolOptBuffer.WriteString(tv.Value)
implVolOptBuffer.WriteString(";")
}
fields = append(fields, implVolOptBuffer.Bytes())
}
msg := makeFields(fields...)
c.reqChan <- msg
}
// CancelCalculateImpliedVolatility cancels a request to calculate volatility for a supplied option price and underlying price.
func (c *EClient) CancelCalculateImpliedVolatility(reqID int64) {
if !c.IsConnected() {
c.wrapper.Error(reqID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
if c.serverVersion < MIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT {
c.wrapper.Error(reqID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support calculateImpliedVolatility req.", "")
return
}
const VERSION = 1
msg := makeFields(CANCEL_CALC_IMPLIED_VOLAT, VERSION, reqID)
c.reqChan <- msg
}
// CalculateOptionPrice calculate the price of the option
// Call this function to calculate price for a supplied option volatility and underlying price.
// Result will be delivered via wrapper.TickOptionComputation().
func (c *EClient) CalculateOptionPrice(reqID int64, contract *Contract, volatility float64, underPrice float64, optPrcOptions []TagValue) {
if !c.IsConnected() {
c.wrapper.Error(reqID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
if c.serverVersion < MIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT {
c.wrapper.Error(reqID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support calculateImpliedVolatility req.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_TRADING_CLASS {
c.wrapper.Error(reqID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support tradingClass parameter in calculateImpliedVolatility.", "")
return
}
const VERSION = 3
fields := make([]interface{}, 0, 19)
fields = append(fields,
REQ_CALC_OPTION_PRICE,
VERSION,
reqID,
contract.ConID,
contract.Symbol,
contract.SecID,
contract.LastTradeDateOrContractMonth,
contract.Strike,
contract.Right,
contract.Multiplier,
contract.Exchange,
contract.PrimaryExchange,
contract.Currency,
contract.LocalSymbol)
if c.serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
fields = append(fields, contract.TradingClass)
}
fields = append(fields, volatility, underPrice)
if c.serverVersion >= MIN_SERVER_VER_LINKING {
var optPrcOptBuffer bytes.Buffer
tagValuesCount := len(optPrcOptions)
fields = append(fields, tagValuesCount)
for _, tv := range optPrcOptions {
optPrcOptBuffer.WriteString(tv.Tag)
optPrcOptBuffer.WriteString("=")
optPrcOptBuffer.WriteString(tv.Value)
optPrcOptBuffer.WriteString(";")
}
fields = append(fields, optPrcOptBuffer.Bytes())
}
msg := makeFields(fields...)
c.reqChan <- msg
}
// CancelCalculateOptionPrice cancels the calculation of option price.
func (c *EClient) CancelCalculateOptionPrice(reqID int64) {
if !c.IsConnected() {
c.wrapper.Error(reqID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
if c.serverVersion < MIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT {
c.wrapper.Error(reqID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support calculateImpliedVolatility req.", "")
return
}
const VERSION = 1
msg := makeFields(CANCEL_CALC_OPTION_PRICE, VERSION, reqID)
c.reqChan <- msg
}
// ExerciseOptions exercises the option defined by the contract.
// reqId is the ticker id and must be a unique value.
// contract contains a description of the contract to be exercised.
// exerciseAction specifies whether you want the option to lapse or be exercised.
//
// Values: 1 = exercise, 2 = lapse.
//
// exerciseQuantity is the quantity you want to exercise.
// account is the 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: 0 = no, 1 = yes.
// manualOrderTime isthe manual order time.
// customerAccount is the customer account.
// professionalCustomer:bool - professional customer.
func (c *EClient) ExerciseOptions(reqID TickerID, contract *Contract, exerciseAction int, exerciseQuantity int, account string, override int, manualOrderTime string, customerAccount string, professionalCustomer bool) {
if !c.IsConnected() {
c.wrapper.Error(reqID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
if c.serverVersion < MIN_SERVER_VER_TRADING_CLASS && (contract.TradingClass != "" || contract.ConID > 0) {
c.wrapper.Error(reqID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support conId, multiplier, tradingClass parameter in exerciseOptions.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_MANUAL_ORDER_TIME_EXERCISE_OPTIONS && manualOrderTime != "" {
c.wrapper.Error(reqID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support manual order time parameter in exerciseOptions.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_CUSTOMER_ACCOUNT && customerAccount != "" {
c.wrapper.Error(reqID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support customer account parameter in exerciseOptions.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_PROFESSIONAL_CUSTOMER && professionalCustomer {
c.wrapper.Error(reqID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support professional customer parameter in exerciseOptions.", "")
return
}
const VERSION = 2
fields := make([]interface{}, 0, 17)
fields = append(fields, EXERCISE_OPTIONS, VERSION, reqID)
// send contract fields
if c.serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
fields = append(fields, contract.ConID)
}
fields = append(fields,
contract.Symbol,
contract.LastTradeDateOrContractMonth,
contract.Strike,
contract.Right,
contract.Multiplier,
contract.Exchange,
contract.Currency,
contract.LocalSymbol)
if c.serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
fields = append(fields, contract.TradingClass)
}
fields = append(fields,
exerciseAction,
exerciseQuantity,
account,
override)
if c.serverVersion >= MIN_SERVER_VER_MANUAL_ORDER_TIME_EXERCISE_OPTIONS {
fields = append(fields, manualOrderTime)
}
if c.serverVersion >= MIN_SERVER_VER_CUSTOMER_ACCOUNT {
fields = append(fields, customerAccount)
}
if c.serverVersion >= MIN_SERVER_VER_PROFESSIONAL_CUSTOMER {
fields = append(fields, professionalCustomer)
}
msg := makeFields(fields...)
c.reqChan <- msg
}
// ##########################################################################
// # Orders
// ##########################################################################
// PlaceOrder places an order.
// The order status will be returned by the orderStatus event.
// The order id must specify a unique value. When the order status returns, it will be identified by this tag.
// This tag is also used when canceling the order.
// contract contains a description of the contract which is being traded.
// order contains the details of the traded order.
func (c *EClient) PlaceOrder(orderID OrderID, contract *Contract, order *Order) {
if !c.IsConnected() {
c.wrapper.Error(orderID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
if c.serverVersion < MIN_SERVER_VER_DELTA_NEUTRAL && contract.DeltaNeutralContract != nil {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support delta-neutral orders.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_SCALE_ORDERS2 && order.ScaleSubsLevelSize != UNSET_INT {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support Subsequent Level Size for Scale orders.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_ALGO_ORDERS && order.AlgoStrategy != "" {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support algo orders.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_NOT_HELD && order.NotHeld {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support notHeld parameter.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_SEC_ID_TYPE && (contract.SecType != "" || contract.SecID != "") {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support secIdType and secId parameters.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_PLACE_ORDER_CONID && contract.ConID != UNSET_INT && contract.ConID > 0 {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support conId parameter.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_SSHORTX && order.ExemptCode != -1 {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support exemptCode parameter.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_SSHORTX {
for _, comboLeg := range contract.ComboLegs {
if comboLeg.ExemptCode != -1 {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support exemptCode parameter.", "")
return
}
}
}
if c.serverVersion < MIN_SERVER_VER_HEDGE_ORDERS && order.HedgeType != "" {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support hedge orders.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_OPT_OUT_SMART_ROUTING && order.OptOutSmartRouting {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support optOutSmartRouting parameter.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_DELTA_NEUTRAL_CONID {
if order.DeltaNeutralConID > 0 || order.DeltaNeutralSettlingFirm != "" || order.DeltaNeutralClearingAccount != "" || order.DeltaNeutralClearingIntent != "" {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support deltaNeutral parameters: ConId, SettlingFirm, ClearingAccount, ClearingIntent.", "")
return
}
}
if c.serverVersion < MIN_SERVER_VER_DELTA_NEUTRAL_OPEN_CLOSE {
if order.DeltaNeutralOpenClose != "" ||
order.DeltaNeutralShortSale ||
order.DeltaNeutralShortSaleSlot > 0 ||
order.DeltaNeutralDesignatedLocation != "" {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support deltaNeutral parameters: OpenClose, ShortSale, ShortSaleSlot, DesignatedLocation.", "")
return
}
}
if c.serverVersion < MIN_SERVER_VER_SCALE_ORDERS3 {
if (order.ScalePriceIncrement > 0 && order.ScalePriceIncrement != UNSET_FLOAT) &&
(order.ScalePriceAdjustValue != UNSET_FLOAT ||
order.ScalePriceAdjustInterval != UNSET_INT ||
order.ScaleProfitOffset != UNSET_FLOAT ||
order.ScaleAutoReset ||
order.ScaleInitPosition != UNSET_INT ||
order.ScaleInitFillQty != UNSET_INT ||
order.ScaleRandomPercent) {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+
" It does not support Scale order parameters: PriceAdjustValue, PriceAdjustInterval, "+
"ProfitOffset, AutoReset, InitPosition, InitFillQty and RandomPercent.", "")
return
}
}
if c.serverVersion < MIN_SERVER_VER_ORDER_COMBO_LEGS_PRICE && contract.SecType == "BAG" {
for _, orderComboLeg := range order.OrderComboLegs {
if orderComboLeg.Price != UNSET_FLOAT {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support per-leg prices for order combo legs.", "")
return
}
}
}
if c.serverVersion < MIN_SERVER_VER_TRAILING_PERCENT && order.TrailingPercent != UNSET_FLOAT {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support trailing percent parameter.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_TRADING_CLASS && contract.TradingClass != "" {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support tradingClass parameter in placeOrder.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_SCALE_TABLE &&
(order.ScaleTable != "" || order.ActiveStartTime != "" || order.ActiveStopTime != "") {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support scaleTable, activeStartTime and activeStopTime parameters.", "")
return
}
if c.serverVersion < MIN_SERVER_VER_ALGO_ID && order.AlgoID != "" {
c.wrapper.Error(orderID, currentTimeMillis(), UPDATE_TWS.Code, UPDATE_TWS.Msg+" It does not support algoId parameter.", "")
return