/
streamer.go
292 lines (244 loc) · 7.57 KB
/
streamer.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
package streamer
import (
"encoding/json"
"fmt"
"log"
"net/url"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/ianmcmahon/tdam"
"github.com/ianmcmahon/tdam/user"
)
const (
QOSExpress QoSLevel = "0" // 500 ms
QOSRealTime QoSLevel = "1" // 750 ms
QOSFast QoSLevel = "2" // 1000ms
QOSModerate QoSLevel = "3" // 1500ms
QOSSlow QoSLevel = "4" // 3000 ms
QOSDelayed QoSLevel = "5" // 3000 ms
)
type QoSLevel string
type responseCallback func(resp response)
type DataCallback func(symbol string, resp Data)
type Streamer struct {
tdamClient *tdam.Client
principal *user.UserPrincipal
conn *websocket.Conn
done chan bool
requestCount int
wg *sync.WaitGroup
responseCallbacks map[int]responseCallback // maps by requestID
// maps by--> service symbol subscriber
dataCallbacks map[string]map[string]map[string]DataCallback
cbMutex *sync.RWMutex
// maps by--> service symbol subscriber
subscribers map[string]map[string][]string
}
func (s *Streamer) nextRequest() int {
cnt := s.requestCount
s.requestCount++
return cnt
}
func New(client *tdam.Client) (*Streamer, error) {
up, err := user.GetUserPrincipals(client)
if err != nil {
return nil, err
}
s := &Streamer{
tdamClient: client,
principal: up,
done: make(chan bool),
requestCount: 0,
wg: &sync.WaitGroup{},
cbMutex: &sync.RWMutex{},
responseCallbacks: make(map[int]responseCallback),
dataCallbacks: map[string]map[string]map[string]DataCallback{
"QUOTE": make(map[string]map[string]DataCallback),
"OPTION": make(map[string]map[string]DataCallback),
"LEVELONE_FUTURES": make(map[string]map[string]DataCallback),
"LEVELONE_FUTURES_OPTIONS": make(map[string]map[string]DataCallback),
},
subscribers: map[string]map[string][]string{
"QUOTE": make(map[string][]string),
"OPTION": make(map[string][]string),
"LEVELONE_FUTURES": make(map[string][]string),
"LEVELONE_FUTURES_OPTIONS": make(map[string][]string),
},
}
// keep wg held whenever we aren't logged in
s.wg.Add(1)
return s, nil
}
func (s *Streamer) Run() error {
var err error
if s == nil {
return fmt.Errorf("streamer is nil!?")
}
if s.principal == nil {
return fmt.Errorf("No user principal!")
}
u := url.URL{Scheme: "ws", Host: s.principal.StreamerInfo.StreamerSocketUrl, Path: "/ws"}
log.Printf("connecting to %s", u.String())
s.conn, _, err = websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
return err
}
go s.handleIncoming()
if err := s.sendRequest(s.loginRequest(), func(resp response) {
code := resp.Content["code"]
// successful login releases the waitlock
if v, ok := code.(float64); ok && v == 0.0 {
//fmt.Printf("Login: code: %T %v\n", code, code)
s.wg.Done()
}
}); err != nil {
log.Printf("error sending login request: %v\n", err)
return err
}
return nil
}
func (s *Streamer) QoS(level QoSLevel) error {
if err := s.sendRequest(s.qosRequest(level), func(resp response) {
}); err != nil {
log.Printf("error sending qos request: %v\n", err)
return err
}
return nil
}
func (s *Streamer) qosRequest(level QoSLevel) request {
loginReq := request{
Service: "ADMIN",
Command: "QOS",
RequestID: s.nextRequest(),
Account: s.principal.Accounts[0].AccountId,
Source: s.principal.StreamerInfo.AppId,
Parameters: map[string]string{
"qoslevel": string(level),
},
}
return loginReq
}
func (s *Streamer) Stop() error {
if err := s.sendRequest(s.logoutRequest(), func(resp response) {
code := resp.Content["code"]
if v, ok := code.(float64); ok && v == 0.0 {
//fmt.Printf("Logout: code: %T %v\n", code, code)
s.done <- true
}
}); err != nil {
log.Printf("error sending logout request: %v\n", err)
return err
}
return nil
}
func (s *Streamer) logoutRequest() request {
logoutReq := request{
Service: "ADMIN",
Command: "LOGOUT",
RequestID: s.nextRequest(),
Account: s.principal.Accounts[0].AccountId,
Source: s.principal.StreamerInfo.AppId,
Parameters: map[string]string{},
}
return logoutReq
}
func (s *Streamer) handleIncoming() {
//dump, err := os.Create("streamdump.log")
//if err != nil {
// log.Fatal(err)
//}
//defer dump.Close()
for {
_, message, err := s.conn.ReadMessage()
if err != nil {
log.Println("read:", err)
s.done <- true
panic(err) // TODO: panic here so that hopefully docker will restart us
return
}
var resp responseWrapper
if err := json.Unmarshal(message, &resp); err != nil {
log.Printf("received: %s", message)
log.Printf("error unmarshaling response: %v", err)
continue
}
// there's three (four really) possible responses in here
// is it possible that we get different types of response in one packet?
// maybe! let's just spin through all of them and route the messages
// fmt.Printf("recv: %#v\n", resp)
for _, resp := range resp.Response {
// requests are submitted with a requestID, and the caller
// can attach a callback. When we receive the response for that request,
// route it back to the caller
if cb, ok := s.responseCallbacks[resp.RequestID]; ok {
cb(resp)
}
}
for _, data := range resp.Data {
// data messages come from subscriptions.
// need to find the list of subscribers for this service/symbol and notify all
for _, packet := range data.Content {
symbol, ok := packet["key"].(string)
if !ok {
continue
}
//fmt.Printf("dataCallbacks[%s][%s: %v\n", data.Service, symbol, s.dataCallbacks[data.Service][symbol])
s.cbMutex.RLock()
callbacks := s.dataCallbacks[data.Service][symbol]
s.cbMutex.RUnlock()
for _, cb := range callbacks {
cb(symbol, Data{data.Service, data.Command, data.Timestamp, []map[string]interface{}{packet}})
}
}
}
}
}
func (s *Streamer) sendRequest(req request, cf responseCallback) error {
if !req.isLoginCommand() {
s.wg.Wait()
}
// todo: this is hacky and could be better. Assumes only one request in the wrapper.
requestId := req.RequestID
wrappedReq := requestWrapper{"requests": []request{req}}
s.responseCallbacks[requestId] = cf
data, err := json.Marshal(wrappedReq)
if err != nil {
return err
}
//log.Printf("sending req: %s\n", data)
if err := s.conn.WriteMessage(websocket.TextMessage, data); err != nil {
log.Println("write:", err)
return err
}
return nil
}
func (s *Streamer) loginRequest() request {
timestamp := time.Time(s.principal.StreamerInfo.TokenTimestamp).Unix() * 1000
credentials := url.Values{
"userid": []string{s.principal.Accounts[0].AccountId},
"token": []string{s.principal.StreamerInfo.Token},
"company": []string{s.principal.Accounts[0].Company},
"segment": []string{s.principal.Accounts[0].Segment},
"cddomain": []string{s.principal.Accounts[0].AccountCdDomainId},
"usergroup": []string{s.principal.StreamerInfo.UserGroup},
"accesslevel": []string{s.principal.StreamerInfo.AccessLevel},
"authorized": []string{"Y"},
"timestamp": []string{fmt.Sprintf("%d", timestamp)},
"appid": []string{s.principal.StreamerInfo.AppId},
"acl": []string{s.principal.StreamerInfo.Acl},
}
loginReq := request{
Service: "ADMIN",
Command: "LOGIN",
RequestID: s.nextRequest(),
Account: s.principal.Accounts[0].AccountId,
Source: s.principal.StreamerInfo.AppId,
Parameters: map[string]string{
"credential": url.QueryEscape(credentials.Encode()),
"token": s.principal.StreamerInfo.Token,
"version": "1.0",
},
}
return loginReq
}