-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathclient.go
3075 lines (2609 loc) · 91.1 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
package ibapi
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"go.uber.org/zap"
)
const (
// MaxRequests is the max request that tws or gateway could take pre second.
MaxRequests = 95
// RequestInternal is the internal microseconds between requests.
RequestInternal = 2
// MaxClientVersion is the max client version that this implement could support.
MaxClientVersion = 148
)
// IbClient is the key component which is used to send request to TWS ro Gateway , such subscribe market data or place order
type IbClient struct {
host string
port int
clientID int64
conn *IbConnection
scanner *bufio.Scanner
writer *bufio.Writer
wrapper IbWrapper
decoder ibDecoder
connectOptions string
reqIDSeq int64
reqChan chan []byte
errChan chan error
msgChan chan []byte
timeChan chan time.Time
terminatedSignal chan int // signal to terminate the three goroutine
done chan bool // done signal is delivered via disconnect
clientVersion Version
serverVersion Version
connTime string
extraAuth bool
wg sync.WaitGroup
ctx context.Context
err error
}
// NewIbClient create IbClient with wrapper
func NewIbClient(wrapper IbWrapper) *IbClient {
ic := &IbClient{}
ic.SetWrapper(wrapper)
ic.reset()
return ic
}
// ConnState is the State of connection.
/*
DISCONNECTED
CONNECTING
CONNECTED
REDIRECT
*/
func (ic *IbClient) ConnState() int {
return ic.conn.state
}
func (ic *IbClient) setConnState(connState int) {
preState := ic.conn.state
ic.conn.state = connState
log.Debug("change connection state", zap.Int("previous", preState), zap.Int("current", connState))
}
// GetReqID before request data or place order
func (ic *IbClient) GetReqID() int64 {
return atomic.AddInt64(&ic.reqIDSeq, 1)
}
// SetWrapper setup the Wrapper
func (ic *IbClient) SetWrapper(wrapper IbWrapper) {
ic.wrapper = wrapper
log.Debug("set wrapper", zap.Reflect("wrapper", wrapper))
ic.decoder = ibDecoder{wrapper: ic.wrapper}
}
// SetContext setup the Connection Context
func (ic *IbClient) SetContext(ctx context.Context) {
ic.ctx = ctx
}
// SetConnectionOptions setup the Connection Options
func (ic *IbClient) SetConnectionOptions(opts string) {
ic.connectOptions = opts
}
// Connect try to connect the TWS or IB GateWay, after this, handshake should be call to get the connection done
func (ic *IbClient) Connect(host string, port int, clientID int64) error {
ic.host, ic.port, ic.clientID = host, port, clientID
log.Info("Connect to client", zap.String("host", host), zap.Int("port", port), zap.Int64("clientID", clientID))
ic.setConnState(CONNECTING)
if err := ic.conn.connect(host, port); err != nil {
ic.wrapper.Error(NO_VALID_ID, CONNECT_FAIL.code, CONNECT_FAIL.msg)
ic.reset()
return CONNECT_FAIL
}
// set done chan after connection is made
ic.done = make(chan bool)
return nil
}
// Disconnect disconnect the client
/*
1.send terminatedSignal to receiver, decoder and requester
2.disconnect the connection
3.wait the 3 goroutine
4.callback ConnectionClosed
5.send the err to done chan
6.reset the IbClient
*/
func (ic *IbClient) Disconnect() error {
log.Debug("close terminatedSignal chan")
close(ic.terminatedSignal) // close make the term signal chan unblocked
if err := ic.conn.disconnect(); err != nil {
return err
}
ic.wg.Wait()
// should not reconnect IbClient in ConnectionClosed
// because reset would be called right after ConnectionClosed
defer func() {
if len(ic.done) > 0 {
ic.done <- true
}
}()
defer ic.reset()
defer ic.wrapper.ConnectionClosed()
defer log.Info("Disconnected!")
return ic.err
}
// IsConnected check if there is a connection to TWS or GateWay
func (ic *IbClient) IsConnected() bool {
return ic.conn.state == CONNECTED
}
// send the clientId to TWS or Gateway
func (ic *IbClient) startAPI() error {
var startAPI []byte
const v = 2
if ic.serverVersion >= mMIN_SERVER_VER_OPTIONAL_CAPABILITIES {
startAPI = makeMsgBytes(mSTART_API, v, ic.clientID, "")
} else {
startAPI = makeMsgBytes(mSTART_API, v, ic.clientID)
}
log.Debug("start API", zap.Binary("bytes", startAPI))
if _, err := ic.writer.Write(startAPI); err != nil {
return err
}
return ic.writer.Flush()
}
// HandShake with the TWS or GateWay to ensure the version,
// send the startApi header ,then receive serverVersion
// and connection time to comfirm the connection with TWS
func (ic *IbClient) HandShake() error {
log.Info("HandShake with TWS or GateWay")
var msg bytes.Buffer
var msgBytes []byte
head := []byte("API\x00")
connectOptions := ""
if ic.connectOptions != "" {
connectOptions = " " + ic.connectOptions
}
clientVersion := []byte(fmt.Sprintf("v%d..%d%s", MIN_CLIENT_VER, MAX_CLIENT_VER, connectOptions))
sizeofCV := make([]byte, 4)
binary.BigEndian.PutUint32(sizeofCV, uint32(len(clientVersion)))
// send head and client version to TWS or Gateway to tell the client version range
msg.Write(head)
msg.Write(sizeofCV)
msg.Write(clientVersion)
log.Debug("send handShake header", zap.Binary("header", msg.Bytes()))
if _, err := ic.writer.Write(msg.Bytes()); err != nil {
return err
}
if err := ic.writer.Flush(); err != nil {
return err
}
log.Debug("recv handShake Info")
// scan once to get server info
if !ic.scanner.Scan() {
return ic.scanner.Err()
}
// Init server info
msgBytes = ic.scanner.Bytes()
serverInfo := splitMsgBytes(msgBytes)
v, _ := strconv.Atoi(string(serverInfo[0]))
ic.serverVersion = Version(v)
ic.connTime = string(serverInfo[1])
// Init Decoder
ic.decoder.setVersion(ic.serverVersion)
// ic.decoder.errChan = make(chan error, 100)
ic.decoder.setmsgID2process()
log.Info("handShake info", zap.Int("serverVersion", ic.serverVersion))
log.Info("handShake info", zap.String("connectionTime", ic.connTime))
// send startAPI to tell server that client is ready
if err := ic.startAPI(); err != nil {
return err
}
go ic.goReceive() // receive the data, make sure client receives the nextValidID and manageAccount which help comfirm the client.
comfirmMsgIDs := []IN{mNEXT_VALID_ID, mMANAGED_ACCTS}
/* comfirmReadyLoop try to receive manage account and vaild id from tws or gateway,
in this way, client could make sure no other client with the same clientId was already connected to tws or gateway.
*/
timeout := time.After(60 * time.Second)
comfirmReadyLoop:
for {
select {
case m := <-ic.msgChan:
f := splitMsgBytes(m)
MsgID, _ := strconv.ParseInt(string(f[0]), 10, 64)
ic.decoder.interpret(m)
// check and del the msg ID
for i, ID := range comfirmMsgIDs {
if MsgID == ID {
comfirmMsgIDs = append(comfirmMsgIDs[:i], comfirmMsgIDs[i+1:]...)
break
}
}
// if all are checked, connect ack
if len(comfirmMsgIDs) == 0 {
ic.setConnState(CONNECTED)
ic.wrapper.ConnectAck()
break comfirmReadyLoop
}
case <-timeout:
ic.setConnState(DISCONNECTED)
ic.wrapper.Error(NO_VALID_ID, ALREADY_CONNECTED.code, ALREADY_CONNECTED.msg)
return ALREADY_CONNECTED
case <-ic.ctx.Done():
ic.setConnState(DISCONNECTED)
ic.wrapper.Error(NO_VALID_ID, ALREADY_CONNECTED.code, ALREADY_CONNECTED.msg)
return ALREADY_CONNECTED
}
}
log.Info("HandShake completed")
return nil
}
// ServerVersion is the tws or gateway version returned by the API
func (ic *IbClient) ServerVersion() Version {
return ic.serverVersion
}
// ConnectionTime is the time that connection is comfirmed
func (ic *IbClient) ConnectionTime() string {
return ic.connTime
}
func (ic *IbClient) reset() {
log.Debug("reset ibClient")
ic.reqIDSeq = 0
ic.conn = &IbConnection{}
ic.host = ""
ic.port = -1
ic.extraAuth = false
ic.clientID = -1
ic.serverVersion = -1
ic.connTime = ""
// init scanner
ic.scanner = bufio.NewScanner(ic.conn)
ic.scanner.Split(scanFields)
ic.scanner.Buffer(make([]byte, 4096), MAX_MSG_LEN)
ic.writer = bufio.NewWriter(ic.conn)
ic.reqChan = make(chan []byte, 10)
ic.errChan = make(chan error, 10)
ic.msgChan = make(chan []byte, 100)
ic.terminatedSignal = make(chan int)
ic.wg = sync.WaitGroup{}
ic.connectOptions = ""
ic.setConnState(DISCONNECTED)
ic.err = nil
if ic.ctx == nil {
ic.ctx = context.TODO()
}
}
// SetServerLogLevel setup the log level of server
func (ic *IbClient) SetServerLogLevel(logLevel int64) {
// v := 1
const v = 1
fields := make([]interface{}, 0, 3)
fields = append(fields,
mSET_SERVER_LOGLEVEL,
v,
logLevel,
)
msg := makeMsgBytes(fields...)
ic.reqChan <- msg
}
// ---------------req func ----------------------------------------------
/*
Market Data
*/
// ReqMktData Call this function to request market data.
// The market data will be returned by the tickPrice and tickSize events.
/*
@param 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.
@param contract:
This structure contains a description of the Contractt for which market data is being requested.
@param genericTickList:
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"
@param snapshot:
Check 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.
@param regulatorySnapshot:
With the US Value Snapshot Bundle for stocks, regulatory snapshots are available for 0.01 USD each.
@param mktDataOptions:
For internal use only.Use default value XYZ.
*/
func (ic *IbClient) ReqMktData(reqID int64, contract *Contract, genericTickList string, snapshot bool, regulatorySnapshot bool, mktDataOptions []TagValue) {
switch {
case ic.serverVersion < mMIN_SERVER_VER_DELTA_NEUTRAL && contract.DeltaNeutralContract != nil:
ic.wrapper.Error(reqID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support delta-neutral orders.")
return
case ic.serverVersion < mMIN_SERVER_VER_REQ_MKT_DATA_CONID && contract.ContractID > 0:
ic.wrapper.Error(reqID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support conId parameter.")
return
case ic.serverVersion < mMIN_SERVER_VER_TRADING_CLASS && contract.TradingClass != "":
ic.wrapper.Error(reqID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support tradingClass parameter in reqMktData.")
return
}
// v := 11
const v = 11
fields := make([]interface{}, 0, 30)
fields = append(fields,
mREQ_MKT_DATA,
v,
reqID,
)
if ic.serverVersion >= mMIN_SERVER_VER_REQ_MKT_DATA_CONID {
fields = append(fields, contract.ContractID)
}
fields = append(fields,
contract.Symbol,
contract.SecurityType,
contract.Expiry,
contract.Strike,
contract.Right,
contract.Multiplier,
contract.Exchange,
contract.PrimaryExchange,
contract.Currency,
contract.LocalSymbol)
if ic.serverVersion >= mMIN_SERVER_VER_TRADING_CLASS {
fields = append(fields, contract.TradingClass)
}
if contract.SecurityType == "BAG" {
comboLegsCount := len(contract.ComboLegs)
fields = append(fields, comboLegsCount)
for _, comboLeg := range contract.ComboLegs {
fields = append(fields,
comboLeg.ContractID,
comboLeg.Ratio,
comboLeg.Action,
comboLeg.Exchange)
}
}
if ic.serverVersion >= mMIN_SERVER_VER_DELTA_NEUTRAL {
if contract.DeltaNeutralContract != nil {
fields = append(fields,
true,
contract.DeltaNeutralContract.ContractID,
contract.DeltaNeutralContract.Delta,
contract.DeltaNeutralContract.Price)
} else {
fields = append(fields, false)
}
}
fields = append(fields,
genericTickList,
snapshot)
if ic.serverVersion >= mMIN_SERVER_VER_REQ_SMART_COMPONENTS {
fields = append(fields, regulatorySnapshot)
}
if ic.serverVersion >= mMIN_SERVER_VER_LINKING {
if len(mktDataOptions) > 0 {
log.Panic("not supported")
}
fields = append(fields, "")
}
msg := makeMsgBytes(fields...)
ic.reqChan <- msg
}
// CancelMktData cancels the market data
func (ic *IbClient) CancelMktData(reqID int64) {
// v := 2
const v = 2
fields := make([]interface{}, 0, 3)
fields = append(fields,
mCANCEL_MKT_DATA,
v,
reqID,
)
msg := makeMsgBytes(fields...)
ic.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.
@param marketDataType:
1 -> realtime streaming market data
2 -> frozen market data
3 -> delayed market data
4 -> delayed frozen market data
*/
func (ic *IbClient) ReqMarketDataType(marketDataType int64) {
if ic.serverVersion < mMIN_SERVER_VER_REQ_MARKET_DATA_TYPE {
ic.wrapper.Error(NO_VALID_ID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support market data type requests.")
return
}
// v := 1
const v = 1
fields := make([]interface{}, 0, 3)
fields = append(fields, mREQ_MARKET_DATA_TYPE, v, marketDataType)
msg := makeMsgBytes(fields...)
ic.reqChan <- msg
}
// ReqSmartComponents request the smartComponents.
func (ic *IbClient) ReqSmartComponents(reqID int64, bboExchange string) {
if ic.serverVersion < mMIN_SERVER_VER_REQ_SMART_COMPONENTS {
ic.wrapper.Error(NO_VALID_ID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support smart components request.")
return
}
msg := makeMsgBytes(mREQ_SMART_COMPONENTS, reqID, bboExchange)
ic.reqChan <- msg
}
// ReqMarketRule request the market rule.
func (ic *IbClient) ReqMarketRule(marketRuleID int64) {
if ic.serverVersion < mMIN_SERVER_VER_MARKET_RULES {
ic.wrapper.Error(NO_VALID_ID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support market rule requests.")
return
}
msg := makeMsgBytes(mREQ_MARKET_RULE, marketRuleID)
ic.reqChan <- msg
}
// ReqTickByTickData request the tick-by-tick data.
/*
Call this func to requst tick-by-tick data.Result will be delivered
via wrapper.TickByTickAllLast() wrapper.TickByTickBidAsk() wrapper.TickByTickMidPoint()
*/
func (ic *IbClient) ReqTickByTickData(reqID int64, contract *Contract, tickType string, numberOfTicks int64, ignoreSize bool) {
if ic.serverVersion < mMIN_SERVER_VER_TICK_BY_TICK {
ic.wrapper.Error(NO_VALID_ID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support tick-by-tick data requests.")
return
}
if ic.serverVersion < mMIN_SERVER_VER_TICK_BY_TICK_IGNORE_SIZE {
ic.wrapper.Error(NO_VALID_ID, 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, 16)
fields = append(fields, mREQ_TICK_BY_TICK_DATA,
reqID,
contract.ContractID,
contract.Symbol,
contract.SecurityType,
contract.Expiry,
contract.Strike,
contract.Right,
contract.Multiplier,
contract.Exchange,
contract.PrimaryExchange,
contract.Currency,
contract.LocalSymbol,
contract.TradingClass,
tickType)
if ic.serverVersion >= mMIN_SERVER_VER_TICK_BY_TICK_IGNORE_SIZE {
fields = append(fields, numberOfTicks, ignoreSize)
}
msg := makeMsgBytes(fields...)
ic.reqChan <- msg
}
// CancelTickByTickData cancel the tick-by-tick data
func (ic *IbClient) CancelTickByTickData(reqID int64) {
if ic.serverVersion < mMIN_SERVER_VER_TICK_BY_TICK {
ic.wrapper.Error(NO_VALID_ID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support tick-by-tick data requests.")
return
}
msg := makeMsgBytes(mCANCEL_TICK_BY_TICK_DATA, reqID)
ic.reqChan <- msg
}
/*
##########################################################################
################## Options
##########################################################################
*/
//CalculateImpliedVolatility calculate the volatility of the option
/*
Call this function to calculate volatility for a supplied
option price and underlying price. Result will be delivered
via wrapper.TickOptionComputation()
@param reqId:
The request id.
@param contract:
Describes the contract.
@param optionPrice:
The price of the option.
@param underPrice:
Price of the underlying.
*/
func (ic *IbClient) CalculateImpliedVolatility(reqID int64, contract *Contract, optionPrice float64, underPrice float64, impVolOptions []TagValue) {
if ic.serverVersion < mMIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT {
ic.wrapper.Error(NO_VALID_ID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support calculateImpliedVolatility req.")
return
}
if ic.serverVersion < mMIN_SERVER_VER_TRADING_CLASS && contract.TradingClass != "" {
ic.wrapper.Error(NO_VALID_ID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support tradingClass parameter in calculateImpliedVolatility.")
return
}
// v := 3
const v = 3
fields := make([]interface{}, 0, 19)
fields = append(fields,
mREQ_CALC_IMPLIED_VOLAT,
v,
reqID,
contract.ContractID,
contract.Symbol,
contract.SecurityID,
contract.Expiry,
contract.Strike,
contract.Right,
contract.Multiplier,
contract.Exchange,
contract.PrimaryExchange,
contract.Currency,
contract.LocalSymbol)
if ic.serverVersion >= mMIN_SERVER_VER_TRADING_CLASS {
fields = append(fields, contract.TradingClass)
}
fields = append(fields, optionPrice, underPrice)
if ic.serverVersion >= mMIN_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 := makeMsgBytes(fields...)
ic.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()
@param reqId:
The request id.
@param contract:
Describes the contract.
@param volatility:
The volatility of the option.
@param underPrice:
Price of the underlying.
*/
func (ic *IbClient) CalculateOptionPrice(reqID int64, contract *Contract, volatility float64, underPrice float64, optPrcOptions []TagValue) {
if ic.serverVersion < mMIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT {
ic.wrapper.Error(reqID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support calculateImpliedVolatility req.")
return
}
if ic.serverVersion < mMIN_SERVER_VER_TRADING_CLASS {
ic.wrapper.Error(reqID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support tradingClass parameter in calculateImpliedVolatility.")
return
}
// v := 3
const v = 3
fields := make([]interface{}, 0, 19)
fields = append(fields,
mREQ_CALC_OPTION_PRICE,
v,
reqID,
contract.ContractID,
contract.Symbol,
contract.SecurityID,
contract.Expiry,
contract.Strike,
contract.Right,
contract.Multiplier,
contract.Exchange,
contract.PrimaryExchange,
contract.Currency,
contract.LocalSymbol)
if ic.serverVersion >= mMIN_SERVER_VER_TRADING_CLASS {
fields = append(fields, contract.TradingClass)
}
fields = append(fields, volatility, underPrice)
if ic.serverVersion >= mMIN_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 := makeMsgBytes(fields...)
ic.reqChan <- msg
}
// CancelCalculateOptionPrice cancels the calculation of option price
func (ic *IbClient) CancelCalculateOptionPrice(reqID int64) {
if ic.serverVersion < mMIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT {
ic.wrapper.Error(reqID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support calculateImpliedVolatility req.")
return
}
// v := 1
const v = 1
msg := makeMsgBytes(mCANCEL_CALC_OPTION_PRICE, v, reqID)
ic.reqChan <- msg
}
// ExerciseOptions exercise the options.
/*
call this func to exercise th options.
@param reqId:
The ticker id must be a unique value.
@param contract:
This structure contains a description of the contract to be exercised
@param exerciseAction:
Specifies whether you want the option to lapse or be exercised.
Values: 1 = exercise, 2 = lapse.
@param exerciseQuantity:
The quantity you want to exercise.
@param account:
destination account
@param 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.
*/
func (ic *IbClient) ExerciseOptions(reqID int64, contract *Contract, exerciseAction int, exerciseQuantity int, account string, override int) {
if ic.serverVersion < mMIN_SERVER_VER_TRADING_CLASS && contract.TradingClass != "" {
ic.wrapper.Error(NO_VALID_ID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support conId, multiplier, tradingClass parameter in exerciseOptions.")
return
}
// v := 2
const v = 2
fields := make([]interface{}, 0, 17)
fields = append(fields, mEXERCISE_OPTIONS, v, reqID)
if ic.serverVersion >= mMIN_SERVER_VER_TRADING_CLASS {
fields = append(fields, contract.ContractID)
}
fields = append(fields,
contract.Symbol,
contract.Expiry,
contract.Strike,
contract.Right,
contract.Multiplier,
contract.Exchange,
contract.Currency,
contract.LocalSymbol)
if ic.serverVersion >= mMIN_SERVER_VER_TRADING_CLASS {
fields = append(fields, contract.TradingClass)
}
fields = append(fields,
exerciseAction,
exerciseQuantity,
account,
override)
msg := makeMsgBytes(fields...)
ic.reqChan <- msg
}
/*
#########################################################################
################## Orders
########################################################################
*/
//PlaceOrder place an order to tws or gateway
/*
Call this function to place an order. The order status will be returned by the orderStatus event.
@param orderId:
The order id.
You must specify a unique value. When the order START_APItus returns,
it will be identified by this tag.This tag is also used when canceling the order.
@param contract:
This structure contains a description of the contract which is being traded.
@param order:
This structure contains the details of tradedhe order.
*/
func (ic *IbClient) PlaceOrder(orderID int64, contract *Contract, order *Order) {
switch v := ic.serverVersion; {
case v < mMIN_SERVER_VER_DELTA_NEUTRAL && contract.DeltaNeutralContract != nil:
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support delta-neutral orders.")
return
case v < mMIN_SERVER_VER_SCALE_ORDERS2 && order.ScaleSubsLevelSize != UNSETINT:
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support Subsequent Level Size for Scale orders.")
return
case v < mMIN_SERVER_VER_ALGO_ORDERS && order.AlgoStrategy != "":
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support algo orders.")
return
case v < mMIN_SERVER_VER_NOT_HELD && order.NotHeld:
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support notHeld parameter.")
return
case v < mMIN_SERVER_VER_SEC_ID_TYPE && (contract.SecurityType != "" || contract.SecurityID != ""):
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support secIdType and secId parameters.")
return
case v < mMIN_SERVER_VER_PLACE_ORDER_CONID && contract.ContractID != UNSETINT && contract.ContractID > 0:
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support conId parameter.")
return
case v < mMIN_SERVER_VER_SSHORTX && order.ExemptCode != -1:
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support exemptCode parameter.")
return
case v < mMIN_SERVER_VER_SSHORTX:
for _, comboLeg := range contract.ComboLegs {
if comboLeg.ExemptCode != -1 {
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support exemptCode parameter.")
return
}
}
fallthrough
case v < mMIN_SERVER_VER_HEDGE_ORDERS && order.HedgeType != "":
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support hedge orders.")
return
case v < mMIN_SERVER_VER_OPT_OUT_SMART_ROUTING && order.OptOutSmartRouting:
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support optOutSmartRouting parameter.")
return
case v < mMIN_SERVER_VER_DELTA_NEUTRAL_CONID:
if order.DeltaNeutralContractID > 0 || order.DeltaNeutralSettlingFirm != "" || order.DeltaNeutralClearingAccount != "" || order.DeltaNeutralClearingIntent != "" {
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support deltaNeutral parameters: ConId, SettlingFirm, ClearingAccount, ClearingIntent.")
return
}
fallthrough
case v < mMIN_SERVER_VER_DELTA_NEUTRAL_OPEN_CLOSE:
if order.DeltaNeutralOpenClose != "" ||
order.DeltaNeutralShortSale ||
order.DeltaNeutralShortSaleSlot > 0 ||
order.DeltaNeutralDesignatedLocation != "" {
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support deltaNeutral parameters: OpenClose, ShortSale, ShortSaleSlot, DesignatedLocation.")
return
}
fallthrough
case v < mMIN_SERVER_VER_SCALE_ORDERS3:
if (order.ScalePriceIncrement > 0 && order.ScalePriceIncrement != UNSETFLOAT) &&
(order.ScalePriceAdjustValue != UNSETFLOAT ||
order.ScalePriceAdjustInterval != UNSETINT ||
order.ScaleProfitOffset != UNSETFLOAT ||
order.ScaleAutoReset ||
order.ScaleInitPosition != UNSETINT ||
order.ScaleInitFillQty != UNSETINT ||
order.ScaleRandomPercent) {
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+
" It does not support Scale order parameters: PriceAdjustValue, PriceAdjustInterval, "+
"ProfitOffset, AutoReset, InitPosition, InitFillQty and RandomPercent.")
return
}
fallthrough
case v < mMIN_SERVER_VER_ORDER_COMBO_LEGS_PRICE && contract.SecurityType == "BAG":
for _, orderComboLeg := range order.OrderComboLegs {
if orderComboLeg.Price != UNSETFLOAT {
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support per-leg prices for order combo legs.")
return
}
}
fallthrough
case v < mMIN_SERVER_VER_TRAILING_PERCENT && order.TrailingPercent != UNSETFLOAT:
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support trailing percent parameter.")
return
case v < mMIN_SERVER_VER_TRADING_CLASS && contract.TradingClass != "":
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support tradingClass parameter in placeOrder.")
return
case v < mMIN_SERVER_VER_SCALE_TABLE &&
(order.ScaleTable != "" ||
order.ActiveStartTime != "" ||
order.ActiveStopTime != ""):
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support scaleTable, activeStartTime and activeStopTime parameters.")
return
case v < mMIN_SERVER_VER_ALGO_ID && order.AlgoID != "":
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support algoId parameter.")
return
case v < mMIN_SERVER_VER_ORDER_SOLICITED && order.Solictied:
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support order solicited parameter.")
return
case v < mMIN_SERVER_VER_MODELS_SUPPORT && order.ModelCode != "":
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support model code parameter.")
return
case v < mMIN_SERVER_VER_EXT_OPERATOR && order.ExtOperator != "":
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support ext operator parameter")
return
case v < mMIN_SERVER_VER_SOFT_DOLLAR_TIER &&
(order.SoftDollarTier.Name != "" || order.SoftDollarTier.Value != ""):
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support soft dollar tier")
return
case v < mMIN_SERVER_VER_CASH_QTY && order.CashQty != UNSETFLOAT:
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support cash quantity parameter")
return
case v < mMIN_SERVER_VER_DECISION_MAKER &&
(order.Mifid2DecisionMaker != "" || order.Mifid2DecisionAlgo != ""):
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support MIFID II decision maker parameters")
return
case v < mMIN_SERVER_VER_MIFID_EXECUTION &&
(order.Mifid2ExecutionTrader != "" || order.Mifid2ExecutionAlgo != ""):
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support MIFID II execution parameters")
return
case v < mMIN_SERVER_VER_AUTO_PRICE_FOR_HEDGE && order.DontUseAutoPriceForHedge:
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support dontUseAutoPriceForHedge parameter")
return
case v < mMIN_SERVER_VER_ORDER_CONTAINER && order.IsOmsContainer:
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support oms container parameter")
return
case v < mMIN_SERVER_VER_PRICE_MGMT_ALGO && order.UsePriceMgmtAlgo:
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support Use price management algo requests")
return
case v < mMIN_SERVER_VER_DURATION && order.Duration != UNSETINT:
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support duration attribute")
case v < mMIN_SERVER_VER_POST_TO_ATS && order.PostToAts != UNSETINT:
ic.wrapper.Error(orderID, UPDATE_TWS.code, UPDATE_TWS.msg+" It does not support postToAts attribute")
}
var v int
if ic.serverVersion < mMIN_SERVER_VER_NOT_HELD {
v = 27
} else {
v = 45
}
fields := make([]interface{}, 0, 150)
fields = append(fields, mPLACE_ORDER)
if ic.serverVersion < mMIN_SERVER_VER_ORDER_CONTAINER {
fields = append(fields, v)
}
fields = append(fields, orderID)
if ic.serverVersion >= mMIN_SERVER_VER_PLACE_ORDER_CONID {
fields = append(fields, contract.ContractID)
}
fields = append(fields,
contract.Symbol,
contract.SecurityType,
contract.Expiry,
contract.Strike,
contract.Right,
contract.Multiplier,
contract.Exchange,
contract.PrimaryExchange,
contract.Currency,
contract.LocalSymbol)
if ic.serverVersion >= mMIN_SERVER_VER_TRADING_CLASS {
fields = append(fields, contract.TradingClass)
}
if ic.serverVersion >= mMIN_SERVER_VER_SEC_ID_TYPE {
fields = append(fields, contract.SecurityIDType, contract.SecurityID)
}
fields = append(fields, order.Action)
if ic.serverVersion >= mMIN_SERVER_VER_FRACTIONAL_POSITIONS {
fields = append(fields, order.TotalQuantity)
} else {
fields = append(fields, int64(order.TotalQuantity))
}
fields = append(fields, order.OrderType)
if ic.serverVersion < mMIN_SERVER_VER_ORDER_COMBO_LEGS_PRICE {
if order.LimitPrice != UNSETFLOAT {
fields = append(fields, order.LimitPrice)
} else {
fields = append(fields, float64(0))