forked from aopoltorzhicky/go_kraken
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
594 lines (529 loc) · 14.6 KB
/
client.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
package websocket
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"strings"
"sync"
"time"
"unicode"
)
type asynchronous interface {
Connect() error
Send(ctx context.Context, msg interface{}) error
Listen() <-chan []byte
Close()
Done() <-chan error
}
type asynchronousFactory interface {
Create() asynchronous
}
type websocketAsynchronousFactory struct {
parameters *Parameters
}
// Client provides a unified interface for users to interact with the Kraken Websocket API.
// nolint:megacheck,structcheck
type Client struct {
asyncFactory asynchronousFactory // for re-creating transport during reconnects
timeout int64 // read timeout
asynchronous asynchronous
isConnected bool
terminal bool
init bool
heartbeat time.Time
hbChannel chan error
// connection & operational behavior
parameters *Parameters
// channel to stop all routines
shutdown chan struct{}
// downstream listener channel to deliver API objects
listener chan interface{}
// race management
waitGroup sync.WaitGroup
subscriptions map[int64]*SubscriptionStatus
factories map[string]ParseFactory
isConnectedMux sync.Mutex
heartbeatMux sync.Mutex
}
// Create returns a new websocket transport.
func (w *websocketAsynchronousFactory) Create() asynchronous {
return newWs(w.parameters.URL, w.parameters.LogTransport)
}
// New creates a default client.
func New() *Client {
params := NewDefaultParameters()
c := &Client{
asyncFactory: &websocketAsynchronousFactory{
parameters: params,
},
isConnected: false,
parameters: params,
listener: make(chan interface{}),
terminal: false,
shutdown: make(chan struct{}),
asynchronous: nil,
heartbeat: time.Now().Add(params.HeartbeatTimeout),
hbChannel: make(chan error),
subscriptions: make(map[int64]*SubscriptionStatus),
factories: make(map[string]ParseFactory),
}
c.createFactories()
return c
}
// NewSandbox - creates a default sandbox client.
func NewSandbox() *Client {
params := NewDefaultSandboxParameters()
c := &Client{
asyncFactory: &websocketAsynchronousFactory{
parameters: params,
},
isConnected: false,
parameters: params,
listener: make(chan interface{}),
terminal: false,
shutdown: make(chan struct{}),
asynchronous: nil,
heartbeat: time.Now().Add(params.HeartbeatTimeout),
hbChannel: make(chan error),
subscriptions: make(map[int64]*SubscriptionStatus),
factories: make(map[string]ParseFactory),
}
c.createFactories()
return c
}
func (c *Client) controlHeartbeat() {
for {
select {
case <-c.shutdown:
log.Printf("Shutdown control heartbeat")
return
default:
}
c.heartbeatMux.Lock()
if time.Now().After(c.heartbeat) {
c.hbChannel <- fmt.Errorf("Heartbeat disconnect on client")
c.heartbeatMux.Unlock()
return
}
c.heartbeatMux.Unlock()
time.Sleep(c.parameters.HeartbeatCheckPeriod)
}
}
func (c *Client) listenHeartbeat() <-chan error {
return c.hbChannel
}
func (c *Client) updateHeartbeat() {
c.heartbeatMux.Lock()
defer c.heartbeatMux.Unlock()
c.heartbeat = time.Now().Add(c.parameters.HeartbeatTimeout)
}
func (c *Client) listenDisconnect() {
select {
case e := <-c.asynchronous.Done():
log.Printf("socket disconnect")
if e != nil {
log.Printf("socket disconnect: %s", e.Error())
}
c.setIsConnected(false)
err := c.reconnect(e)
if err != nil {
log.Printf("socket disconnect: %s", err.Error())
}
case <-c.shutdown:
log.Printf("Shutdown listen disconnect")
c.setIsConnected(false)
return
case e := <-c.listenHeartbeat():
log.Printf("Heartbeat")
if e != nil {
c.closeAsyncAndWait(c.parameters.ShutdownTimeout)
err := c.reconnect(nil)
if err != nil {
log.Printf("socket disconnect: %s", err.Error())
}
}
c.setIsConnected(false)
}
}
func (c *Client) dumpParams() {
log.Print("----Kraken Client Parameters----")
log.Printf("AutoReconnect=%t", c.parameters.AutoReconnect)
log.Printf("ReconnectInterval=%s", c.parameters.ReconnectInterval)
log.Printf("ReconnectAttempts=%d", c.parameters.ReconnectAttempts)
log.Printf("ShutdownTimeout=%s", c.parameters.ShutdownTimeout)
log.Printf("ResubscribeOnReconnect=%t", c.parameters.ResubscribeOnReconnect)
log.Printf("HeartbeatTimeout=%s", c.parameters.HeartbeatTimeout)
log.Printf("URL=%s", c.parameters.URL)
}
func (c *Client) reset() {
if c.asynchronous == nil {
c.asynchronous = c.asyncFactory.Create()
c.init = true
}
c.updateHeartbeat()
go c.listenDisconnect()
go c.listenUpstream()
go c.controlHeartbeat()
}
func (c *Client) connect() error {
err := c.asynchronous.Connect()
c.setIsConnected(err == nil)
return err
}
func (c *Client) resubscribe() error {
ctx := context.Background()
for _, sub := range c.subscriptions {
s := SubscriptionRequest{
Event: EventSubscribe,
Pairs: []string{sub.Pair},
Subscription: sub.Subscription,
}
err := c.asynchronous.Send(ctx, s)
if err != nil {
log.Println(err)
return err
}
}
return nil
}
func (c *Client) reconnect(err error) error {
if c.terminal {
return c.exit(err)
}
if !c.parameters.AutoReconnect {
s := "Empty error"
if err != nil {
s = err.Error()
}
return c.exit(fmt.Errorf("AutoReconnect setting is disabled, do not reconnect: %s", s))
}
reconnectTry := 0
for ; reconnectTry < c.parameters.ReconnectAttempts; reconnectTry++ {
log.Printf("waiting %s until reconnect...", c.parameters.ReconnectInterval)
time.Sleep(c.parameters.ReconnectInterval)
log.Printf("reconnect attempt %d/%d", reconnectTry+1, c.parameters.ReconnectAttempts)
c.reset()
if err = c.connect(); err == nil {
err = c.resubscribe()
if err == nil {
log.Print("reconnect OK")
return nil
}
log.Printf("reconnect failed: %s", err.Error())
return c.exit(err)
}
log.Printf("reconnect failed: %s", err.Error())
}
if err != nil {
log.Printf("could not reconnect: %s", err.Error())
}
return c.exit(err)
}
func (c *Client) exit(err error) error {
c.terminal = true
c.close(err)
return err
}
func (c *Client) listenUpstream() {
for {
select {
case <-c.shutdown:
log.Printf("Shutdown listen upstream")
return
case msg := <-c.asynchronous.Listen():
if msg != nil {
// log.Printf("[DEBUG]: %s\n", msg)
err := c.handleMessage(msg)
if err != nil {
log.Printf("[WARN]: %s\n", err)
}
}
}
}
}
func (c *Client) close(e error) {
if c.listener != nil {
if e != nil {
c.listener <- e
}
close(c.listener)
}
if c.shutdown != nil {
close(c.shutdown)
}
}
func (c *Client) closeAsyncAndWait(t time.Duration) {
if !c.init {
return
}
timeout := make(chan bool)
c.waitGroup.Add(1)
go func() {
select {
case <-c.asynchronous.Done():
c.waitGroup.Done()
case <-timeout:
c.waitGroup.Done()
}
}()
c.asynchronous.Close()
go func() {
time.Sleep(t)
close(timeout)
}()
c.waitGroup.Wait()
}
func (c *Client) handleMessage(msg []byte) (err error) {
t := bytes.TrimLeftFunc(msg, unicode.IsSpace)
c.updateHeartbeat()
if bytes.HasPrefix(t, []byte("[")) {
err = c.handleChannel(msg)
} else if bytes.HasPrefix(t, []byte("{")) {
err = c.handleEvent(msg)
} else {
return fmt.Errorf("unexpected message: %s", msg)
}
return err
}
func (c *Client) createFactories() {
c.createFactory(ChanTicker, newTickerFactory())
c.createFactory(ChanCandles, newCandlesFactory())
c.createFactory(ChanTrades, newTradesFactory())
c.createFactory(ChanSpread, newSpreadFactory())
c.createFactory(ChanBook, newBookFactory())
}
func (c *Client) createFactory(name string, factory ParseFactory) {
c.factories[name] = factory
}
func (c *Client) handleEvent(msg []byte) error {
event := &EventType{}
err := json.Unmarshal(msg, event)
if err != nil {
return err
}
switch event.Event {
case EventPong:
pong := PongResponse{}
err = json.Unmarshal(msg, &pong)
if err != nil {
return err
}
log.Print("Pong received")
case EventSystemStatus:
systemStatus := SystemStatus{}
err = json.Unmarshal(msg, &systemStatus)
if err != nil {
return err
}
log.Printf("Status: %s", systemStatus.Status)
log.Printf("Connection ID: %s", systemStatus.ConnectionID.String())
log.Printf("Version: %s", systemStatus.Version)
case EventSubscriptionStatus:
status := SubscriptionStatus{}
err = json.Unmarshal(msg, &status)
if err != nil {
return err
}
if status.Status == SubscriptionStatusError {
log.Printf("[ERROR] %s: %s", status.Error, status.Pair)
} else {
log.Printf("\tStatus: %s", status.Status)
log.Printf("\tPair: %s", status.Pair)
log.Printf("\tSubscription: %s", status.Subscription.Name)
log.Printf("\tChannel ID: %d", status.ChannelID)
log.Printf("\tReq ID: %s", status.ReqID)
if status.Status == SubscriptionStatusSubscribed {
c.subscriptions[status.ChannelID] = &status
} else if status.Status == SubscriptionStatusUnsubscribed {
delete(c.subscriptions, status.ChannelID)
}
}
case EventCancelOrderStatus:
cancelOrderResponse := CancelOrderResponse{}
err = json.Unmarshal(msg, &cancelOrderResponse)
if err != nil {
return err
}
if cancelOrderResponse.Status == StatusError {
log.Printf("[ERROR] %s", cancelOrderResponse.ErrorMessage)
} else if cancelOrderResponse.Status == StatusOK {
log.Print("[INFO] Order successfully cancelled")
c.listener <- DataUpdate{
ChannelName: EventCancelOrder,
Data: cancelOrderResponse,
}
} else {
log.Printf("[ERROR] Unknown status: %s", cancelOrderResponse.Status)
}
case EventAddOrderStatus:
addOrderResponse := AddOrderResponse{}
err = json.Unmarshal(msg, &addOrderResponse)
if err != nil {
return err
}
if addOrderResponse.Status == StatusError {
log.Printf("[ERROR] %s", addOrderResponse.ErrorMessage)
} else if addOrderResponse.Status == StatusOK {
log.Print("[INFO] Order successfully sent")
c.listener <- DataUpdate{
ChannelName: EventAddOrder,
Data: addOrderResponse,
}
} else {
log.Printf("[ERROR] Unknown status: %s", addOrderResponse.Status)
}
case EventHeartbeat:
default:
fmt.Printf("unknown event: %s", msg)
}
return nil
}
func (c *Client) handleChannel(msg []byte) error {
var data DataUpdate
err := json.Unmarshal(msg, &data)
if err != nil {
return err
}
channel := strings.Split(data.ChannelName, "-")[0]
factory, ok := c.factories[channel]
if !ok {
return fmt.Errorf("Unknown message type: %s", data.ChannelName)
}
result, err := factory.Parse(data.Data, data.Pair)
if err != nil {
return err
}
data.Data = result
c.listener <- data
return nil
}
// IsConnected returns true if the underlying asynchronous transport is connected to an endpoint.
func (c *Client) IsConnected() bool {
c.isConnectedMux.Lock()
defer c.isConnectedMux.Unlock()
return c.isConnected
}
func (c *Client) setIsConnected(value bool) {
c.isConnectedMux.Lock()
defer c.isConnectedMux.Unlock()
c.isConnected = true
}
// Connect to the Kraken API, this should only be called once.
func (c *Client) Connect() error {
c.dumpParams()
c.reset()
return c.connect()
}
// Listen provides an atomic interface for receiving API messages.
// When a websocket connection is terminated, the publisher channel will close.
func (c *Client) Listen() <-chan interface{} {
return c.listener
}
// Close provides an interface for a user initiated shutdown.
func (c *Client) Close() {
c.terminal = true
c.closeAsyncAndWait(c.parameters.ShutdownTimeout)
timeout := make(chan bool)
go func() {
time.Sleep(c.parameters.ShutdownTimeout)
close(timeout)
}()
select {
case <-c.shutdown:
return // successful cleanup
case <-timeout:
log.Print("shutdown timed out")
return
}
}
// SubscribeTicker - Ticker information includes best ask and best bid prices, 24hr volume, last trade price, volume weighted average price, etc for a given currency pair. A ticker message is published every time a trade or a group of trade happens.
func (c *Client) SubscribeTicker(pairs []string) error {
ctx, cxl := context.WithTimeout(context.Background(), c.parameters.ContextTimeout)
defer cxl()
s := SubscriptionRequest{
Event: EventSubscribe,
Pairs: pairs,
Subscription: Subscription{
Name: ChanTicker,
},
}
return c.asynchronous.Send(ctx, s)
}
// SubscribeCandles - Open High Low Close (Candle) feed for a currency pair and interval period.
func (c *Client) SubscribeCandles(pairs []string, interval int64) error {
ctx, cxl := context.WithTimeout(context.Background(), c.parameters.ContextTimeout)
defer cxl()
s := SubscriptionRequest{
Event: EventSubscribe,
Pairs: pairs,
Subscription: Subscription{
Name: ChanCandles,
Interval: interval,
},
}
return c.asynchronous.Send(ctx, s)
}
// SubscribeTrades - Trade feed for a currency pair.
func (c *Client) SubscribeTrades(pairs []string) error {
ctx, cxl := context.WithTimeout(context.Background(), c.parameters.ContextTimeout)
defer cxl()
s := SubscriptionRequest{
Event: EventSubscribe,
Pairs: pairs,
Subscription: Subscription{
Name: ChanTrades,
},
}
return c.asynchronous.Send(ctx, s)
}
// SubscribeSpread - Spread feed to show best bid and ask price for a currency pair
func (c *Client) SubscribeSpread(pairs []string) error {
ctx, cxl := context.WithTimeout(context.Background(), c.parameters.ContextTimeout)
defer cxl()
s := SubscriptionRequest{
Event: EventSubscribe,
Pairs: pairs,
Subscription: Subscription{
Name: ChanSpread,
},
}
return c.asynchronous.Send(ctx, s)
}
// SubscribeBook - Order book levels. On subscription, a snapshot will be published at the specified depth, following the snapshot, level updates will be published.
func (c *Client) SubscribeBook(pairs []string, depth int64) error {
ctx, cxl := context.WithTimeout(context.Background(), c.parameters.ContextTimeout)
defer cxl()
s := SubscriptionRequest{
Event: EventSubscribe,
Pairs: pairs,
Subscription: Subscription{
Name: ChanBook,
Depth: depth,
},
}
return c.asynchronous.Send(ctx, s)
}
// Unsubscribe - Unsubscribe from single subscription, can specify multiple currency pairs.
func (c *Client) Unsubscribe(channelType string, pairs []string) error {
ctx, cxl := context.WithTimeout(context.Background(), c.parameters.ContextTimeout)
defer cxl()
u := UnsubscribeRequest{
Event: EventUnsubscribe,
Pairs: pairs,
Subscription: Subscription{
Name: channelType,
},
}
return c.asynchronous.Send(ctx, u)
}
// Ping - Client can ping server to determine whether connection is alive, server responds with pong. This is an application level ping as opposed to default ping in WebSockets standard which is server initiated
func (c *Client) Ping() error {
ctx, cxl := context.WithTimeout(context.Background(), c.parameters.ContextTimeout)
defer cxl()
ping := PingRequest{
Event: EventPing,
}
return c.asynchronous.Send(ctx, ping)
}