forked from aliukevicius/cexio-websocket-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcexio_public.go
410 lines (335 loc) · 8.94 KB
/
cexio_public.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
package cexio
import (
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
)
//NewAPI returns new API instance with default settings
func NewAPI(key string, secret string) (*API, chan error) {
api := &API{
Key: key,
Secret: secret,
Dialer: websocket.DefaultDialer,
responseSubscribers: map[string]chan subscriberType{},
subscriberMutex: sync.Mutex{},
orderBookHandlers: map[string]chan bool{},
stopDataCollector: false,
ReceiveDone: make(chan bool),
authenticate: true,
reconAtempts: 100,
}
locker := &sync.Mutex{}
api.cond = sync.NewCond(locker)
api.HeartMonitor = make(chan bool)
api.HeartBeat = make(chan bool, 100)
api.errorChan = make(chan error, 1)
return api, api.errorChan
}
//NewAPI returns new API instance with default settings
func NewPublicAPI() (*API, chan error) {
api := &API{
Dialer: websocket.DefaultDialer,
responseSubscribers: map[string]chan subscriberType{},
subscriberMutex: sync.Mutex{},
orderBookHandlers: map[string]chan bool{},
stopDataCollector: false,
ReceiveDone: make(chan bool),
authenticate: false,
reconAtempts: 100,
}
locker := &sync.Mutex{}
api.cond = sync.NewCond(locker)
api.HeartMonitor = make(chan bool)
api.HeartBeat = make(chan bool, 100)
api.errorChan = make(chan error, 1)
return api, api.errorChan
}
//Connect connects to cex.io websocket API server
func (a *API) Connect() error {
go a.watchDog()
// -------------------------------------------
// Create done channel on connect.
// Close closes it, so Connect must create it
// -------------------------------------------
a.done = make(chan bool)
a.cond.L.Lock()
a.connected = false
a.cond.L.Unlock()
sub := a.subscribe("connected")
defer a.unsubscribe("connected")
// --------------------------------
// Attempt to connect to websocket
// --------------------------------
errCounter := a.reconAtempts
conn, _, err := a.Dialer.Dial(apiURL, nil)
for err != nil {
conn, _, err = a.Dialer.Dial(apiURL, nil)
if err == nil {
break
}
errCounter--
if errCounter <= 0 {
err = fmt.Errorf("Could not connect to websocket after %d attempts: %s", a.reconAtempts, err.Error())
return err
}
log.Debugf("Websocket Connection error, will try %d more times : %s", errCounter, err.Error())
time.Sleep(time.Second * 30)
}
a.conn = conn
log.Info("Dialed into websocket...")
// run response from API server collector
go a.connectionResponse(a.authenticate)
<-sub //wait for connect response
// run authentication
if a.authenticate {
err = a.auth()
if err != nil {
return err
}
}
log.Info("Connection complete!!")
a.cond.L.Lock()
a.connected = true
a.cond.L.Unlock()
log.Info("Sending broadcast...")
a.cond.Broadcast()
return nil
}
//Close closes API connection
func (a *API) Close(ID string) error {
log.Info("Closing CEXIO Websocket connection...", ID)
a.stopDataCollector = true
close(a.done)
log.Info("Done channel closed...")
a.connected = false
//a.stopDataCollector = true
err := a.conn.Close()
if err != nil {
log.Error("Close error:", err.Error())
return err
}
log.Info("CEXIO Websocket connection closed!! ", ID)
return nil
}
//Ticker send ticker request
func (a *API) Ticker(cCode1 string, cCode2 string) (*ResponseTicker, error) {
//Signal that the transaction was completed
msgDone := false
timeOut := make(chan bool)
// --------------------------------------------------------------
// Time closure to monitor that the transaction gets completed
// --------------------------------------------------------------
timer := func() {
startTime := time.Now()
for !msgDone {
elapsed := time.Since(startTime)
if elapsed > time.Second*10 {
msgDone = true
timeOut <- true
log.Warn("Ticker msg timeout !!")
}
time.Sleep(time.Second)
}
}
a.cond.L.Lock()
for !a.connected {
a.cond.Wait()
}
action := "ticker"
sub := a.subscribe(action)
defer a.unsubscribe(action)
timestamp := time.Now().UnixNano()
msg := requestTicker{
E: action,
Data: []string{cCode1, cCode2},
Oid: fmt.Sprintf("%d_%s:%s", timestamp, cCode1, cCode2),
}
/*
err := a.conn.SetReadDeadline(time.Now().Add(10 * time.Second))
if err != nil {
myError, _ := fmt.Printf("read deadline:%s\n ", err.Error())
log.Error(myError)
}
err = a.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
if err != nil {
myError, _ := fmt.Printf("write deadline:%s\n ", err.Error())
log.Error(myError)
}
*/
// ------------
// Start Timer
// -----------
go timer()
err := a.conn.WriteJSON(msg)
if err != nil {
log.Error("Ticker WriteJSON:", err.Error())
msgDone = true
doRestart := false
if strings.Contains(err.Error(), "use of closed connection") {
doRestart = true
log.Warn("use of closed connection detected, handling error")
}
if doRestart {
log.Warn("restarting conn...")
a.reconnect()
log.Warn("Rewriting jsjon...")
err := a.conn.WriteJSON(msg)
if err != nil {
log.Fatal("Could not WriteJSON after reconnection...")
}
log.Warn("Rewriting jsjon...done!!")
} else {
//a.mu.Unlock()
log.Error("Con WriteJson: ", err.Error())
a.cond.L.Unlock()
return nil, err
}
}
a.cond.L.Unlock()
/*
if err != nil {
log.Error("Error while geting ticker: ", err.Error())
ws.reconnect()
ticker, err = ws.api.Ticker(cCode1, cCode2)
}
*/
// wait for response from sever
select {
case resp := <-sub:
{
respMsg := resp.([]byte)
msgDone = true
resp := &ResponseTicker{}
err = json.Unmarshal(respMsg, resp)
if err != nil {
log.Error("Ticker Error: Conn Unmarshal: ", err.Error())
return nil, err
}
// check if authentication was successfull
if resp.OK != "ok" {
log.Error("Ticker Error: Conn Authentication: ", resp.Data)
return nil, errors.New(resp.Data.Error)
}
return resp, nil
}
case _ = <-timeOut:
{
msgDone = true
log.Error("Ticker Time out")
return &ResponseTicker{}, nil
}
}
}
//Ticker send ticker request
func (a *API) GetBalance() (*responseGetBalance, error) {
a.cond.L.Lock()
action := "get-balance"
sub := a.subscribe(action)
defer a.unsubscribe(action)
timestamp := time.Now().UnixNano()
msg := requestGetBalance{
E: action,
Data: "",
Oid: fmt.Sprintf("%d_%s", timestamp, action),
}
err := a.conn.WriteJSON(msg)
if err != nil {
a.cond.L.Unlock()
return nil, err
}
// wait for response from sever
resp := (<-sub).(*responseGetBalance)
/*
resp := &responseGetBalance{}
err = json.Unmarshal(respMsg, resp)
if err != nil {
return nil, err
}
*/
// check if authentication was successfull
if resp.OK != "ok" {
a.cond.L.Unlock()
return nil, errors.New(resp.OK)
}
a.cond.L.Unlock()
return resp, nil
}
//OrderBookSubscribe subscribes to order book updates.
//Order book snapshot will come as a first update
func (a *API) OrderBookSubscribe(cCode1 string, cCode2 string, depth int64, handler SubscriptionHandler) (int64, error) {
action := "order-book-subscribe"
currencyPair := fmt.Sprintf("%s:%s", cCode1, cCode2)
subscriptionIdentifier := fmt.Sprintf("%s_%s", action, currencyPair)
sub := a.subscribe(subscriptionIdentifier)
defer a.unsubscribe(subscriptionIdentifier)
timestamp := time.Now().UnixNano()
req := requestOrderBookSubscribe{
E: action,
Oid: fmt.Sprintf("%d_%s:%s", timestamp, cCode1, cCode2),
Data: requestOrderBookSubscribeData{
Pair: []string{cCode1, cCode2},
Subscribe: true,
Depth: depth,
},
}
err := a.conn.WriteJSON(req)
if err != nil {
return 0, err
}
bookSnapshot := (<-sub).(*responseOrderBookSubscribe)
go a.handleOrderBookSubscriptions(bookSnapshot, currencyPair, handler)
return bookSnapshot.Data.ID, nil
}
func (a *API) TickerSub(tickerChan chan ResponseTickerSubData) {
funcName := "TickerSub"
//Signal that the transaction was completed
log.Info("Registering tickerSub")
action := "tick"
sub := a.subscribe(action)
defer a.unsubscribe(action)
msg := requestTickerSub{
E: "subscribe",
Rooms: []string{"tickers"},
}
// ------------
// Start Timer
// -----------
err := a.conn.WriteJSON(msg)
if err != nil {
tickerSubErr := fmt.Errorf("%s, WriteJSON :%s", funcName, err.Error())
log.Error(tickerSubErr)
a.errorChan <- tickerSubErr
return
}
log.Info("TickerSub request sent...")
for {
// wait for response from sever
select {
case <-a.done:
{
log.Infof("TickerSub exiting...")
return
}
case resp := <-sub:
{
respMsg := resp.([]byte)
resp := &ResponseTickerSub{}
err = json.Unmarshal(respMsg, resp)
if err != nil {
tickerSubErr := fmt.Errorf("%s, from response channel :%s", funcName, err.Error())
log.Error(tickerSubErr)
a.errorChan <- tickerSubErr
return
} else {
//log.Info("RESP:", resp.Data.Symbol1, resp.Data.Symbol2, resp.Data.Price)
tickerChan <- resp.Data
}
}
}
}
}