forked from adshao/go-binance
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket_service.go
737 lines (667 loc) · 26.1 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
package futures
import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
)
// Endpoints
const (
baseWsMainUrl = "wss://fstream.binance.com/ws"
baseWsTestnetUrl = "wss://stream.binancefuture.com/ws"
)
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
// UseTestnet switch all the WS streams from production to the testnet
UseTestnet = false
)
// getWsEndpoint return the base endpoint of the WS according the UseTestnet flag
func getWsEndpoint() string {
if UseTestnet {
return baseWsTestnetUrl
}
return baseWsMainUrl
}
// WsAggTradeEvent define websocket aggTrde event.
type WsAggTradeEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Symbol string `json:"s"`
AggregateTradeID int64 `json:"a"`
Price string `json:"p"`
Quantity string `json:"q"`
FirstTradeID int64 `json:"f"`
LastTradeID int64 `json:"l"`
TradeTime int64 `json:"T"`
Maker bool `json:"m"`
}
// WsAggTradeHandler handle websocket that push trade information that is aggregated for a single taker order.
type WsAggTradeHandler func(event *WsAggTradeEvent)
// WsAggTradeServe serve websocket that push trade information that is aggregated for a single taker order.
func WsAggTradeServe(symbol string, handler WsAggTradeHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@aggTrade", getWsEndpoint(), 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)
}
// WsMarkPriceEvent define websocket markPriceUpdate event.
type WsMarkPriceEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Symbol string `json:"s"`
MarkPrice string `json:"p"`
IndexPrice string `json:"i"`
EstimatedSettlePrice string `json:"P"`
FundingRate string `json:"r"`
NextFundingTime int64 `json:"T"`
}
// WsMarkPriceHandler handle websocket that pushes price and funding rate for a single symbol.
type WsMarkPriceHandler func(event *WsMarkPriceEvent)
func wsMarkPriceServe(endpoint string, handler WsMarkPriceHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsMarkPriceEvent)
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsMarkPriceServe serve websocket that pushes price and funding rate for a single symbol.
func WsMarkPriceServe(symbol string, handler WsMarkPriceHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@markPrice", getWsEndpoint(), strings.ToLower(symbol))
return wsMarkPriceServe(endpoint, handler, errHandler)
}
// WsMarkPriceServeWithRate serve websocket that pushes price and funding rate for a single symbol and rate.
func WsMarkPriceServeWithRate(symbol string, rate time.Duration, handler WsMarkPriceHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
var rateStr string
switch rate {
case 3 * time.Second:
rateStr = ""
case 1 * time.Second:
rateStr = "@1s"
default:
return nil, nil, errors.New("Invalid rate")
}
endpoint := fmt.Sprintf("%s/%s@markPrice%s", getWsEndpoint(), strings.ToLower(symbol), rateStr)
return wsMarkPriceServe(endpoint, handler, errHandler)
}
// WsAllMarkPriceEvent defines an array of websocket markPriceUpdate events.
type WsAllMarkPriceEvent []*WsMarkPriceEvent
// WsAllMarkPriceHandler handle websocket that pushes price and funding rate for all symbol.
type WsAllMarkPriceHandler func(event WsAllMarkPriceEvent)
func wsAllMarkPriceServe(endpoint string, handler WsAllMarkPriceHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
var event WsAllMarkPriceEvent
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsAllMarkPriceServe serve websocket that pushes price and funding rate for all symbol.
func WsAllMarkPriceServe(handler WsAllMarkPriceHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/!markPrice@arr", getWsEndpoint())
return wsAllMarkPriceServe(endpoint, handler, errHandler)
}
// WsAllMarkPriceServeWithRate serve websocket that pushes price and funding rate for all symbol and rate.
func WsAllMarkPriceServeWithRate(rate time.Duration, handler WsAllMarkPriceHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
var rateStr string
switch rate {
case 3 * time.Second:
rateStr = ""
case 1 * time.Second:
rateStr = "@1s"
default:
return nil, nil, errors.New("Invalid rate")
}
endpoint := fmt.Sprintf("%s/!markPrice@arr%s", getWsEndpoint(), rateStr)
return wsAllMarkPriceServe(endpoint, handler, 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"`
}
// WsKlineHandler handle websocket kline event
type WsKlineHandler func(event *WsKlineEvent)
// WsKlineServe serve websocket kline handler with a symbol and interval like 15m, 30s
func WsKlineServe(symbol string, interval string, handler WsKlineHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@kline_%s", getWsEndpoint(), 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)
}
// WsMiniMarketTickerEvent define websocket mini market ticker event.
type WsMiniMarketTickerEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Symbol string `json:"s"`
ClosePrice string `json:"c"`
OpenPrice string `json:"o"`
HighPrice string `json:"h"`
LowPrice string `json:"l"`
Volume string `json:"v"`
QuoteVolume string `json:"q"`
}
// WsMiniMarketTickerHandler handle websocket that pushes 24hr rolling window mini-ticker statistics for a single symbol.
type WsMiniMarketTickerHandler func(event *WsMiniMarketTickerEvent)
// WsMiniMarketTickerServe serve websocket that pushes 24hr rolling window mini-ticker statistics for a single symbol.
func WsMiniMarketTickerServe(symbol string, handler WsMiniMarketTickerHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@miniTicker", getWsEndpoint(), strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsMiniMarketTickerEvent)
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsAllMiniMarketTickerEvent define an array of websocket mini market ticker events.
type WsAllMiniMarketTickerEvent []*WsMiniMarketTickerEvent
// WsAllMiniMarketTickerHandler handle websocket that pushes price and funding rate for all markets.
type WsAllMiniMarketTickerHandler func(event WsAllMiniMarketTickerEvent)
// WsAllMiniMarketTickerServe serve websocket that pushes price and funding rate for all markets.
func WsAllMiniMarketTickerServe(handler WsAllMiniMarketTickerHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/!miniTicker@arr", getWsEndpoint())
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
var event WsAllMiniMarketTickerEvent
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsMarketTickerEvent define websocket market ticker event.
type WsMarketTickerEvent 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"`
ClosePrice string `json:"c"`
CloseQty string `json:"Q"`
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"`
TradeCount int64 `json:"n"`
}
// WsMarketTickerHandler handle websocket that pushes 24hr rolling window mini-ticker statistics for a single symbol.
type WsMarketTickerHandler func(event *WsMarketTickerEvent)
// WsMarketTickerServe serve websocket that pushes 24hr rolling window mini-ticker statistics for a single symbol.
func WsMarketTickerServe(symbol string, handler WsMarketTickerHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@ticker", getWsEndpoint(), strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsMarketTickerEvent)
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsAllMarketTickerEvent define an array of websocket mini ticker events.
type WsAllMarketTickerEvent []*WsMarketTickerEvent
// WsAllMarketTickerHandler handle websocket that pushes price and funding rate for all markets.
type WsAllMarketTickerHandler func(event WsAllMarketTickerEvent)
// WsAllMarketTickerServe serve websocket that pushes price and funding rate for all markets.
func WsAllMarketTickerServe(handler WsAllMarketTickerHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/!ticker@arr", getWsEndpoint())
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
var event WsAllMarketTickerEvent
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsBookTickerEvent define websocket best book ticker event.
type WsBookTickerEvent struct {
Event string `json:"e"`
UpdateID int64 `json:"u"`
Time int64 `json:"E"`
TransactionTime int64 `json:"T"`
Symbol string `json:"s"`
BestBidPrice string `json:"b"`
BestBidQty string `json:"B"`
BestAskPrice string `json:"a"`
BestAskQty string `json:"A"`
}
// 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 WsBookTickerServe(symbol string, handler WsBookTickerHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@bookTicker", getWsEndpoint(), 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)
}
// WsAllBookTickerServe serve websocket that pushes updates to the best bid or ask price or quantity in real-time for all symbols.
func WsAllBookTickerServe(handler WsBookTickerHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/!bookTicker", getWsEndpoint())
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)
}
// WsLiquidationOrderEvent define websocket liquidation order event.
type WsLiquidationOrderEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
LiquidationOrder WsLiquidationOrder `json:"o"`
}
// WsLiquidationOrder define websocket liquidation order.
type WsLiquidationOrder struct {
Symbol string `json:"s"`
Side SideType `json:"S"`
OrderType OrderType `json:"o"`
TimeInForce TimeInForceType `json:"f"`
OrigQuantity string `json:"q"`
Price string `json:"p"`
AvgPrice string `json:"ap"`
OrderStatus OrderStatusType `json:"X"`
LastFilledQty string `json:"l"`
AccumulatedFilledQty string `json:"z"`
TradeTime int64 `json:"T"`
}
// WsLiquidationOrderHandler handle websocket that pushes force liquidation order information for specific symbol.
type WsLiquidationOrderHandler func(event *WsLiquidationOrderEvent)
// WsLiquidationOrderServe serve websocket that pushes force liquidation order information for specific symbol.
func WsLiquidationOrderServe(symbol string, handler WsLiquidationOrderHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@forceOrder", getWsEndpoint(), strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsLiquidationOrderEvent)
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsAllLiquidationOrderServe serve websocket that pushes force liquidation order information for all symbols.
func WsAllLiquidationOrderServe(handler WsLiquidationOrderHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/!forceOrder@arr", getWsEndpoint())
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsLiquidationOrderEvent)
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsDepthEvent define websocket depth book event
type WsDepthEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
TransactionTime int64 `json:"T"`
Symbol string `json:"s"`
FirstUpdateID int64 `json:"U"`
LastUpdateID int64 `json:"u"`
PrevLastUpdateID int64 `json:"pu"`
Bids []Bid `json:"b"`
Asks []Ask `json:"a"`
}
// WsDepthHandler handle websocket depth event
type WsDepthHandler func(event *WsDepthEvent)
func wsPartialDepthServe(symbol string, levels int, rate *time.Duration, handler WsDepthHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
if levels != 5 && levels != 10 && levels != 20 {
return nil, nil, errors.New("Invalid levels")
}
levelsStr := fmt.Sprintf("%d", levels)
return wsDepthServe(symbol, levelsStr, rate, handler, errHandler)
}
// WsPartialDepthServe serve websocket partial depth handler.
func WsPartialDepthServe(symbol string, levels int, handler WsDepthHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
return wsPartialDepthServe(symbol, levels, nil, handler, errHandler)
}
// WsPartialDepthServeWithRate serve websocket partial depth handler with rate.
func WsPartialDepthServeWithRate(symbol string, levels int, rate time.Duration, handler WsDepthHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
return wsPartialDepthServe(symbol, levels, &rate, handler, errHandler)
}
// WsDiffDepthServe serve websocket diff. depth handler.
func WsDiffDepthServe(symbol string, handler WsDepthHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
return wsDepthServe(symbol, "", nil, handler, errHandler)
}
// WsDiffDepthServeWithRate serve websocket diff. depth handler with rate.
func WsDiffDepthServeWithRate(symbol string, rate time.Duration, handler WsDepthHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
return wsDepthServe(symbol, "", &rate, handler, errHandler)
}
func wsDepthServe(symbol string, levels string, rate *time.Duration, handler WsDepthHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
var rateStr string
if rate != nil {
switch *rate {
case 250 * time.Millisecond:
rateStr = ""
case 500 * time.Millisecond:
rateStr = "@500ms"
case 100 * time.Millisecond:
rateStr = "@100ms"
default:
return nil, nil, errors.New("Invalid rate")
}
}
endpoint := fmt.Sprintf("%s/%s@depth%s%s", getWsEndpoint(), strings.ToLower(symbol), levels, rateStr)
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.TransactionTime = j.Get("T").MustInt64()
event.Symbol = j.Get("s").MustString()
event.FirstUpdateID = j.Get("U").MustInt64()
event.LastUpdateID = j.Get("u").MustInt64()
event.PrevLastUpdateID = j.Get("pu").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)
}
// WsBLVTInfoEvent define websocket BLVT info event
type WsBLVTInfoEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Symbol string `json:"s"`
Issued float64 `json:"m"`
Baskets []WsBLVTBasket `json:"b"`
Nav float64 `json:"n"`
Leverage float64 `json:"l"`
TargetLeverage int64 `json:"t"`
FundingRate float64 `json:"f"`
}
// WsBLVTBasket define websocket BLVT basket
type WsBLVTBasket struct {
Symbol string `json:"s"`
Position int64 `json:"n"`
}
// WsBLVTInfoHandler handle websocket BLVT event
type WsBLVTInfoHandler func(event *WsBLVTInfoEvent)
// WsBLVTInfoServe serve BLVT info stream
func WsBLVTInfoServe(name string, handler WsBLVTInfoHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@tokenNav", getWsEndpoint(), strings.ToUpper(name))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsBLVTInfoEvent)
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsBLVTKlineEvent define BLVT kline event
type WsBLVTKlineEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Symbol string `json:"s"`
Kline WsBLVTKline `json:"k"`
}
// WsBLVTKline BLVT kline
type WsBLVTKline struct {
StartTime int64 `json:"t"`
CloseTime int64 `json:"T"`
Symbol string `json:"s"`
Interval string `json:"i"`
FirstUpdateTime int64 `json:"f"`
LastUpdateTime int64 `json:"L"`
OpenPrice string `json:"o"`
ClosePrice string `json:"c"`
HighPrice string `json:"h"`
LowPrice string `json:"l"`
Leverage string `json:"v"`
Count int64 `json:"n"`
}
// WsBLVTKlineHandler BLVT kline handler
type WsBLVTKlineHandler func(event *WsBLVTKlineEvent)
// WsBLVTKlineServe serve BLVT kline stream
func WsBLVTKlineServe(name string, interval string, handler WsBLVTKlineHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@nav_Kline_%s", getWsEndpoint(), strings.ToUpper(name), interval)
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsBLVTKlineEvent)
err := json.Unmarshal(message, event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsCompositeIndexEvent websocket composite index event
type WsCompositeIndexEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Symbol string `json:"s"`
Price string `json:"p"`
Composition []WsComposition `json:"c"`
}
// WsComposition websocket composite index event composition
type WsComposition struct {
BaseAsset string `json:"b"`
WeightQty string `json:"w"`
WeighPercent string `json:"W"`
}
// WsCompositeIndexHandler websocket composite index handler
type WsCompositeIndexHandler func(event *WsCompositeIndexEvent)
// WsCompositiveIndexServe serve composite index information for index symbols
func WsCompositiveIndexServe(symbol string, handler WsCompositeIndexHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@compositeIndex", getWsEndpoint(), strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsCompositeIndexEvent)
err := json.Unmarshal(message, event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsUserDataEvent define user data event
type WsUserDataEvent struct {
Event UserDataEventType `json:"e"`
Time int64 `json:"E"`
CrossWalletBalance string `json:"cw"`
MarginCallPositions []WsPosition `json:"p"`
TransactionTime int64 `json:"T"`
AccountUpdate WsAccountUpdate `json:"a"`
OrderTradeUpdate WsOrderTradeUpdate `json:"o"`
AccountConfigUpdate WsAccountConfigUpdate `json:"ac"`
}
// WsAccountUpdate define account update
type WsAccountUpdate struct {
Reason UserDataEventReasonType `json:"m"`
Balances []WsBalance `json:"B"`
Positions []WsPosition `json:"P"`
}
// WsBalance define balance
type WsBalance struct {
Asset string `json:"a"`
Balance string `json:"wb"`
CrossWalletBalance string `json:"cw"`
}
// WsPosition define position
type WsPosition struct {
Symbol string `json:"s"`
Side PositionSideType `json:"ps"`
Amount string `json:"pa"`
MarginType MarginType `json:"mt"`
IsolatedWallet string `json:"iw"`
EntryPrice string `json:"ep"`
MarkPrice string `json:"mp"`
UnrealizedPnL string `json:"up"`
AccumulatedRealized string `json:"cr"`
MaintenanceMarginRequired string `json:"mm"`
}
// WsOrderTradeUpdate define order trade update
type WsOrderTradeUpdate struct {
Symbol string `json:"s"`
ClientOrderID string `json:"c"`
Side SideType `json:"S"`
Type OrderType `json:"o"`
TimeInForce TimeInForceType `json:"f"`
OriginalQty string `json:"q"`
OriginalPrice string `json:"p"`
AveragePrice string `json:"ap"`
StopPrice string `json:"sp"`
ExecutionType OrderExecutionType `json:"x"`
Status OrderStatusType `json:"X"`
ID int64 `json:"i"`
LastFilledQty string `json:"l"`
AccumulatedFilledQty string `json:"z"`
LastFilledPrice string `json:"L"`
CommissionAsset string `json:"N"`
Commission string `json:"n"`
TradeTime int64 `json:"T"`
TradeID int64 `json:"t"`
BidsNotional string `json:"b"`
AsksNotional string `json:"a"`
IsMaker bool `json:"m"`
IsReduceOnly bool `json:"R"`
WorkingType WorkingType `json:"wt"`
OriginalType OrderType `json:"ot"`
PositionSide PositionSideType `json:"ps"`
IsClosingPosition bool `json:"cp"`
ActivationPrice string `json:"AP"`
CallbackRate string `json:"cr"`
RealizedPnL string `json:"rp"`
}
// WsAccountConfigUpdate define account config update
type WsAccountConfigUpdate struct {
Symbol string `json:"s"`
Leverage int64 `json:"l"`
}
// WsUserDataHandler handle WsUserDataEvent
type WsUserDataHandler func(event *WsUserDataEvent)
// WsUserDataServe serve user data handler with listen key
func WsUserDataServe(listenKey string, handler WsUserDataHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s", getWsEndpoint(), listenKey)
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsUserDataEvent)
err := json.Unmarshal(message, event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}