-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathclient.go
More file actions
6399 lines (4856 loc) · 183 KB
/
client.go
File metadata and controls
6399 lines (4856 loc) · 183 KB
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"
"errors"
"fmt"
"os"
"os/signal"
"strconv"
"sync"
"sync/atomic"
"syscall"
"github.com/scmhub/ibapi/protobuf"
"google.golang.org/protobuf/proto"
)
type ConnState int
const (
DISCONNECTED ConnState = iota
CONNECTING
CONNECTED
)
func (cs ConnState) String() string {
switch cs {
case DISCONNECTED:
return "disconnected"
case CONNECTING:
return "connecting"
case CONNECTED:
return "connected"
default:
return "unknown connection state"
}
}
// MsgEncoder efficiently encodes messages for IB API
type MsgEncoder struct {
buf bytes.Buffer
eClient *EClient
}
// NewMsgEncoder creates a new MsgEncoder with an initial number of fields and server version
func NewMsgEncoder(nFields int, eClient *EClient) *MsgEncoder {
me := &MsgEncoder{
eClient: eClient,
}
me.buf.Grow(8*nFields + 4)
// Reserve 4 bytes for the message size header
me.buf.Write([]byte{0, 0, 0, 0})
return me
}
// encodeMsgID encodes a message ID with appropriate format based on server version
func (me *MsgEncoder) encodeMsgID(msgID int64) *MsgEncoder {
if me.eClient.serverVersion >= MIN_SERVER_VER_PROTOBUF {
// Encode as raw int (4 bytes, byte-swapped)
me.encodeRawInt64(msgID)
} else {
// Encode as a regular field (string + delimiter)
me.encodeInt64(msgID)
}
return me
}
// encodeField encodes a value of any supported type
func (me *MsgEncoder) encodeField(v any) *MsgEncoder {
switch val := v.(type) {
case int:
return me.encodeInt(val)
case int64:
return me.encodeInt64(val)
case float64:
return me.encodeFloat64(val)
case string:
return me.encodeString(val)
case bool:
return me.encodeBool(val)
case []byte:
return me.encodeBytes(val)
case Decimal:
return me.encodeDecimal(val)
default:
// Convert to string as fallback
return me.encodeString(fmt.Sprintf("%v", val))
}
}
// encodeFileds encode many fields
func (me *MsgEncoder) encodeFields(v ...any) *MsgEncoder {
for _, f := range v {
me.encodeField(f)
}
return me
}
// encodeMax encodes a value that might be UNSET
func (me *MsgEncoder) encodeMax(v any) *MsgEncoder {
switch val := v.(type) {
case int64:
return me.encodeIntMax(val)
case float64:
return me.encodeFloatMax(val)
// case Decimal:
// return me.encodeDecimalMax(val)
default:
return me.encodeField(v)
}
}
// encodeInt adds an int value to the message
func (me *MsgEncoder) encodeInt(v int) *MsgEncoder {
me.buf.WriteString(strconv.Itoa(v))
me.buf.WriteByte(delim)
return me
}
// encodeInt64 adds an int64 value to the message
func (me *MsgEncoder) encodeInt64(v int64) *MsgEncoder {
me.buf.WriteString(strconv.FormatInt(v, 10))
me.buf.WriteByte(delim)
return me
}
// encodeInt64 adds a raw int64 value to the message
func (me *MsgEncoder) encodeRawInt64(v int64) *MsgEncoder {
var arrayOfBytes [RAW_INT_LEN]byte
binary.BigEndian.PutUint32(arrayOfBytes[:], uint32(v))
me.buf.Write(arrayOfBytes[:])
return me
}
// encodeFloat64 adds a float64 value to the message
func (me *MsgEncoder) encodeFloat64(v float64) *MsgEncoder {
me.buf.WriteString(strconv.FormatFloat(v, 'f', -1, 64))
me.buf.WriteByte(delim)
return me
}
// encodeString adds a string value to the message
func (me *MsgEncoder) encodeString(v string) *MsgEncoder {
me.buf.WriteString(v)
me.buf.WriteByte(delim)
return me
}
// encodeBool adds a boolean value to the message
func (me *MsgEncoder) encodeBool(v bool) *MsgEncoder {
if v {
me.buf.WriteByte('1')
} else {
me.buf.WriteByte('0')
}
me.buf.WriteByte(delim)
return me
}
// encodeBytes adds raw bytes to the message
func (me *MsgEncoder) encodeBytes(v []byte) *MsgEncoder {
me.buf.Write(v)
me.buf.WriteByte(delim)
return me
}
// encodeBytes adds raw bytes to the message
func (me *MsgEncoder) encodeProto(v []byte) *MsgEncoder {
me.buf.Write(v)
return me
}
// encodeDecimal adds a Decimal value to the message
func (me *MsgEncoder) encodeDecimal(v Decimal) *MsgEncoder {
me.buf.WriteString(DecimalToString(v))
me.buf.WriteByte(delim)
return me
}
// encodeTagValues adds a slice of TagValue to the message
func (me *MsgEncoder) encodeTagValues(v []TagValue) *MsgEncoder {
for _, tv := range v {
me.buf.WriteString(tv.Tag)
me.buf.WriteString("=")
me.buf.WriteString(tv.Value)
me.buf.WriteString(";")
}
me.buf.WriteByte(delim)
return me
}
func (me *MsgEncoder) encodeContract(v *Contract) *MsgEncoder {
me.encodeInt64(v.ConID)
me.encodeString(v.Symbol)
me.encodeString(v.SecType)
me.encodeString(v.LastTradeDateOrContractMonth)
me.encodeFloatMax(v.Strike)
me.encodeString(v.Right)
me.encodeString(v.Multiplier)
me.encodeString(v.Exchange)
me.encodeString(v.PrimaryExchange)
me.encodeString(v.Currency)
me.encodeString(v.LocalSymbol)
me.encodeString(v.TradingClass)
me.encodeBool(v.IncludeExpired)
return me
}
// encodeIntMax adds an int64 value to the message, handling UNSET_INT
func (me *MsgEncoder) encodeIntMax(v int64) *MsgEncoder {
if v == UNSET_INT {
me.buf.WriteByte(delim)
return me
}
return me.encodeInt64(v)
}
// encodeFloatMax adds a float64 value to the message, handling UNSET_FLOAT
func (me *MsgEncoder) encodeFloatMax(v float64) *MsgEncoder {
if v == UNSET_FLOAT {
me.buf.WriteByte(delim)
return me
}
return me.encodeFloat64(v)
}
// // encodeDecimalMax adds a Decimal value to the message, handling UNSET_DECIMAL
// func (me *MsgEncoder) encodeDecimalMax(v Decimal) *MsgEncoder {
// if v == UNSET_DECIMAL {
// me.buf.WriteByte(delim)
// return me
// }
// return me.encodeDecimal(v)
// }
// Bytes finalizes the message by writing the size header and returning the complete message
func (me *MsgEncoder) Bytes() []byte {
// Get the final buffer bytes
result := me.buf.Bytes()
// Calculate message size (excluding the 4-byte header)
msgSize := len(result) - 4
if msgSize > MAX_MSG_LEN {
log.Error().Int("msgSize", msgSize).Msg("Message size exceeds maximum allowed size")
me.eClient.wrapper.Error(NO_VALID_ID, currentTimeMillis(), BAD_LENGTH.Code, BAD_LENGTH.Msg, "")
return nil
}
// Write the size back into the header
binary.BigEndian.PutUint32(result[:4], uint32(msgSize))
return result
}
// Reset resets the buffer for reuse while maintaining its capacity
func (me *MsgEncoder) Reset() {
me.buf.Reset()
// Reserve 4 bytes for the message size header
me.buf.Write([]byte{0, 0, 0, 0})
}
// 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
optionalCapabilities string
conn *Connection
serverVersion Version
connTime string
connState int32
writer *bufio.Writer
scanner *bufio.Scanner
wrapper EWrapper
decoder *EDecoder
reqChan chan []byte
ctx context.Context
cancel context.CancelFunc
extraAuth bool
wg sync.WaitGroup
watchOnce sync.Once
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.connectOptions = ""
c.optionalCapabilities = ""
c.extraAuth = false
c.conn = &Connection{wrapper: c.wrapper}
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.watchOnce = sync.Once{}
c.setConnState(DISCONNECTED)
c.connectOptions = ""
}
func (c *EClient) setConnState(state ConnState) {
cs := ConnState(atomic.LoadInt32(&c.connState))
atomic.StoreInt32(&c.connState, int32(state))
log.Debug().Stringer("from", cs).Stringer("to", state).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:
log.Trace().Bytes("req", req).Msg("sending request")
if !c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
c.cancel()
return
}
nn, err := c.writer.Write(req)
if err != nil {
log.Error().Err(err).Int("nbytes", nn).Bytes("reqMsg", req).Msg("requester write error")
// Disconnect the client
log.Info().Msg("Disconnecting client due to write error.")
if disconnectErr := c.Disconnect(); disconnectErr != nil {
log.Error().Err(disconnectErr).Msg("Error during disconnect.")
}
c.cancel()
return
}
err = c.writer.Flush()
if err != nil {
log.Error().Err(err).Bytes("reqMsg", req).Msg("requester flush error")
c.cancel()
return
}
}
}
}
func (c *EClient) validateInvalidSymbols(host string) error {
if host != "" && !isASCIIPrintable(host) {
return errors.New(host)
}
if c.connectOptions != "" && !isASCIIPrintable(c.connectOptions) {
return errors.New(c.connectOptions)
}
if c.optionalCapabilities != "" && !isASCIIPrintable(c.optionalCapabilities) {
return errors.New(c.optionalCapabilities)
}
return nil
}
func (c *EClient) useProtoBuf(msgID int64) bool {
if version, exists := PROTOBUF_MSG_IDS[OUT(msgID)]; exists {
return version <= c.serverVersion
}
return false
}
// startAPI initiates the message exchange between the client application and the TWS/IB Gateway.
func (c *EClient) startAPI() error {
if c.useProtoBuf(START_API) {
return c.startApiProtoBuf(createStartApiRequestProto(c.clientID, c.optionalCapabilities))
}
if !c.conn.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return NOT_CONNECTED
}
const VERSION = 2
msg := makeField(VERSION) + makeField(c.clientID)
if c.serverVersion >= MIN_SERVER_VER_OPTIONAL_CAPABILITIES {
msg += makeField(c.optionalCapabilities)
}
var payload []byte
if c.serverVersion >= MIN_SERVER_VER_PROTOBUF {
idBytes := make([]byte, 4)
binary.BigEndian.PutUint32(idBytes, uint32(START_API))
payload = append(idBytes, []byte(msg)...)
} else {
payload = []byte(makeField(START_API) + msg)
}
msgLen := uint32(len(payload))
bs := make([]byte, 4+len(payload))
binary.BigEndian.PutUint32(bs[:4], msgLen)
copy(bs[4:], payload)
log.Debug().Bytes("req", bs).Msg("sending startAPI")
if _, err := c.writer.Write(bs); err != nil {
return err
}
if err := c.writer.Flush(); err != nil {
return err
}
return nil
}
func (c *EClient) startApiProtoBuf(startApiRequestProto *protobuf.StartApiRequest) error {
if !c.conn.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return NOT_CONNECTED
}
me := NewMsgEncoder(4, c)
me.encodeMsgID(START_API + PROTOBUF_MSG_ID)
msg, err := proto.Marshal(startApiRequestProto)
if err != nil {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), ERROR_ENCODING_PROTOBUF.Code, ERROR_ENCODING_PROTOBUF.Msg+err.Error(), "")
return err
}
me.encodeProto(msg)
payload := me.Bytes()
if payload == nil {
return fmt.Errorf("failed to encode START_API protobuf payload")
}
if _, err := c.writer.Write(payload); err != nil {
return err
}
return c.writer.Flush()
}
// 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.".
// You should wait for the connection to be established and NextValidID to be returned before calling any other function. If you don't wait, you will get a broken pipe error.
func (c *EClient) Connect(host string, port int, clientID int64) error {
if c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), ALREADY_CONNECTED.Code, ALREADY_CONNECTED.Msg, "")
return ALREADY_CONNECTED
}
if err := c.validateInvalidSymbols(host); err != nil {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), INVALID_SYMBOL.Code, INVALID_SYMBOL.Msg+err.Error(), "")
return err
}
c.host = host
c.port = port
c.clientID = clientID
c.setConnState(CONNECTING)
// Connecting to IB server
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 := fmt.Appendf(nil, "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("Sending 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("Receiving 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)
if c.serverVersion < MIN_SERVER_VER_SUPPORTED {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), UNSUPPORTED_VERSION.Code, UNSUPPORTED_VERSION.Msg, "")
return UNSUPPORTED_VERSION
}
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.cancel, c.scanner, c.decoder, &c.wg)
// start requester
go c.request()
// startAPI
if err := c.startAPI(); err != nil {
return err
}
c.setConnState(CONNECTED)
c.wrapper.ConnectAck()
// 4) Launch the shutdown watcher exactly once
c.watchOnce.Do(func() {
go func() {
<-c.ctx.Done() // waits for c.cancel()
if err := c.Disconnect(); err != nil {
log.Error().Err(err).Msg("Disconnect error in watcher")
}
}()
})
log.Debug().Msg("IB Client Connected!")
return nil
}
// ConnectWithGracefulShutdown connects and sets up signal handling for graceful shutdown.
// This is a convenience for simple apps. Advanced users should handle signals themselves.
func (c *EClient) ConnectWithGracefulShutdown(host string, port int, clientID int64) error {
err := c.Connect(host, port, clientID)
if err != nil {
return err
}
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigChan
log.Warn().Msg("detected termination signal, shutting down gracefully")
c.Disconnect()
os.Exit(0)
}()
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
}
// Set Disconnected state realy so that new calls to Disconnect() will not block
c.setConnState(DISCONNECTED)
// 1) Cancel to unblock request Loop
c.cancel()
// 2) Close the socket to unblock reader loop
if err := c.conn.disconnect(); err != nil {
return err
}
// 3) Wait for loops to exit
c.wg.Wait()
// 4) Reset internal state
c.reset()
c.wrapper.ConnectionClosed()
log.Debug().Msg("IB Client Disconnected!")
return nil
}
func (c *EClient) Ctx() context.Context {
return c.ctx
}
// IsConnected checks connection to TWS or GateWay.
func (c *EClient) IsConnected() bool {
return c.conn.IsConnected() && ConnState(atomic.LoadInt32(&c.connState)) == CONNECTED
}
// OptionalCapabilities returns the Optional Capabilities.
func (c *EClient) OptionalCapabilities() string {
return c.optionalCapabilities
}
// SetOptionalCapabilities setup the Optional Capabilities.
func (c *EClient) SetOptionalCapabilities(optCapts string) {
c.optionalCapabilities = optCapts
}
// SetConnectionOptions setup the Connection Options.
func (c *EClient) SetConnectionOptions(connectOptions string) {
if c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), ALREADY_CONNECTED.Code, ALREADY_CONNECTED.Msg, "")
return
}
c.connectOptions = connectOptions
}
// ReqCurrentTime asks the current system time on the server side.
func (c *EClient) ReqCurrentTime() {
if c.useProtoBuf(REQ_CURRENT_TIME) {
c.reqCurrentTimeProtoBuf(createCurrentTimeRequestProto())
return
}
if !c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
const VERSION = 1
me := NewMsgEncoder(2, c)
me.encodeMsgID(REQ_CURRENT_TIME).encodeInt(VERSION)
c.reqChan <- me.Bytes()
}
func (c *EClient) reqCurrentTimeProtoBuf(currentTimeRequestProto *protobuf.CurrentTimeRequest) {
if !c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
me := NewMsgEncoder(2, c)
me.encodeMsgID(REQ_CURRENT_TIME + PROTOBUF_MSG_ID)
msg, err := proto.Marshal(currentTimeRequestProto)
if err != nil {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), ERROR_ENCODING_PROTOBUF.Code, ERROR_ENCODING_PROTOBUF.Msg+err.Error(), "")
return
}
me.encodeProto(msg)
c.reqChan <- me.Bytes()
}
// 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.useProtoBuf(SET_SERVER_LOGLEVEL) {
c.setServerLogLevelProtoBuf(createSetServerLogLevelRequestProto(logLevel))
return
}
if !c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
const VERSION = 1
me := NewMsgEncoder(3, c)
me.encodeMsgID(SET_SERVER_LOGLEVEL).encodeInt(VERSION).encodeInt64(logLevel)
c.reqChan <- me.Bytes()
}
func (c *EClient) setServerLogLevelProtoBuf(SetServerLogLevelRequest *protobuf.SetServerLogLevelRequest) {
if !c.IsConnected() {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
me := NewMsgEncoder(2, c)
me.encodeMsgID(SET_SERVER_LOGLEVEL + PROTOBUF_MSG_ID)
msg, err := proto.Marshal(SetServerLogLevelRequest)
if err != nil {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), ERROR_ENCODING_PROTOBUF.Code, ERROR_ENCODING_PROTOBUF.Msg+err.Error(), "")
return
}
me.encodeProto(msg)
c.reqChan <- me.Bytes()
}
// 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 int64, contract *Contract, genericTickList string, snapshot bool, regulatorySnapshot bool, mktDataOptions []TagValue) {
if c.useProtoBuf(REQ_MKT_DATA) {
c.reqMarketDataProtoBuf(createMarketDataRequestProto(reqID, contract, genericTickList, snapshot, regulatorySnapshot, mktDataOptions))
return
}
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
me := NewMsgEncoder(30, c)
me.encodeMsgID(REQ_MKT_DATA).encodeInt(VERSION).encodeInt64(reqID)
if c.serverVersion >= MIN_SERVER_VER_REQ_MKT_DATA_CONID {
me.encodeInt64(contract.ConID)
}
me.encodeString(contract.Symbol)
me.encodeString(contract.SecType)
me.encodeString(contract.LastTradeDateOrContractMonth)
me.encodeFloatMax(contract.Strike)
me.encodeString(contract.Right)
me.encodeString(contract.Multiplier) // srv v15 and above
me.encodeString(contract.Exchange)
me.encodeString(contract.PrimaryExchange)
me.encodeString(contract.Currency)
me.encodeString(contract.LocalSymbol)
if c.serverVersion >= MIN_SERVER_VER_TRADING_CLASS {
me.encodeString(contract.TradingClass)
}
// Send combo legs for BAG requests (srv v8 and above)
if contract.SecType == "BAG" {
comboLegsCount := len(contract.ComboLegs)
me.encodeInt(comboLegsCount)
for _, comboLeg := range contract.ComboLegs {
me.encodeInt64(comboLeg.ConID)
me.encodeInt64(comboLeg.Ratio)
me.encodeString(comboLeg.Action)
me.encodeString(comboLeg.Exchange)
}
}
if c.serverVersion >= MIN_SERVER_VER_DELTA_NEUTRAL {
if contract.DeltaNeutralContract != nil {
me.encodeBool(true)
me.encodeInt64(contract.DeltaNeutralContract.ConID)
me.encodeFloat64(contract.DeltaNeutralContract.Delta)
me.encodeFloat64(contract.DeltaNeutralContract.Price)
} else {
me.encodeBool(false)
}
}
me.encodeString(genericTickList)
me.encodeBool(snapshot)
if c.serverVersion >= MIN_SERVER_VER_REQ_SMART_COMPONENTS {
me.encodeBool(regulatorySnapshot)
}
// send mktDataOptions parameter
if c.serverVersion >= MIN_SERVER_VER_LINKING {
me.encodeTagValues(mktDataOptions)
}
c.reqChan <- me.Bytes()
}
func (c *EClient) reqMarketDataProtoBuf(marketDataRequestProto *protobuf.MarketDataRequest) {
reqID := NO_VALID_ID
if marketDataRequestProto.ReqId != nil {
reqID = int64(*marketDataRequestProto.ReqId)
}
if !c.IsConnected() {
c.wrapper.Error(reqID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
me := NewMsgEncoder(30, c)
me.encodeMsgID(REQ_MKT_DATA + PROTOBUF_MSG_ID)
msg, err := proto.Marshal(marketDataRequestProto)
if err != nil {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), ERROR_ENCODING_PROTOBUF.Code, ERROR_ENCODING_PROTOBUF.Msg+err.Error(), "")
return
}
me.encodeProto(msg)
c.reqChan <- me.Bytes()
}
// CancelMktData stops the market data flow for the specified TickerId.
func (c *EClient) CancelMktData(reqID int64) {
if c.useProtoBuf(CANCEL_MKT_DATA) {
c.cancelMarketDataProtoBuf(createCancelMarketDataProto(reqID))
return
}
if !c.IsConnected() {
c.wrapper.Error(reqID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
const VERSION = 2
me := NewMsgEncoder(3, c)
me.encodeMsgID(CANCEL_MKT_DATA).encodeInt(VERSION).encodeInt64(reqID)
c.reqChan <- me.Bytes()
}
func (c *EClient) cancelMarketDataProtoBuf(cancelMarketDataProto *protobuf.CancelMarketData) {
reqID := NO_VALID_ID
if cancelMarketDataProto.ReqId != nil {
reqID = int64(*cancelMarketDataProto.ReqId)
}
if !c.IsConnected() {
c.wrapper.Error(reqID, currentTimeMillis(), NOT_CONNECTED.Code, NOT_CONNECTED.Msg, "")
return
}
me := NewMsgEncoder(3, c)
me.encodeMsgID(CANCEL_MKT_DATA + PROTOBUF_MSG_ID)
msg, err := proto.Marshal(cancelMarketDataProto)
if err != nil {
c.wrapper.Error(NO_VALID_ID, currentTimeMillis(), ERROR_ENCODING_PROTOBUF.Code, ERROR_ENCODING_PROTOBUF.Msg+err.Error(), "")
return
}
me.encodeProto(msg)
c.reqChan <- me.Bytes()
}
// 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.useProtoBuf(REQ_MARKET_DATA_TYPE) {
c.reqMarketDataTypeProtoBuf(createMarketDataTypeRequestProto(marketDataType))
return
}
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
me := NewMsgEncoder(3, c)
me.encodeMsgID(REQ_MARKET_DATA_TYPE).encodeInt(VERSION).encodeInt64(marketDataType)
c.reqChan <- me.Bytes()
}
func (c *EClient) reqMarketDataTypeProtoBuf(marketDataTypeRequestProto *protobuf.MarketDataTypeRequest) {