forked from gofinance/ib
-
Notifications
You must be signed in to change notification settings - Fork 1
/
engine.go
683 lines (607 loc) · 15.1 KB
/
engine.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
// Package ib trade offers a pure Go abstraction over Interactive Brokers IB API.
//
// Engine is the main type. It provides a mechanism to connect to either IB
// Gateway or TWS, send Request values and receive Reply values. The Engine
// provides an observer pattern both for receiving Reply values as well as Engine
// termination notification. Any network level errors will terminate the Engine.
//
// A high-level Manager interface is also provided. This provides a way to
// easily use IB API without needing to deal directly with Engine and the
// associated Request, Reply, message ID and Reply ordering considerations.
//
// All types are thread-safe and can be used from multiple goroutines at once.
// Blocking methods are identified in the documentation.
package ib
import (
"bufio"
"bytes"
"fmt"
"log"
"net"
"reflect"
"strings"
"time"
)
// consts .
const (
gatewayDefault = "127.0.0.1:4001"
UnmatchedReplyID = int64(-9223372036854775808)
)
// EngineOptions .
type EngineOptions struct {
Gateway string
Client int64
DumpConversation bool
}
// Engine is the entry point to the IB IB API
type Engine struct {
id chan int64
exit chan bool
terminated chan struct{}
ch chan command
gateway string
client int64
con net.Conn
reader *bufio.Reader
input *bytes.Buffer
output *bytes.Buffer
rxReply chan Reply
rxErr chan error
txRequest chan txrequest
txErr chan error
observers map[int64]chan<- Reply
unObservers []chan<- Reply
allObservers []chan<- Reply
stObservers []chan<- EngineState
state EngineState
serverTime time.Time
clientVersion int64
serverVersion int64
dumpConversation bool
lastDumpRead int64
lastDumpID int64
fatalError error
}
type command struct {
fun func()
ack chan struct{}
}
type txrequest struct {
req Request
ack chan struct{}
}
func uniqueID(start int64) chan int64 {
ch := make(chan int64)
id := start
go func() {
for {
if id == UnmatchedReplyID {
id++
}
ch <- id
id++
}
}()
return ch
}
// Next client id. Package scope to ensure new engines have unique client IDs.
var clientSeq = uniqueID(1)
// NewEngine takes a client id and returns a new connection
// to IB Gateway or IB Trader Workstation.
func NewEngine(opt EngineOptions) (re *Engine, rerr error) {
gateway := opt.Gateway
if gateway == "" {
gateway = gatewayDefault
}
conn, err := net.Dial("tcp", gateway)
if err != nil {
return nil, err
}
defer func() {
if rerr != nil {
_ = conn.Close()
}
}()
client := opt.Client
if client == 0 {
client = <-clientSeq
}
e := Engine{
id: uniqueID(100),
exit: make(chan bool),
terminated: make(chan struct{}),
ch: make(chan command),
gateway: gateway,
client: client,
con: conn,
reader: bufio.NewReader(conn),
input: bytes.NewBuffer(make([]byte, 0, 4096)),
output: bytes.NewBuffer(make([]byte, 0, 4096)),
rxReply: make(chan Reply),
rxErr: make(chan error),
txRequest: make(chan txrequest),
txErr: make(chan error),
observers: map[int64]chan<- Reply{},
state: EngineReady,
dumpConversation: opt.DumpConversation,
}
if err := e.handshake(); err != nil {
return nil, err
}
// start worker goroutines (these exit on request or error)
go e.startReceiver()
go e.startTransmitter()
go e.startMainLoop()
// send the StartAPI request
e.Send(&StartAPI{Client: e.client})
return &e, nil
}
func (e *Engine) handshake() error {
// write client version
clientShake := &clientHandshake{clientVersion}
e.output.Reset()
if err := clientShake.write(e.output); err != nil {
return err
}
if _, err := e.con.Write(e.output.Bytes()); err != nil {
return err
}
// read server version and time
serverShake := &serverHandshake{}
e.input.Reset()
if err := serverShake.read(e.reader); err != nil {
return err
}
if serverShake.version < minServerVersion {
return fmt.Errorf("%s must be at least version %d (reported %d)", e.ConnectionInfo(), minServerVersion, serverShake.version)
}
e.serverVersion = serverShake.version
e.serverTime = serverShake.time
return nil
}
func (e *Engine) startReceiver() {
defer func() {
close(e.rxReply)
close(e.rxErr)
}()
for {
r, err := e.receive()
if err != nil {
select {
case <-e.terminated:
return
case e.rxErr <- err:
return
}
}
select {
case <-e.terminated:
return
case e.rxReply <- r:
}
}
}
func (e *Engine) startTransmitter() {
defer func() {
// Don't close txRequest, as we are not the sender
close(e.txErr)
}()
for {
select {
case <-e.terminated:
return
case t := <-e.txRequest:
if err := e.transmit(t.req); err != nil {
select {
case <-e.terminated:
return
case e.txErr <- err:
return
}
}
close(t.ack)
}
}
}
func (e *Engine) startMainLoop() {
defer func() {
// Signal terminating for benefit of other goroutines
close(e.terminated)
// Safe to kill the connection, as we're advising other goroutines we're quitting
e.con.Close()
// Wait for other goroutines to indicate they've finished
<-e.txErr
<-e.rxErr
outer:
for _, ob := range e.stObservers {
for {
select {
case ob <- e.state:
continue outer
case <-time.After(5 * time.Second):
log.Printf("Waited 5 seconds for state channel %v\n", ob)
}
}
}
}()
for {
select {
case <-e.exit:
e.state = EngineExitNormal
return
case err := <-e.rxErr:
log.Printf("%s engine: RX error %s", e.ConnectionInfo(), err)
e.fatalError = err
e.state = EngineExitError
return
case err := <-e.txErr:
log.Printf("%s engine: TX error %s", e.ConnectionInfo(), err)
e.fatalError = err
e.state = EngineExitError
return
case cmd := <-e.ch:
cmd.fun()
close(cmd.ack)
case r := <-e.rxReply:
e.deliverToObservers(r)
}
}
}
func (e *Engine) deliverToObservers(r Reply) {
if r.code() == mErrorMessage {
var done []chan<- Reply
outer:
for _, o := range e.observers {
for _, prevDone := range done {
if o == prevDone {
continue outer
}
}
done = append(done, o)
e.deliverToObserver(o, r)
}
for _, o := range e.unObservers {
e.deliverToObserver(o, r)
}
for _, o := range e.allObservers {
e.deliverToObserver(o, r)
}
return
}
if mr, ok := r.(MatchedReply); ok {
if o, ok := e.observers[mr.ID()]; ok {
e.deliverToObserver(o, r)
}
for _, o := range e.allObservers {
e.deliverToObserver(o, r)
}
return
}
// must be a non-error, unmatched reply
for _, o := range e.unObservers {
e.deliverToObserver(o, r)
}
for _, o := range e.allObservers {
e.deliverToObserver(o, r)
}
}
func (e *Engine) deliverToObserver(c chan<- Reply, r Reply) {
for {
select {
case c <- r:
return
case <-time.After(time.Duration(5) * time.Second):
log.Printf("Waited 5 seconds for reply channel %v\n", c)
}
}
}
func (e *Engine) transmit(r Request) (err error) {
e.output.Reset()
// encode message type and client version
hdr := &header{
code: int64(r.code()),
version: r.version(),
}
if err = hdr.write(e.output); err != nil {
return
}
// encode the message itself
if err = r.write(e.output); err != nil {
return
}
if e.dumpConversation {
b := e.output
s := strings.Replace(b.String(), "\000", "-", -1)
fmt.Printf("%d> '%s'\n", e.client, s)
}
_, err = e.con.Write(e.output.Bytes())
return
}
// NextRequestID returns a unique request id (which is never UnmatchedReplyID).
func (e *Engine) NextRequestID() int64 {
return <-e.id
}
// ClientID .
func (e *Engine) ClientID() int64 {
return e.client
}
// ConnectionInfo returns the gateway address and client ID of this connection.
func (e *Engine) ConnectionInfo() string {
return fmt.Sprintf("%s/%d", e.gateway, e.client)
}
// sendCommand delivers the func to the engine, blocking the calling goroutine
// until the command is acknowledged as completed or the engine exits.
func (e *Engine) sendCommand(c func()) {
cmd := command{c, make(chan struct{})}
// send cmd
select {
case <-e.terminated:
return
case e.ch <- cmd:
}
// await ack (also handle termination, although it shouldn't happen
// given the cmd was delivered so we beat any exit/error situations)
select {
case <-e.terminated:
log.Println("Engine unexpectedly terminated after command sent")
return
case <-cmd.ack:
return
}
}
// Subscribe will notify subscribers of future events with given id.
// Many request types implement MatchedRequest and therefore provide a SetID().
// To receive the corresponding MatchedReply events, firstly subscribe with the
// same id as will be assigned with SetID(). Any incoming events that do not
// implement MatchedReply will be delivered to those observers subscribed to
// the UnmatchedReplyID constant. Note that the engine will raise an error if
// an attempt is made to send a MatchedRequest with UnmatchedReplyID as its id,
// given the high unlikelihood of that id being required in normal situations
// and that NextRequestID() guarantees to never return UnmatchedReplyID.
// Each ErrorMessage event is delivered once only to each known observer.
// The engine never closes the channel (allowing reuse across IDs and engines).
// This call will block until the subscriber is registered or engine terminates.
func (e *Engine) Subscribe(o chan<- Reply, id int64) {
e.sendCommand(func() {
if id != UnmatchedReplyID {
e.observers[id] = o
return
}
e.unObservers = append(e.unObservers, o)
})
}
// SubscribeAll .
func (e *Engine) SubscribeAll(o chan<- Reply) {
e.sendCommand(func() {
e.allObservers = append(e.allObservers, o)
})
}
// Unsubscribe blocks until the observer is removed. It also maintains a
// goroutine to sink the channel until the unsubscribe is finalised, which
// frees the caller from maintaining a separate goroutine.
func (e *Engine) Unsubscribe(o chan Reply, id int64) {
terminate := make(chan struct{})
go func() {
for {
select {
case <-o:
case <-terminate:
return
}
}
}()
e.sendCommand(func() {
if id != UnmatchedReplyID {
delete(e.observers, id)
return
}
newUnObs := []chan<- Reply{}
for _, existing := range e.unObservers {
if existing != o {
newUnObs = append(newUnObs, o)
}
}
e.unObservers = newUnObs
})
close(terminate)
}
// UnsubscribeAll .
func (e *Engine) UnsubscribeAll(o chan Reply) {
terminate := make(chan struct{})
go func() {
for {
select {
case <-o:
case <-terminate:
return
}
}
}()
e.sendCommand(func() {
newUnObs := []chan<- Reply{}
for _, existing := range e.allObservers {
if existing != o {
newUnObs = append(newUnObs, o)
}
}
e.allObservers = newUnObs
})
close(terminate)
}
// SubscribeState will register an engine state subscriber that is notified when
// the engine exits for any reason. The engine will close the channel after use.
// This call will block until the subscriber is registered or engine terminates.
func (e *Engine) SubscribeState(o chan<- EngineState) {
if o == nil {
return
}
e.sendCommand(func() { e.stObservers = append(e.stObservers, o) })
}
// UnsubscribeState blocks until the observer is removed. It also maintains a
// goroutine to sink the channel until the unsubscribe is finalised, which
// frees the caller from maintaining a separate goroutine.
func (e *Engine) UnsubscribeState(o chan EngineState) {
terminate := make(chan struct{})
go func() {
for {
select {
case <-o:
case <-terminate:
return
}
}
}()
e.sendCommand(func() {
var r []chan<- EngineState
for _, exist := range e.stObservers {
if exist != o {
r = append(r, exist)
}
}
e.stObservers = r
})
close(terminate)
}
// FatalError returns the error which caused termination (or nil if no error).
func (e *Engine) FatalError() error {
return e.fatalError
}
// State returns the engine's current state.
func (e *Engine) State() EngineState {
return e.state
}
// Stop blocks until the engine is fully stopped. It can be safely called on an
// already-stopped or stopping engine.
func (e *Engine) Stop() {
select {
case <-e.terminated:
return
case e.exit <- true:
}
<-e.terminated
}
type header struct {
code int64
version int64
}
func (v *header) write(b *bytes.Buffer) error {
if err := writeInt(b, v.code); err != nil {
return err
}
return writeInt(b, v.version)
}
func (v *header) read(b *bufio.Reader) error {
var err error
if v.code, err = readInt(b); err != nil {
return err
}
v.version, err = readInt(b)
return err
}
// Send a message to the engine, blocking until sent or the engine exits.
// This method will return an error if the UnmatchedReplyID is used or the
// engine exits. A nil error indicates successful transmission. Any transmission
// failure (eg connectivity loss) will cause the engine to exit with an error.
func (e *Engine) Send(r Request) error {
if mr, ok := r.(MatchedRequest); ok {
if mr.ID() == UnmatchedReplyID {
return fmt.Errorf("%d is a reserved ID (try using NextRequestID)", UnmatchedReplyID)
}
}
t := txrequest{r, make(chan struct{})}
// send tx request
select {
case <-e.terminated:
if err := e.FatalError(); err != nil {
return err
}
return fmt.Errorf("Engine has already exited normally")
case e.txRequest <- t:
}
// await ack or error
select {
case <-e.terminated:
if err := e.FatalError(); err != nil {
return err
}
return fmt.Errorf("Engine has already exited normally")
case <-t.ack:
return nil
}
}
type packetError struct {
value interface{}
kind reflect.Type
}
func (e *packetError) Error() string {
return fmt.Sprintf("don't understand packet '%v' of type '%v'", e.value, e.kind)
}
func failPacket(v interface{}) error {
return &packetError{
value: v,
kind: reflect.ValueOf(v).Type(),
}
}
func (e *Engine) receive() (Reply, error) {
e.input.Reset()
hdr := &header{}
// decode header
if err := hdr.read(e.reader); err != nil {
if e.dumpConversation {
fmt.Printf("%d< %v\n", e.client, err)
}
return nil, err
}
// decode message
r, err := code2Msg(hdr.code)
if err != nil {
if e.dumpConversation {
fmt.Printf("%d< %v %s\n", e.client, hdr, err)
}
return nil, err
}
if err := r.read(e.reader); err != nil {
if e.dumpConversation {
fmt.Printf("%d< %v %s\n", e.client, hdr, err)
}
return nil, err
}
if e.dumpConversation {
dump := hdr.code != e.lastDumpRead
e.lastDumpRead = hdr.code
dump = dump || r.code() == mErrorMessage
if mr, ok := r.(MatchedReply); ok {
dump = dump || mr.ID() != e.lastDumpID
e.lastDumpID = mr.ID()
}
if dump {
str := fmt.Sprintf("%v", r)
cut := len(str)
if cut > 80 {
str = str[:76] + "..."
}
fmt.Printf("%d< %v %s\n", e.client, hdr, str)
}
}
return r, nil
}
// EngineState .
type EngineState int
// Engine State enum
const (
EngineReady EngineState = 1 << iota
EngineExitError
EngineExitNormal
)
func (s EngineState) String() string {
switch s {
case EngineReady:
return "EngineReady"
case EngineExitError:
return "EngineExitError"
case EngineExitNormal:
return "EngineExitNormal"
default:
panic("unreachable")
}
}