-
Notifications
You must be signed in to change notification settings - Fork 74
/
websocket_service.go
848 lines (759 loc) · 28.7 KB
/
websocket_service.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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
package binance_connector
import (
"fmt"
"strconv"
"strings"
"time"
"encoding/json"
)
type PriceLevel struct {
Price string
Quantity string
}
// Parse parses this PriceLevel's Price and Quantity and
// returns them both. It also returns an error if either
// fails to parse.
func (p *PriceLevel) Parse() (float64, float64, error) {
price, err := strconv.ParseFloat(p.Price, 64)
if err != nil {
return 0, 0, err
}
quantity, err := strconv.ParseFloat(p.Quantity, 64)
if err != nil {
return price, 0, err
}
return price, quantity, nil
}
// Ask is a type alias for PriceLevel.
type Ask = PriceLevel
// Bid is a type alias for PriceLevel.
type Bid = PriceLevel
const (
UserDataEventTypeOutboundAccountPosition UserDataEventType = "outboundAccountPosition"
UserDataEventTypeBalanceUpdate UserDataEventType = "balanceUpdate"
UserDataEventTypeExecutionReport UserDataEventType = "executionReport"
UserDataEventTypeListStatus UserDataEventType = "ListStatus"
)
var (
// WebsocketTimeout is an interval for sending ping/pong messages if WebsocketKeepalive is enabled
WebsocketTimeout = time.Second * 60
// WebsocketKeepalive enables sending ping/pong messages to check the connection stability
WebsocketKeepalive = false
)
// WsPartialDepthEvent define websocket partial depth book event
type WsPartialDepthEvent struct {
Symbol string
LastUpdateID int64 `json:"lastUpdateId"`
Bids []Bid `json:"bids"`
Asks []Ask `json:"asks"`
}
// WsPartialDepthHandler handle websocket partial depth event
type WsPartialDepthHandler func(event *WsPartialDepthEvent)
// WsPartialDepthServe serve websocket partial depth handler with a symbol, using 1sec updates
func (c *WebsocketStreamClient) WsPartialDepthServe(symbol string, levels string, handler WsPartialDepthHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@depth%s", c.Endpoint, strings.ToLower(symbol), levels)
return wsPartialDepthServe(endpoint, symbol, handler, errHandler)
}
// WsPartialDepthServe100Ms serve websocket partial depth handler with a symbol, using 100msec updates
func (c *WebsocketStreamClient) WsPartialDepthServe100Ms(symbol string, levels string, handler WsPartialDepthHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@depth%s@100ms", c.Endpoint, strings.ToLower(symbol), levels)
return wsPartialDepthServe(endpoint, symbol, handler, errHandler)
}
// WsPartialDepthServe serve websocket partial depth handler with a symbol
func wsPartialDepthServe(endpoint string, symbol string, handler WsPartialDepthHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
j, err := newJSON(message)
if err != nil {
errHandler(err)
return
}
event := new(WsPartialDepthEvent)
event.Symbol = symbol
event.LastUpdateID = j.Get("lastUpdateId").MustInt64()
bidsLen := len(j.Get("bids").MustArray())
event.Bids = make([]Bid, bidsLen)
for i := 0; i < bidsLen; i++ {
item := j.Get("bids").GetIndex(i)
event.Bids[i] = Bid{
Price: item.GetIndex(0).MustString(),
Quantity: item.GetIndex(1).MustString(),
}
}
asksLen := len(j.Get("asks").MustArray())
event.Asks = make([]Ask, asksLen)
for i := 0; i < asksLen; i++ {
item := j.Get("asks").GetIndex(i)
event.Asks[i] = Ask{
Price: item.GetIndex(0).MustString(),
Quantity: item.GetIndex(1).MustString(),
}
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsCombinedPartialDepthServe is similar to WsPartialDepthServe, but it for multiple symbols
func (c *WebsocketStreamClient) WsCombinedPartialDepthServe(symbolLevels map[string]string, handler WsPartialDepthHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := c.Endpoint
for s, l := range symbolLevels {
endpoint += fmt.Sprintf("%s@depth%s", strings.ToLower(s), l) + "/"
}
endpoint = endpoint[:len(endpoint)-1]
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
j, err := newJSON(message)
if err != nil {
errHandler(err)
return
}
event := new(WsPartialDepthEvent)
stream := j.Get("stream").MustString()
symbol := strings.Split(stream, "@")[0]
event.Symbol = strings.ToUpper(symbol)
data := j.Get("data").MustMap()
event.LastUpdateID, _ = data["lastUpdateId"].(json.Number).Int64()
bidsLen := len(data["bids"].([]interface{}))
event.Bids = make([]Bid, bidsLen)
for i := 0; i < bidsLen; i++ {
item := data["bids"].([]interface{})[i].([]interface{})
event.Bids[i] = Bid{
Price: item[0].(string),
Quantity: item[1].(string),
}
}
asksLen := len(data["asks"].([]interface{}))
event.Asks = make([]Ask, asksLen)
for i := 0; i < asksLen; i++ {
item := data["asks"].([]interface{})[i].([]interface{})
event.Asks[i] = Ask{
Price: item[0].(string),
Quantity: item[1].(string),
}
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsDepthHandler handle websocket depth event
type WsDepthHandler func(event *WsDepthEvent)
// WsDepthServe serve websocket depth handler with a symbol, using 1sec updates
func (c *WebsocketStreamClient) WsDepthServe(symbol string, handler WsDepthHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@depth", c.Endpoint, strings.ToLower(symbol))
return wsDepthServe(endpoint, handler, errHandler)
}
// WsDepthServe100Ms serve websocket depth handler with a symbol, using 100msec updates
func (c *WebsocketStreamClient) WsDepthServe100Ms(symbol string, handler WsDepthHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@depth@100ms", c.Endpoint, strings.ToLower(symbol))
return wsDepthServe(endpoint, handler, errHandler)
}
// WsDepthServe serve websocket depth handler with an arbitrary endpoint address
func wsDepthServe(endpoint string, handler WsDepthHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
j, err := newJSON(message)
if err != nil {
errHandler(err)
return
}
event := new(WsDepthEvent)
event.Event = j.Get("e").MustString()
event.Time = j.Get("E").MustInt64()
event.Symbol = j.Get("s").MustString()
event.FirstUpdateID = j.Get("U").MustInt64()
event.LastUpdateID = j.Get("u").MustInt64()
bidsLen := len(j.Get("b").MustArray())
event.Bids = make([]Bid, bidsLen)
for i := 0; i < bidsLen; i++ {
item := j.Get("b").GetIndex(i)
event.Bids[i] = Bid{
Price: item.GetIndex(0).MustString(),
Quantity: item.GetIndex(1).MustString(),
}
}
asksLen := len(j.Get("a").MustArray())
event.Asks = make([]Ask, asksLen)
for i := 0; i < asksLen; i++ {
item := j.Get("a").GetIndex(i)
event.Asks[i] = Ask{
Price: item.GetIndex(0).MustString(),
Quantity: item.GetIndex(1).MustString(),
}
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsDepthEvent define websocket depth event
type WsDepthEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Symbol string `json:"s"`
FirstUpdateID int64 `json:"U"`
LastUpdateID int64 `json:"u"`
Bids []Bid `json:"b"`
Asks []Ask `json:"a"`
}
// WsCombinedDepthServe is similar to WsDepthServe, but it for multiple symbols
func (c *WebsocketStreamClient) WsCombinedDepthServe(symbols []string, handler WsDepthHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := c.Endpoint
for _, s := range symbols {
endpoint += fmt.Sprintf("%s@depth", strings.ToLower(s)) + "/"
}
endpoint = endpoint[:len(endpoint)-1]
return wsCombinedDepthServe(endpoint, handler, errHandler)
}
func (c *WebsocketStreamClient) WsCombinedDepthServe100Ms(symbols []string, handler WsDepthHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := c.Endpoint
for _, s := range symbols {
endpoint += fmt.Sprintf("%s@depth@100ms", strings.ToLower(s)) + "/"
}
endpoint = endpoint[:len(endpoint)-1]
return wsCombinedDepthServe(endpoint, handler, errHandler)
}
func wsCombinedDepthServe(endpoint string, handler WsDepthHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
j, err := newJSON(message)
if err != nil {
errHandler(err)
return
}
event := new(WsDepthEvent)
stream := j.Get("stream").MustString()
symbol := strings.Split(stream, "@")[0]
event.Symbol = strings.ToUpper(symbol)
data := j.Get("data").MustMap()
event.Time, _ = data["E"].(json.Number).Int64()
event.LastUpdateID, _ = data["u"].(json.Number).Int64()
event.FirstUpdateID, _ = data["U"].(json.Number).Int64()
bidsLen := len(data["b"].([]interface{}))
event.Bids = make([]Bid, bidsLen)
for i := 0; i < bidsLen; i++ {
item := data["b"].([]interface{})[i].([]interface{})
event.Bids[i] = Bid{
Price: item[0].(string),
Quantity: item[1].(string),
}
}
asksLen := len(data["a"].([]interface{}))
event.Asks = make([]Ask, asksLen)
for i := 0; i < asksLen; i++ {
item := data["a"].([]interface{})[i].([]interface{})
event.Asks[i] = Ask{
Price: item[0].(string),
Quantity: item[1].(string),
}
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsKlineHandler handle websocket kline event
type WsKlineHandler func(event *WsKlineEvent)
// WsCombinedKlineServe is similar to WsKlineServe, but it handles multiple symbols with it interval
func (c *WebsocketStreamClient) WsCombinedKlineServe(symbolIntervalPair map[string]string, handler WsKlineHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := c.Endpoint
for symbol, interval := range symbolIntervalPair {
endpoint += fmt.Sprintf("%s@kline_%s", strings.ToLower(symbol), interval) + "/"
}
endpoint = endpoint[:len(endpoint)-1]
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
j, err := newJSON(message)
if err != nil {
errHandler(err)
return
}
stream := j.Get("stream").MustString()
data := j.Get("data").MustMap()
symbol := strings.Split(stream, "@")[0]
jsonData, _ := json.Marshal(data)
event := new(WsKlineEvent)
err = json.Unmarshal(jsonData, event)
if err != nil {
errHandler(err)
return
}
event.Symbol = strings.ToUpper(symbol)
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsKlineServe serve websocket kline handler with a symbol and interval like 15m, 30s
func (c *WebsocketStreamClient) WsKlineServe(symbol string, interval string, handler WsKlineHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@kline_%s", c.Endpoint, strings.ToLower(symbol), interval)
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsKlineEvent)
err := json.Unmarshal(message, event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsKlineEvent define websocket kline event
type WsKlineEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Symbol string `json:"s"`
Kline WsKline `json:"k"`
}
// WsKline define websocket kline
type WsKline struct {
StartTime int64 `json:"t"`
EndTime int64 `json:"T"`
Symbol string `json:"s"`
Interval string `json:"i"`
FirstTradeID int64 `json:"f"`
LastTradeID int64 `json:"L"`
Open string `json:"o"`
Close string `json:"c"`
High string `json:"h"`
Low string `json:"l"`
Volume string `json:"v"`
TradeNum int64 `json:"n"`
IsFinal bool `json:"x"`
QuoteVolume string `json:"q"`
ActiveBuyVolume string `json:"V"`
ActiveBuyQuoteVolume string `json:"Q"`
}
// WsAggTradeHandler handle websocket aggregate trade event
type WsAggTradeHandler func(event *WsAggTradeEvent)
// WsAggTradeServe serve websocket aggregate handler with a symbol
func (c *WebsocketStreamClient) WsAggTradeServe(symbol string, handler WsAggTradeHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@aggTrade", c.Endpoint, strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsAggTradeEvent)
err := json.Unmarshal(message, event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsCombinedAggTradeServe is similar to WsAggTradeServe, but it handles multiple symbolx
func (c *WebsocketStreamClient) WsCombinedAggTradeServe(symbols []string, handler WsAggTradeHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := c.Endpoint
for s := range symbols {
endpoint += fmt.Sprintf("%s@aggTrade", strings.ToLower(symbols[s])) + "/"
}
endpoint = endpoint[:len(endpoint)-1]
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
j, err := newJSON(message)
if err != nil {
errHandler(err)
return
}
stream := j.Get("stream").MustString()
data := j.Get("data").MustMap()
symbol := strings.Split(stream, "@")[0]
jsonData, _ := json.Marshal(data)
event := new(WsAggTradeEvent)
err = json.Unmarshal(jsonData, event)
if err != nil {
errHandler(err)
return
}
event.Symbol = strings.ToUpper(symbol)
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsAggTradeEvent define websocket aggregate trade event
type WsAggTradeEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Symbol string `json:"s"`
AggTradeID int64 `json:"a"`
Price string `json:"p"`
Quantity string `json:"q"`
FirstBreakdownTradeID int64 `json:"f"`
LastBreakdownTradeID int64 `json:"l"`
TradeTime int64 `json:"T"`
IsBuyerMaker bool `json:"m"`
Placeholder bool `json:"M"` // add this field to avoid case insensitive unmarshaling
}
// WsTradeHandler handle websocket trade event
type WsTradeHandler func(event *WsTradeEvent)
type WsCombinedTradeHandler func(event *WsCombinedTradeEvent)
// WsTradeServe serve websocket handler with a symbol
func (c *WebsocketStreamClient) WsTradeServe(symbol string, handler WsTradeHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@trade", c.Endpoint, strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsTradeEvent)
err := json.Unmarshal(message, event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
func (c *WebsocketStreamClient) WsCombinedTradeServe(symbols []string, handler WsCombinedTradeHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := c.Endpoint
for _, s := range symbols {
endpoint += fmt.Sprintf("%s@trade/", strings.ToLower(s))
}
endpoint = endpoint[:len(endpoint)-1]
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsCombinedTradeEvent)
err := json.Unmarshal(message, event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsTradeEvent define websocket trade event
type WsTradeEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Symbol string `json:"s"`
TradeID int64 `json:"t"`
Price string `json:"p"`
Quantity string `json:"q"`
BuyerOrderId int64 `json:"b"`
SellerOrderId int64 `json:"a"`
TradeTime int64 `json:"T"`
IsBuyerMaker bool `json:"m"`
Placeholder bool `json:"M"` // add this field to avoid case insensitive unmarshaling
}
type WsCombinedTradeEvent struct {
Stream string `json:"stream"`
Data WsTradeEvent `json:"data"`
}
// WsUserDataEvent define user data event
type WsUserDataEvent struct {
Event UserDataEventType `json:"e"`
Time int64 `json:"E"`
TransactionTime int64 `json:"T"`
AccountUpdateTime int64 `json:"u"`
AccountUpdate WsAccountUpdateList
BalanceUpdate WsBalanceUpdate
OrderUpdate WsOrderUpdate
OCOUpdate WsOCOUpdate
}
type WsAccountUpdateList struct {
WsAccountUpdates []WsAccountUpdate `json:"B"`
}
// WsAccountUpdate define account update
type WsAccountUpdate struct {
Asset string `json:"a"`
Free string `json:"f"`
Locked string `json:"l"`
}
type WsBalanceUpdate struct {
Asset string `json:"a"`
Change string `json:"d"`
}
type WsOrderUpdate struct {
Symbol string `json:"s"`
ClientOrderId string `json:"c"`
Side string `json:"S"`
Type string `json:"o"`
TimeInForce TimeInForceType `json:"f"`
Volume string `json:"q"`
Price string `json:"p"`
StopPrice string `json:"P"`
TrailingDelta int64 `json:"d"` // Trailing Delta
IceBergVolume string `json:"F"`
OrderListId int64 `json:"g"` // for OCO
OrigCustomOrderId string `json:"C"` // customized order ID for the original order
ExecutionType string `json:"x"` // execution type for this event NEW/TRADE...
Status string `json:"X"` // order status
RejectReason string `json:"r"`
Id int64 `json:"i"` // order id
LatestVolume string `json:"l"` // quantity for the latest trade
FilledVolume string `json:"z"`
LatestPrice string `json:"L"` // price for the latest trade
FeeAsset string `json:"N"`
FeeCost string `json:"n"`
TransactionTime int64 `json:"T"`
TradeId int64 `json:"t"`
IsInOrderBook bool `json:"w"` // is the order in the order book?
IsMaker bool `json:"m"` // is this order maker?
CreateTime int64 `json:"O"`
FilledQuoteVolume string `json:"Z"` // the quote volume that already filled
LatestQuoteVolume string `json:"Y"` // the quote volume for the latest trade
QuoteVolume string `json:"Q"`
TrailingTime int64 `json:"D"` // Trailing Time
StrategyId int64 `json:"j"` // Strategy ID
StrategyType int64 `json:"J"` // Strategy Type
WorkingTime int64 `json:"W"` // Working Time
SelfTradePreventionMode string `json:"V"`
}
type WsOCOUpdate struct {
Symbol string `json:"s"`
OrderListId int64 `json:"g"`
ContingencyType string `json:"c"`
ListStatusType string `json:"l"`
ListOrderStatus string `json:"L"`
RejectReason string `json:"r"`
ClientOrderId string `json:"C"` // List Client Order ID
Orders WsOCOOrderList
}
type WsOCOOrderList struct {
WsOCOOrders []WsOCOOrder `json:"O"`
}
type WsOCOOrder struct {
Symbol string `json:"s"`
OrderId int64 `json:"i"`
ClientOrderId string `json:"c"`
}
// WsUserDataHandler handle WsUserDataEvent
type WsUserDataHandler func(event *WsUserDataEvent)
// WsUserDataServe serve user data handler with listen key
func (c *WebsocketStreamClient) WsUserDataServe(listenKey string, handler WsUserDataHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s", c.Endpoint, listenKey)
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
j, err := newJSON(message)
if err != nil {
errHandler(err)
return
}
event := new(WsUserDataEvent)
err = json.Unmarshal(message, event)
if err != nil {
errHandler(err)
return
}
switch UserDataEventType(j.Get("e").MustString()) {
case UserDataEventTypeOutboundAccountPosition:
err = json.Unmarshal(message, &event.AccountUpdate)
if err != nil {
errHandler(err)
return
}
case UserDataEventTypeBalanceUpdate:
err = json.Unmarshal(message, &event.BalanceUpdate)
if err != nil {
errHandler(err)
return
}
case UserDataEventTypeExecutionReport:
err = json.Unmarshal(message, &event.OrderUpdate)
if err != nil {
errHandler(err)
return
}
// Unmarshal has case sensitive problem
event.TransactionTime = j.Get("T").MustInt64()
event.OrderUpdate.TransactionTime = j.Get("T").MustInt64()
event.OrderUpdate.Id = j.Get("i").MustInt64()
event.OrderUpdate.TradeId = j.Get("t").MustInt64()
event.OrderUpdate.FeeAsset = j.Get("N").MustString()
case UserDataEventTypeListStatus:
err = json.Unmarshal(message, &event.OCOUpdate)
if err != nil {
errHandler(err)
return
}
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsMarketTickersStatHandler handle websocket that push single market statistics for 24hr
type WsMarketTickersStatHandler func(event *WsMarketTickerStatEvent)
// WsCombinedMarketTickersStatServe is similar to WsMarketTickersStatServe, but it handles multiple symbols
func (c *WebsocketStreamClient) WsCombinedMarketTickersStatServe(symbols []string, handler WsMarketTickersStatHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := c.Endpoint
for s := range symbols {
endpoint += fmt.Sprintf("%s@ticker", strings.ToLower(symbols[s])) + "/"
}
endpoint = endpoint[:len(endpoint)-1]
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
j, err := newJSON(message)
if err != nil {
errHandler(err)
return
}
stream := j.Get("stream").MustString()
data := j.Get("data").MustMap()
symbol := strings.Split(stream, "@")[0]
jsonData, _ := json.Marshal(data)
event := new(WsMarketTickerStatEvent)
err = json.Unmarshal(jsonData, event)
if err != nil {
errHandler(err)
return
}
event.Symbol = strings.ToUpper(symbol)
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsMarketTickersStatServe serve websocket that push 24hr statistics for single market every second
func (c *WebsocketStreamClient) WsMarketTickersStatServe(symbol string, handler WsMarketTickersStatHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@ticker", c.Endpoint, strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
var event WsMarketTickerStatEvent
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(&event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsAllMarketTickersStatHandler handle websocket that push all markets statistics for 24hr
type WsAllMarketTickersStatHandler func(event WsAllMarketTickersStatEvent)
// WsAllMarketTickersStatServe serve websocket that push 24hr statistics for all market every second
func (c *WebsocketStreamClient) WsAllMarketTickersStatServe(handler WsAllMarketTickersStatHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/!ticker@arr", c.Endpoint)
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
var event WsAllMarketTickersStatEvent
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsAllMarketTickersStatEvent define array of websocket market statistics events
type WsAllMarketTickersStatEvent []*WsMarketTickerStatEvent
// WsMarketTickerStatEvent define websocket market statistics event
type WsMarketTickerStatEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Symbol string `json:"s"`
PriceChange string `json:"p"`
PriceChangePercent string `json:"P"`
WeightedAvgPrice string `json:"w"`
PrevClosePrice string `json:"x"`
LastPrice string `json:"c"`
CloseQty string `json:"Q"`
BidPrice string `json:"b"`
BidQty string `json:"B"`
AskPrice string `json:"a"`
AskQty string `json:"A"`
OpenPrice string `json:"o"`
HighPrice string `json:"h"`
LowPrice string `json:"l"`
BaseVolume string `json:"v"`
QuoteVolume string `json:"q"`
OpenTime int64 `json:"O"`
CloseTime int64 `json:"C"`
FirstID int64 `json:"F"`
LastID int64 `json:"L"`
Count int64 `json:"n"`
}
// WsAllMarketMiniTickersStatServeHandler handle websocket that push all mini-ticker market statistics for 24hr
type WsAllMarketMiniTickersStatServeHandler func(event WsAllMarketMiniTickersStatEvent)
// WsAllMarketMiniTickersStatServe serve websocket that push mini version of 24hr statistics for all market every second
func (c *WebsocketStreamClient) WsAllMarketMiniTickersStatServe(handler WsAllMarketMiniTickersStatServeHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/!miniTicker@arr", c.Endpoint)
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
var event WsAllMarketMiniTickersStatEvent
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsAllMarketMiniTickersStatEvent define array of websocket market mini-ticker statistics events
type WsAllMarketMiniTickersStatEvent []*WsMarketMiniStatEvent
// WsMarketMiniTickersStatHandler handle websocket that push single market statistics for 24hr
type WsMarketMiniTickersStatHandler func(event WsMarketMiniTickerStatEvent)
// WsMarketMiniTickersStatServe serve websocket that push mini version of 24hr statistics for single market every second
func (c *WebsocketStreamClient) WsMarketMiniTickersStatServe(symbol string, handler WsMarketMiniTickersStatHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@miniTicker", c.Endpoint, strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
var event WsMarketMiniTickerStatEvent
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsMarketMiniTickerStatEvent define array of websocket market mini-ticker statistics events
type WsMarketMiniTickerStatEvent *WsMarketMiniStatEvent
// WsMarketMiniStatEvent define websocket market mini-ticker statistics event
type WsMarketMiniStatEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Symbol string `json:"s"`
LastPrice string `json:"c"`
OpenPrice string `json:"o"`
HighPrice string `json:"h"`
LowPrice string `json:"l"`
BaseVolume string `json:"v"`
QuoteVolume string `json:"q"`
}
// WsBookTickerEvent define websocket best book ticker event.
type WsBookTickerEvent struct {
UpdateID int64 `json:"u"`
Symbol string `json:"s"`
BestBidPrice string `json:"b"`
BestBidQty string `json:"B"`
BestAskPrice string `json:"a"`
BestAskQty string `json:"A"`
}
type WsCombinedBookTickerEvent struct {
Data *WsBookTickerEvent `json:"data"`
Stream string `json:"stream"`
}
// WsBookTickerHandler handle websocket that pushes updates to the best bid or ask price or quantity in real-time for a specified symbol.
type WsBookTickerHandler func(event *WsBookTickerEvent)
// WsBookTickerServe serve websocket that pushes updates to the best bid or ask price or quantity in real-time for a specified symbol.
func (c *WebsocketStreamClient) WsBookTickerServe(symbol string, handler WsBookTickerHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@bookTicker", c.Endpoint, strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsBookTickerEvent)
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsCombinedBookTickerServe is similar to WsBookTickerServe, but it is for multiple symbols
func (c *WebsocketStreamClient) WsCombinedBookTickerServe(symbols []string, handler WsBookTickerHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
endpoint := c.Endpoint
for _, s := range symbols {
endpoint += fmt.Sprintf("%s@bookTicker", strings.ToLower(s)) + "/"
}
endpoint = endpoint[:len(endpoint)-1]
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsCombinedBookTickerEvent)
err := json.Unmarshal(message, event)
if err != nil {
errHandler(err)
return
}
handler(event.Data)
}
return wsServe(cfg, wsHandler, errHandler)
}