forked from gofinance/ib
-
Notifications
You must be signed in to change notification settings - Fork 1
/
metadata_manager.go
119 lines (101 loc) · 2.2 KB
/
metadata_manager.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
package ib
import (
"fmt"
)
type optionm struct {
sectype string
exchange string
}
// MetadataManager .
type MetadataManager struct {
AbstractManager
id int64
c Contract
options []optionm
metadata []ContractData
}
// NewMetadataManager .
func NewMetadataManager(e *Engine, c Contract) (*MetadataManager, error) {
am, err := NewAbstractManager(e)
if err != nil {
return nil, err
}
options := []optionm{
{"", ""}, // send as per contract
{"STK", "SMART"},
{"IND", "SMART"},
{"FUT", "GLOBEX"},
{"IND", "DTB"},
{"FUT", "DTB"},
}
m := &MetadataManager{
AbstractManager: *am,
c: c,
metadata: []ContractData{},
options: options,
}
go m.startMainLoop(m.preLoop, m.receive, m.preDestroy)
return m, nil
}
func (m *MetadataManager) preLoop() error {
return m.request()
}
func (m *MetadataManager) request() error {
if len(m.options) == 0 {
return nil
}
opt := m.options[0]
m.options = m.options[1:]
if opt.sectype != "" {
m.c.SecurityType = opt.sectype
}
if opt.exchange != "" {
m.c.Exchange = opt.exchange
}
m.eng.Unsubscribe(m.rc, m.id) // AbstractMgr goroutine already rx reply
m.id = m.eng.NextRequestID()
req := &RequestContractData{
Contract: m.c,
}
req.SetID(m.id)
m.eng.Subscribe(m.rc, m.id)
return m.eng.Send(req)
}
func (m *MetadataManager) preDestroy() {
m.eng.Unsubscribe(m.rc, m.id)
}
func (m *MetadataManager) receive(r Reply) (UpdateStatus, error) {
switch r.(type) {
case *ErrorMessage:
r := r.(*ErrorMessage)
if r.Code == 321 || r.Code == 200 {
if err := m.request(); err != nil {
return UpdateFalse, err
}
return UpdateFalse, nil
}
if r.SeverityWarning() {
return UpdateFalse, nil
}
return UpdateFalse, r.Error()
case *ContractData:
r := r.(*ContractData)
m.metadata = append(m.metadata, *r)
return UpdateFalse, nil
case *ContractDataEnd:
return UpdateFinish, nil
}
return UpdateFalse, fmt.Errorf("Unexpected type %v", r)
}
// Contract .
func (m *MetadataManager) Contract() Contract {
m.rwm.RLock()
defer m.rwm.RUnlock()
return m.c
}
// ContractData .
func (m *MetadataManager) ContractData() []ContractData {
m.rwm.RLock()
defer m.rwm.RUnlock()
return m.metadata
}