-
Notifications
You must be signed in to change notification settings - Fork 14
/
lightstreamer.go
233 lines (207 loc) · 7.2 KB
/
lightstreamer.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
package igmarkets
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
)
type LightStreamerTick struct {
Epic string
Time time.Time
Bid float64
Ask float64
}
const lightStreamerContentType = "application/x-www-form-urlencoded"
// OpenLightStreamerSubscription GetOTCWorkingOrders - Get all working orders
// epic: e.g. CS.D.BITCOIN.CFD.IP
// tickReceiver: receives all ticks from lightstreamer API
func (ig *IGMarkets) OpenLightStreamerSubscription(ctx context.Context, epics []string, tickReceiver chan LightStreamerTick) error {
// Obtain CST and XST tokens first
sessionVersion2, err := ig.LoginVersion2(ctx)
if err != nil {
return fmt.Errorf("ig.LoginVersion2() failed: %v", err)
}
timeZone, err := time.LoadLocation("Europe/London")
if err != nil {
return err
}
ig.Lock()
ig.TimeZoneLightStreamer = timeZone
ig.Unlock()
tr := &http.Transport{
MaxIdleConns: 1,
IdleConnTimeout: 30 * time.Second,
DisableCompression: true,
}
c := &http.Client{Transport: tr}
sessionID, sessionMsg, err := ig.lightStreamerConnect(c, sessionVersion2)
if err != nil {
return err
}
if err := ig.lightStreamerSubscribe(c, sessionVersion2.LightstreamerEndpoint, sessionID, sessionMsg, epics); err != nil {
return err
}
httpStream, err := ig.lightStreamerBindToConnection(c, sessionVersion2.LightstreamerEndpoint, sessionID)
if err != nil {
return err
}
go ig.lightstreamerReadSubscription(epics, tickReceiver, httpStream)
return nil
}
// connectToLightStream - Create new lightstreamer session
func (ig *IGMarkets) lightStreamerConnect(client *http.Client, sessionVersion2 *SessionVersion2) (sessionID, sessionMsg string, err error) {
body := []byte("LS_polling=true&LS_polling_millis=0&LS_idle_millis=0&LS_op2=create&LS_password=CST-" +
sessionVersion2.CSTToken + "|" + "XST-" + sessionVersion2.XSTToken + "&LS_user=" +
sessionVersion2.CurrentAccountId + "&LS_cid=mgQkwtwdysogQz2BJ4Ji kOj2Bg")
bodyBuf := bytes.NewBuffer(body)
url := fmt.Sprintf("%s/lightstreamer/create_session.txt", sessionVersion2.LightstreamerEndpoint)
resp, err := client.Post(url, lightStreamerContentType, bodyBuf)
if err != nil {
if resp != nil {
body, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil {
return "", "", fmt.Errorf("calling lightstreamer endpoint %s failed: %v; reading HTTP body also failed: %v",
url, err, err2)
}
return "", "", fmt.Errorf("calling lightstreamer endpoint %s failed: %v http.StatusCode:%d Body: %q",
url, err, resp.StatusCode, string(body))
}
return "", "", fmt.Errorf("calling lightstreamer endpoint %q failed: %v", url, err)
}
respBody, _ := ioutil.ReadAll(resp.Body)
sessionMsg = string(respBody[:])
if !strings.HasPrefix(sessionMsg, "OK") {
return "", "", fmt.Errorf("unexpected response from lightstreamer session endpoint %q: %q", url, sessionMsg)
}
sessionParts := strings.Split(sessionMsg, "\r\n")
sessionID = sessionParts[1]
sessionID = strings.ReplaceAll(sessionID, "SessionId:", "")
return sessionID, sessionMsg, nil
}
// lightStreamerSubscribe - Adding subscription for epics
func (ig *IGMarkets) lightStreamerSubscribe(client *http.Client, lightStreamerEndpoint, sessionID, sessionMsg string, epics []string) error {
var epicList string
for _, epic := range epics {
epicList = epicList + "MARKET:" + epic + "+"
}
body := []byte("LS_session=" + sessionID +
"&LS_polling=true&LS_polling_millis=0&LS_idle_millis=0&LS_op=add&LS_Table=1&LS_id=" +
epicList + "&LS_schema=UPDATE_TIME+BID+OFFER+MARKET_STATE&LS_mode=MERGE")
bodyBuf := bytes.NewBuffer(body)
url := fmt.Sprintf("%s/lightstreamer/control.txt", lightStreamerEndpoint)
resp, err := client.Post(url, lightStreamerContentType, bodyBuf)
if err != nil {
if resp != nil {
body, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil {
return fmt.Errorf("calling lightstreamer endpoint %s failed: %v; reading HTTP body also failed: %v",
url, err, err2)
}
return fmt.Errorf("calling lightstreamer endpoint %q failed: %v http.StatusCode:%d Body: %q",
url, err, resp.StatusCode, string(body))
}
return fmt.Errorf("calling lightstreamer endpoint %q failed: %v", url, err)
}
body, _ = ioutil.ReadAll(resp.Body)
if !strings.HasPrefix(sessionMsg, "OK") {
return fmt.Errorf("unexpected control.txt response: %q", body)
}
return nil
}
func (ig *IGMarkets) lightStreamerBindToConnection(client *http.Client, lightStreamerEndpoint, sessionID string) (httpStream *http.Response, err error) {
body := []byte("LS_session=" + sessionID + "&LS_polling=false&LS_polling_millis=0&LS_idle_millis=0")
bodyBuf := bytes.NewBuffer(body)
url := fmt.Sprintf("%s/lightstreamer/bind_session.txt", lightStreamerEndpoint)
resp, err := client.Post(url, lightStreamerContentType, bodyBuf)
if err != nil {
if resp != nil {
body, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil {
return nil, fmt.Errorf("calling lightstreamer endpoint %s failed: %v; reading HTTP body also failed: %v",
url, err, err2)
}
return nil, fmt.Errorf("calling lightstreamer endpoint %q failed: %v http.StatusCode:%d Body: %q",
url, err, resp.StatusCode, string(body))
}
return nil, fmt.Errorf("calling lightstreamer endpoint %q failed: %v", url, err)
}
return resp, nil
}
func (ig *IGMarkets) lightstreamerReadSubscription(epics []string, tickReceiver chan LightStreamerTick, resp *http.Response) {
const epicNameUnknown = "unknown"
var respBuf = make([]byte, 64)
var lastTicks = make(map[string]LightStreamerTick, len(epics)) // epic -> tick
defer close(tickReceiver)
// map table index -> epic name
var epicIndex = make(map[string]string, len(epics))
for i, epic := range epics {
epicIndex[fmt.Sprintf("1,%d", i+1)] = epic
}
for {
read, err := resp.Body.Read(respBuf)
if err != nil {
if err == io.EOF {
break
}
fmt.Printf("reading lightstreamer subscription failed: %v", err)
break
}
priceMsg := string(respBuf[0:read])
priceParts := strings.Split(priceMsg, "|")
// Sever ends streaming
if priceMsg == "LOOP\r\n\r\n" {
fmt.Printf("ending\n")
break
}
if len(priceParts) != 5 {
//fmt.Printf("Malformed price message: %q\n", priceMsg)
continue
}
var parsedTime time.Time
if priceParts[1] != "" {
priceTime := priceParts[1]
now := time.Now().In(ig.TimeZoneLightStreamer)
parsedTime, err = time.ParseInLocation("2006-1-2 15:04:05", fmt.Sprintf("%d-%d-%d %s",
now.Year(), now.Month(), now.Day(), priceTime), ig.TimeZoneLightStreamer)
if err != nil {
fmt.Printf("parsing time failed: %v time=%q\n", err, priceTime)
continue
}
}
tableIndex := priceParts[0]
priceBid, _ := strconv.ParseFloat(priceParts[2], 64)
priceAsk, _ := strconv.ParseFloat(priceParts[3], 64)
epic, found := epicIndex[tableIndex]
if !found {
fmt.Printf("unknown epic %q\n", tableIndex)
epic = epicNameUnknown
}
if epic != epicNameUnknown {
var lastTick, found = lastTicks[epic]
if found {
if priceAsk == 0 {
priceAsk = lastTick.Ask
}
if priceBid == 0 {
priceBid = lastTick.Bid
}
if parsedTime.IsZero() {
parsedTime = lastTick.Time
}
}
}
tick := LightStreamerTick{
Epic: epic,
Time: parsedTime,
Bid: priceBid,
Ask: priceAsk,
}
tickReceiver <- tick
lastTicks[epic] = tick
}
}