2020-07-11 05:02:53 +00:00
|
|
|
package binance
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2020-12-21 06:43:40 +00:00
|
|
|
"math/rand"
|
2021-05-25 11:13:10 +00:00
|
|
|
"net"
|
2021-01-23 08:59:51 +00:00
|
|
|
"os"
|
|
|
|
"strconv"
|
2020-08-07 01:15:50 +00:00
|
|
|
"strings"
|
2021-01-25 05:53:11 +00:00
|
|
|
"sync"
|
2020-07-13 08:03:47 +00:00
|
|
|
"time"
|
|
|
|
|
2021-01-11 05:36:49 +00:00
|
|
|
"github.com/adshao/go-binance/v2"
|
2020-11-10 06:19:33 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
2021-05-18 16:41:34 +00:00
|
|
|
"github.com/gorilla/websocket"
|
2020-11-10 06:19:33 +00:00
|
|
|
|
2020-10-11 08:46:15 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
2020-07-11 05:02:53 +00:00
|
|
|
)
|
|
|
|
|
2021-01-23 08:59:51 +00:00
|
|
|
var debugBinanceDepth bool
|
|
|
|
|
2020-12-21 06:43:40 +00:00
|
|
|
func init() {
|
2020-12-21 09:48:30 +00:00
|
|
|
// randomize pulling
|
2020-12-21 06:43:40 +00:00
|
|
|
rand.Seed(time.Now().UnixNano())
|
2021-01-23 08:59:51 +00:00
|
|
|
|
2021-05-18 16:41:34 +00:00
|
|
|
debugBinanceDepth, _ = strconv.ParseBool(os.Getenv("DEBUG_BINANCE_DEPTH"))
|
|
|
|
if debugBinanceDepth {
|
|
|
|
log.Info("binance depth debugging is enabled")
|
2021-01-23 08:59:51 +00:00
|
|
|
}
|
2020-12-21 06:43:40 +00:00
|
|
|
}
|
|
|
|
|
2020-07-11 05:02:53 +00:00
|
|
|
type StreamRequest struct {
|
|
|
|
// request ID is required
|
|
|
|
ID int `json:"id"`
|
|
|
|
Method string `json:"method"`
|
|
|
|
Params []string `json:"params"`
|
|
|
|
}
|
|
|
|
|
2020-10-03 10:35:28 +00:00
|
|
|
//go:generate callbackgen -type Stream -interface
|
|
|
|
type Stream struct {
|
2021-01-19 18:09:12 +00:00
|
|
|
types.MarginSettings
|
2020-12-21 09:48:30 +00:00
|
|
|
|
2020-10-03 10:35:28 +00:00
|
|
|
types.StandardStream
|
2020-07-15 13:02:08 +00:00
|
|
|
|
2021-05-27 06:42:14 +00:00
|
|
|
Client *binance.Client
|
|
|
|
ListenKey string
|
|
|
|
Conn *websocket.Conn
|
|
|
|
ConnLock sync.Mutex
|
2021-05-25 11:13:10 +00:00
|
|
|
|
|
|
|
connCtx context.Context
|
|
|
|
connCancel context.CancelFunc
|
2020-07-11 08:07:09 +00:00
|
|
|
|
2020-12-21 07:26:05 +00:00
|
|
|
publicOnly bool
|
|
|
|
|
2020-07-11 08:07:09 +00:00
|
|
|
// custom callbacks
|
2020-10-03 12:09:22 +00:00
|
|
|
depthEventCallbacks []func(e *DepthEvent)
|
2020-09-16 04:28:15 +00:00
|
|
|
kLineEventCallbacks []func(e *KLineEvent)
|
|
|
|
kLineClosedEventCallbacks []func(e *KLineEvent)
|
2020-07-11 08:07:09 +00:00
|
|
|
|
2020-12-21 09:48:30 +00:00
|
|
|
balanceUpdateEventCallbacks []func(event *BalanceUpdateEvent)
|
|
|
|
outboundAccountInfoEventCallbacks []func(event *OutboundAccountInfoEvent)
|
|
|
|
outboundAccountPositionEventCallbacks []func(event *OutboundAccountPositionEvent)
|
|
|
|
executionReportEventCallbacks []func(event *ExecutionReportEvent)
|
2021-01-24 02:02:38 +00:00
|
|
|
|
|
|
|
depthFrames map[string]*DepthFrame
|
2020-07-11 05:02:53 +00:00
|
|
|
}
|
|
|
|
|
2020-10-03 12:09:22 +00:00
|
|
|
func NewStream(client *binance.Client) *Stream {
|
2020-10-03 11:38:35 +00:00
|
|
|
stream := &Stream{
|
2021-05-27 06:42:14 +00:00
|
|
|
StandardStream: types.StandardStream{
|
|
|
|
ReconnectC: make(chan struct{}, 1),
|
|
|
|
},
|
2021-01-24 02:02:38 +00:00
|
|
|
Client: client,
|
|
|
|
depthFrames: make(map[string]*DepthFrame),
|
2020-10-03 11:38:35 +00:00
|
|
|
}
|
|
|
|
|
2020-10-05 06:16:55 +00:00
|
|
|
stream.OnDepthEvent(func(e *DepthEvent) {
|
2021-05-25 11:13:10 +00:00
|
|
|
if debugBinanceDepth {
|
2021-05-25 13:36:14 +00:00
|
|
|
log.Infof("received %s depth event updateID %d ~ %d (len %d)", e.Symbol, e.FirstUpdateID, e.FinalUpdateID, e.FinalUpdateID-e.FirstUpdateID)
|
2021-05-25 11:13:10 +00:00
|
|
|
}
|
|
|
|
|
2021-01-24 02:02:38 +00:00
|
|
|
f, ok := stream.depthFrames[e.Symbol]
|
2020-10-05 06:16:55 +00:00
|
|
|
if !ok {
|
|
|
|
f = &DepthFrame{
|
2021-01-24 06:12:44 +00:00
|
|
|
client: client,
|
2021-01-24 06:09:07 +00:00
|
|
|
context: context.Background(),
|
2021-01-24 06:12:44 +00:00
|
|
|
Symbol: e.Symbol,
|
2021-05-25 17:20:24 +00:00
|
|
|
resetC: make(chan struct{}, 1),
|
2020-10-05 06:16:55 +00:00
|
|
|
}
|
2021-01-24 06:09:07 +00:00
|
|
|
|
|
|
|
stream.depthFrames[e.Symbol] = f
|
|
|
|
|
2021-05-25 13:36:14 +00:00
|
|
|
f.OnReady(func(snapshotDepth DepthEvent, bufEvents []DepthEvent) {
|
2021-05-25 17:20:24 +00:00
|
|
|
log.Infof("depth snapshot ready: %s", snapshotDepth.String())
|
2021-05-25 13:36:14 +00:00
|
|
|
|
|
|
|
snapshot, err := snapshotDepth.OrderBook()
|
2020-10-05 06:16:55 +00:00
|
|
|
if err != nil {
|
2021-01-25 06:13:39 +00:00
|
|
|
log.WithError(err).Error("book snapshot convert error")
|
2020-10-05 06:16:55 +00:00
|
|
|
return
|
|
|
|
}
|
2021-01-24 06:09:07 +00:00
|
|
|
|
2021-01-25 05:53:11 +00:00
|
|
|
if valid, err := snapshot.IsValid(); !valid {
|
2021-05-25 13:36:14 +00:00
|
|
|
log.Errorf("depth snapshot is invalid, event: %+v, error: %v", snapshotDepth, err)
|
2021-01-24 06:09:07 +00:00
|
|
|
}
|
|
|
|
|
2020-10-05 06:16:55 +00:00
|
|
|
stream.EmitBookSnapshot(snapshot)
|
|
|
|
|
|
|
|
for _, e := range bufEvents {
|
2021-05-25 13:36:14 +00:00
|
|
|
bookUpdate, err := e.OrderBook()
|
2020-10-05 06:16:55 +00:00
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("book convert error")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-05-25 13:36:14 +00:00
|
|
|
stream.EmitBookUpdate(bookUpdate)
|
2020-10-05 06:16:55 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
f.OnPush(func(e DepthEvent) {
|
|
|
|
book, err := e.OrderBook()
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("book convert error")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
stream.EmitBookUpdate(book)
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
f.PushEvent(*e)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2020-12-21 09:48:30 +00:00
|
|
|
stream.OnOutboundAccountPositionEvent(func(e *OutboundAccountPositionEvent) {
|
2020-10-26 14:03:42 +00:00
|
|
|
snapshot := types.BalanceMap{}
|
2020-10-03 11:38:35 +00:00
|
|
|
for _, balance := range e.Balances {
|
2020-11-10 06:19:33 +00:00
|
|
|
available := fixedpoint.Must(fixedpoint.NewFromString(balance.Free))
|
|
|
|
locked := fixedpoint.Must(fixedpoint.NewFromString(balance.Locked))
|
2020-10-03 11:38:35 +00:00
|
|
|
snapshot[balance.Asset] = types.Balance{
|
|
|
|
Currency: balance.Asset,
|
|
|
|
Available: available,
|
|
|
|
Locked: locked,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
stream.EmitBalanceSnapshot(snapshot)
|
|
|
|
})
|
|
|
|
|
|
|
|
stream.OnKLineEvent(func(e *KLineEvent) {
|
2020-10-26 14:03:42 +00:00
|
|
|
kline := e.KLine.KLine()
|
2020-10-03 11:38:35 +00:00
|
|
|
if e.KLine.Closed {
|
|
|
|
stream.EmitKLineClosedEvent(e)
|
2020-10-26 14:03:42 +00:00
|
|
|
stream.EmitKLineClosed(kline)
|
|
|
|
} else {
|
|
|
|
stream.EmitKLine(kline)
|
2020-10-03 11:38:35 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
stream.OnExecutionReportEvent(func(e *ExecutionReportEvent) {
|
|
|
|
switch e.CurrentExecutionType {
|
2020-10-29 13:10:01 +00:00
|
|
|
|
|
|
|
case "NEW", "CANCELED", "REJECTED", "EXPIRED", "REPLACED":
|
|
|
|
order, err := e.Order()
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("order convert error")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
stream.EmitOrderUpdate(*order)
|
|
|
|
|
2020-10-03 11:38:35 +00:00
|
|
|
case "TRADE":
|
|
|
|
trade, err := e.Trade()
|
|
|
|
if err != nil {
|
2020-10-05 06:16:55 +00:00
|
|
|
log.WithError(err).Error("trade convert error")
|
2020-10-29 13:10:01 +00:00
|
|
|
return
|
2020-10-03 11:38:35 +00:00
|
|
|
}
|
2020-10-05 06:16:55 +00:00
|
|
|
|
2020-10-29 11:47:53 +00:00
|
|
|
stream.EmitTradeUpdate(*trade)
|
2021-05-12 16:41:23 +00:00
|
|
|
|
|
|
|
order, err := e.Order()
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("order convert error")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update Order with FILLED event
|
2021-05-18 16:41:34 +00:00
|
|
|
if order.Status == types.OrderStatusFilled {
|
2021-05-12 16:41:23 +00:00
|
|
|
stream.EmitOrderUpdate(*order)
|
|
|
|
}
|
2020-10-03 11:38:35 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
stream.OnDisconnect(func() {
|
2021-05-25 13:36:14 +00:00
|
|
|
log.Infof("resetting depth snapshots...")
|
2021-01-24 06:09:07 +00:00
|
|
|
for _, f := range stream.depthFrames {
|
2021-05-25 17:20:24 +00:00
|
|
|
f.emitReset()
|
2021-01-24 06:09:07 +00:00
|
|
|
}
|
2021-05-25 11:13:10 +00:00
|
|
|
})
|
2021-01-24 06:09:07 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
stream.OnConnect(func() {
|
2020-10-03 12:09:22 +00:00
|
|
|
var params []string
|
|
|
|
for _, subscription := range stream.Subscriptions {
|
|
|
|
params = append(params, convertSubscription(subscription))
|
|
|
|
}
|
|
|
|
|
2020-11-15 05:32:46 +00:00
|
|
|
if len(params) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-12-21 06:53:34 +00:00
|
|
|
log.Infof("subscribing channels: %+v", params)
|
2020-10-03 12:09:22 +00:00
|
|
|
err := stream.Conn.WriteJSON(StreamRequest{
|
|
|
|
Method: "SUBSCRIBE",
|
|
|
|
Params: params,
|
|
|
|
ID: 1,
|
|
|
|
})
|
2020-10-03 11:38:35 +00:00
|
|
|
|
2020-10-03 12:09:22 +00:00
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("subscribe error")
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
return stream
|
|
|
|
}
|
2020-10-03 11:38:35 +00:00
|
|
|
|
2020-12-21 07:26:05 +00:00
|
|
|
func (s *Stream) SetPublicOnly() {
|
|
|
|
s.publicOnly = true
|
|
|
|
}
|
|
|
|
|
2020-10-03 10:35:28 +00:00
|
|
|
func (s *Stream) dial(listenKey string) (*websocket.Conn, error) {
|
2020-12-21 07:43:54 +00:00
|
|
|
var url string
|
|
|
|
if s.publicOnly {
|
|
|
|
url = "wss://stream.binance.com:9443/ws"
|
|
|
|
} else {
|
|
|
|
url = "wss://stream.binance.com:9443/ws/" + listenKey
|
|
|
|
}
|
|
|
|
|
2020-07-11 05:02:53 +00:00
|
|
|
conn, _, err := websocket.DefaultDialer.Dial(url, nil)
|
2020-07-12 14:52:24 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-02-11 00:13:50 +00:00
|
|
|
// use the default ping handler
|
|
|
|
conn.SetPingHandler(nil)
|
|
|
|
|
2020-07-12 14:52:24 +00:00
|
|
|
return conn, nil
|
|
|
|
}
|
|
|
|
|
2020-12-02 14:19:31 +00:00
|
|
|
func (s *Stream) fetchListenKey(ctx context.Context) (string, error) {
|
2021-01-19 18:09:12 +00:00
|
|
|
if s.IsMargin {
|
|
|
|
if s.IsIsolatedMargin {
|
|
|
|
log.Infof("isolated margin %s is enabled, requesting margin user stream listen key...", s.IsolatedMarginSymbol)
|
2021-01-15 06:56:11 +00:00
|
|
|
req := s.Client.NewStartIsolatedMarginUserStreamService()
|
2021-01-19 18:09:12 +00:00
|
|
|
req.Symbol(s.IsolatedMarginSymbol)
|
2021-01-15 06:56:11 +00:00
|
|
|
return req.Do(ctx)
|
2020-12-21 09:48:30 +00:00
|
|
|
}
|
|
|
|
|
2021-01-15 06:56:11 +00:00
|
|
|
log.Infof("margin mode is enabled, requesting margin user stream listen key...")
|
|
|
|
req := s.Client.NewStartMarginUserStreamService()
|
2020-12-21 09:48:30 +00:00
|
|
|
return req.Do(ctx)
|
2020-12-02 14:19:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return s.Client.NewStartUserStreamService().Do(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Stream) keepaliveListenKey(ctx context.Context, listenKey string) error {
|
2021-01-19 18:09:12 +00:00
|
|
|
if s.IsMargin {
|
|
|
|
if s.IsIsolatedMargin {
|
2021-01-15 06:56:11 +00:00
|
|
|
req := s.Client.NewKeepaliveIsolatedMarginUserStreamService().ListenKey(listenKey)
|
2021-01-19 18:09:12 +00:00
|
|
|
req.Symbol(s.IsolatedMarginSymbol)
|
2021-01-15 06:56:11 +00:00
|
|
|
return req.Do(ctx)
|
2020-12-21 09:48:30 +00:00
|
|
|
}
|
|
|
|
|
2021-01-15 06:56:11 +00:00
|
|
|
req := s.Client.NewKeepaliveMarginUserStreamService().ListenKey(listenKey)
|
2020-12-21 09:48:30 +00:00
|
|
|
return req.Do(ctx)
|
2020-12-02 14:19:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return s.Client.NewKeepaliveUserStreamService().ListenKey(listenKey).Do(ctx)
|
|
|
|
}
|
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
func (s *Stream) Connect(ctx context.Context) error {
|
|
|
|
err := s.connect(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// start one re-connector goroutine with the base context
|
|
|
|
go s.reconnector(ctx)
|
|
|
|
|
|
|
|
s.EmitStart()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Stream) reconnector(ctx context.Context) {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
|
2021-05-27 06:42:14 +00:00
|
|
|
case <-s.ReconnectC:
|
2021-05-25 11:13:10 +00:00
|
|
|
// ensure the previous context is cancelled
|
|
|
|
if s.connCancel != nil {
|
|
|
|
s.connCancel()
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Warnf("received reconnect signal, reconnecting...")
|
|
|
|
time.Sleep(3 * time.Second)
|
|
|
|
|
|
|
|
if err := s.connect(ctx); err != nil {
|
|
|
|
log.WithError(err).Errorf("connect error, try to reconnect again...")
|
2021-05-27 06:42:14 +00:00
|
|
|
s.Reconnect()
|
2021-05-25 11:13:10 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-03 10:35:28 +00:00
|
|
|
func (s *Stream) connect(ctx context.Context) error {
|
2021-05-25 11:13:10 +00:00
|
|
|
// should only start one connection one time, so we lock the mutex
|
2021-05-27 06:42:14 +00:00
|
|
|
s.ConnLock.Lock()
|
2021-05-25 11:13:10 +00:00
|
|
|
|
|
|
|
// create a new context
|
|
|
|
s.connCtx, s.connCancel = context.WithCancel(ctx)
|
|
|
|
|
2020-12-21 07:26:05 +00:00
|
|
|
if s.publicOnly {
|
|
|
|
log.Infof("stream is set to public only mode")
|
|
|
|
} else {
|
2020-12-02 14:19:31 +00:00
|
|
|
log.Infof("request listen key for creating user data stream...")
|
|
|
|
|
|
|
|
listenKey, err := s.fetchListenKey(ctx)
|
2020-12-21 07:26:05 +00:00
|
|
|
if err != nil {
|
2021-05-25 11:13:10 +00:00
|
|
|
s.connCancel()
|
2021-05-27 06:42:14 +00:00
|
|
|
s.ConnLock.Unlock()
|
2020-12-21 07:26:05 +00:00
|
|
|
return err
|
|
|
|
}
|
2020-07-12 14:52:24 +00:00
|
|
|
|
2020-12-21 07:26:05 +00:00
|
|
|
s.ListenKey = listenKey
|
2020-12-21 09:48:30 +00:00
|
|
|
log.Infof("user data stream created. listenKey: %s", maskListenKey(s.ListenKey))
|
2021-05-25 11:13:10 +00:00
|
|
|
|
|
|
|
go s.listenKeyKeepAlive(s.connCtx, listenKey)
|
2020-12-21 07:26:05 +00:00
|
|
|
}
|
2020-07-12 14:52:24 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
// when in public mode, the listen key is an empty string
|
2020-07-12 14:52:24 +00:00
|
|
|
conn, err := s.dial(s.ListenKey)
|
2020-07-11 05:02:53 +00:00
|
|
|
if err != nil {
|
2021-05-25 11:13:10 +00:00
|
|
|
s.connCancel()
|
2021-05-27 06:42:14 +00:00
|
|
|
s.ConnLock.Unlock()
|
2020-07-11 05:02:53 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-12-21 06:53:34 +00:00
|
|
|
log.Infof("websocket connected")
|
2021-01-25 05:53:11 +00:00
|
|
|
|
2021-05-28 15:34:21 +00:00
|
|
|
conn.SetReadDeadline(time.Now().Add(15 * time.Second))
|
|
|
|
conn.SetPongHandler(func(string) error {
|
|
|
|
conn.SetReadDeadline(time.Now().Add(15 * time.Second))
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
2020-07-11 05:02:53 +00:00
|
|
|
s.Conn = conn
|
2021-05-27 06:42:14 +00:00
|
|
|
s.ConnLock.Unlock()
|
2020-07-11 05:02:53 +00:00
|
|
|
|
2020-11-07 04:38:57 +00:00
|
|
|
s.EmitConnect()
|
2021-05-25 11:13:10 +00:00
|
|
|
|
|
|
|
go s.read(s.connCtx)
|
|
|
|
go s.ping(s.connCtx)
|
2020-10-03 12:09:22 +00:00
|
|
|
return nil
|
2020-07-12 14:52:24 +00:00
|
|
|
}
|
2020-07-11 05:02:53 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
func (s *Stream) ping(ctx context.Context) {
|
2021-05-28 15:34:21 +00:00
|
|
|
pingTicker := time.NewTicker(5 * time.Second)
|
2021-05-25 11:13:10 +00:00
|
|
|
defer pingTicker.Stop()
|
2020-10-03 11:14:15 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
for {
|
|
|
|
select {
|
2020-10-03 11:14:15 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
case <-ctx.Done():
|
|
|
|
log.Info("ping worker stopped")
|
|
|
|
return
|
2020-10-03 11:14:15 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
case <-pingTicker.C:
|
2021-05-28 15:34:21 +00:00
|
|
|
if err := s.Conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(3*time.Second)); err != nil {
|
2021-05-25 11:13:10 +00:00
|
|
|
log.WithError(err).Error("ping error", err)
|
2021-05-27 06:42:14 +00:00
|
|
|
s.Reconnect()
|
2021-05-25 11:13:10 +00:00
|
|
|
}
|
|
|
|
}
|
2020-07-11 05:02:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
func (s *Stream) listenKeyKeepAlive(ctx context.Context, listenKey string) {
|
2020-08-07 01:17:35 +00:00
|
|
|
keepAliveTicker := time.NewTicker(5 * time.Minute)
|
|
|
|
defer keepAliveTicker.Stop()
|
2020-07-11 05:02:53 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
// if we exit, we should invalidate the existing listen key
|
|
|
|
defer func() {
|
|
|
|
log.Info("keepalive worker stopped")
|
2021-05-28 15:34:21 +00:00
|
|
|
if err := s.invalidateListenKey(context.Background(), listenKey); err != nil {
|
2021-05-25 11:13:10 +00:00
|
|
|
log.WithError(err).Error("invalidate listen key error")
|
|
|
|
}
|
|
|
|
}()
|
2020-07-11 05:02:53 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
for {
|
|
|
|
select {
|
2020-07-11 05:02:53 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
2021-01-15 06:56:11 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
case <-keepAliveTicker.C:
|
|
|
|
if err := s.keepaliveListenKey(ctx, listenKey); err != nil {
|
|
|
|
log.WithError(err).Errorf("listen key keep-alive error: %v key: %s", err, maskListenKey(listenKey))
|
2021-05-27 06:42:14 +00:00
|
|
|
s.Reconnect()
|
2021-05-25 11:13:10 +00:00
|
|
|
return
|
|
|
|
}
|
2021-01-25 05:53:11 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-08-07 01:17:35 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
func (s *Stream) read(ctx context.Context) {
|
|
|
|
defer func() {
|
|
|
|
if s.connCancel != nil {
|
|
|
|
s.connCancel()
|
2021-01-15 06:56:11 +00:00
|
|
|
}
|
2021-05-25 11:13:10 +00:00
|
|
|
s.EmitDisconnect()
|
2021-01-15 06:56:11 +00:00
|
|
|
}()
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
2020-07-18 02:43:27 +00:00
|
|
|
|
2020-07-11 05:02:53 +00:00
|
|
|
default:
|
2021-05-27 10:35:34 +00:00
|
|
|
if err := s.Conn.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil {
|
2020-07-11 08:07:09 +00:00
|
|
|
log.WithError(err).Errorf("set read deadline error: %s", err.Error())
|
2020-07-11 05:02:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
mt, message, err := s.Conn.ReadMessage()
|
2020-07-12 14:52:24 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
if err != nil {
|
|
|
|
// if it's a network timeout error, we should re-connect
|
|
|
|
switch err := err.(type) {
|
2021-03-15 05:27:18 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
// if it's a websocket related error
|
|
|
|
case *websocket.CloseError:
|
|
|
|
if err.Code == websocket.CloseNormalClosure {
|
2020-07-12 17:06:04 +00:00
|
|
|
return
|
2021-05-25 11:13:10 +00:00
|
|
|
}
|
2020-07-12 17:06:04 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
// for unexpected close error, we should re-connect
|
|
|
|
// emit reconnect to start a new connection
|
2021-05-27 06:42:14 +00:00
|
|
|
s.Reconnect()
|
2021-05-25 11:13:10 +00:00
|
|
|
return
|
2020-07-13 05:25:48 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
case net.Error:
|
|
|
|
log.WithError(err).Error("network error")
|
2021-05-27 06:42:14 +00:00
|
|
|
s.Reconnect()
|
2021-05-25 11:13:10 +00:00
|
|
|
return
|
2020-07-12 14:52:24 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
default:
|
|
|
|
log.WithError(err).Error("unexpected connection error")
|
2021-05-27 06:42:14 +00:00
|
|
|
s.Reconnect()
|
2021-05-25 11:13:10 +00:00
|
|
|
return
|
|
|
|
}
|
2020-07-11 05:02:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// skip non-text messages
|
|
|
|
if mt != websocket.TextMessage {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-12-21 09:48:30 +00:00
|
|
|
log.Debug(string(message))
|
2020-07-11 05:02:53 +00:00
|
|
|
|
|
|
|
e, err := ParseEvent(string(message))
|
|
|
|
if err != nil {
|
2021-05-28 15:34:21 +00:00
|
|
|
log.WithError(err).Errorf("websocket event parse error")
|
2020-07-11 05:02:53 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-07-11 08:07:09 +00:00
|
|
|
switch e := e.(type) {
|
|
|
|
|
2020-12-21 09:48:30 +00:00
|
|
|
case *OutboundAccountPositionEvent:
|
|
|
|
s.EmitOutboundAccountPositionEvent(e)
|
|
|
|
|
2020-07-11 08:07:09 +00:00
|
|
|
case *OutboundAccountInfoEvent:
|
|
|
|
s.EmitOutboundAccountInfoEvent(e)
|
|
|
|
|
|
|
|
case *BalanceUpdateEvent:
|
|
|
|
s.EmitBalanceUpdateEvent(e)
|
|
|
|
|
|
|
|
case *KLineEvent:
|
|
|
|
s.EmitKLineEvent(e)
|
|
|
|
|
2020-10-03 12:09:22 +00:00
|
|
|
case *DepthEvent:
|
|
|
|
s.EmitDepthEvent(e)
|
|
|
|
|
2020-07-11 08:07:09 +00:00
|
|
|
case *ExecutionReportEvent:
|
|
|
|
s.EmitExecutionReportEvent(e)
|
|
|
|
}
|
2020-07-11 05:02:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-02 14:19:31 +00:00
|
|
|
func (s *Stream) invalidateListenKey(ctx context.Context, listenKey string) (err error) {
|
|
|
|
// should use background context to invalidate the user stream
|
2020-12-21 09:48:30 +00:00
|
|
|
log.Info("closing listen key")
|
2020-12-02 14:19:31 +00:00
|
|
|
|
2021-01-19 18:09:12 +00:00
|
|
|
if s.IsMargin {
|
|
|
|
if s.IsIsolatedMargin {
|
2021-01-15 06:56:11 +00:00
|
|
|
req := s.Client.NewCloseIsolatedMarginUserStreamService().ListenKey(listenKey)
|
2021-01-19 18:09:12 +00:00
|
|
|
req.Symbol(s.IsolatedMarginSymbol)
|
2021-01-15 06:56:11 +00:00
|
|
|
err = req.Do(ctx)
|
|
|
|
} else {
|
|
|
|
req := s.Client.NewCloseMarginUserStreamService().ListenKey(listenKey)
|
|
|
|
err = req.Do(ctx)
|
2020-12-21 09:48:30 +00:00
|
|
|
}
|
|
|
|
|
2020-12-02 14:19:31 +00:00
|
|
|
} else {
|
|
|
|
err = s.Client.NewCloseUserStreamService().ListenKey(listenKey).Do(ctx)
|
|
|
|
}
|
|
|
|
|
2020-07-11 05:02:53 +00:00
|
|
|
if err != nil {
|
2020-12-21 09:48:30 +00:00
|
|
|
log.WithError(err).Error("error deleting listen key")
|
2020-07-11 05:02:53 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-07-11 09:02:37 +00:00
|
|
|
return nil
|
2020-07-11 05:02:53 +00:00
|
|
|
}
|
2020-07-12 14:52:24 +00:00
|
|
|
|
2020-10-03 10:35:28 +00:00
|
|
|
func (s *Stream) Close() error {
|
2020-12-21 06:53:34 +00:00
|
|
|
log.Infof("closing user data stream...")
|
2020-07-12 14:52:24 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
if s.connCancel != nil {
|
|
|
|
s.connCancel()
|
2020-12-21 07:26:05 +00:00
|
|
|
}
|
|
|
|
|
2021-05-27 06:42:14 +00:00
|
|
|
s.ConnLock.Lock()
|
2021-05-25 11:13:10 +00:00
|
|
|
err := s.Conn.Close()
|
2021-05-27 06:42:14 +00:00
|
|
|
s.ConnLock.Unlock()
|
2021-05-25 11:13:10 +00:00
|
|
|
return err
|
2020-07-12 14:52:24 +00:00
|
|
|
}
|
2020-08-07 01:17:35 +00:00
|
|
|
|
|
|
|
func maskListenKey(listenKey string) string {
|
|
|
|
maskKey := listenKey[0:5]
|
|
|
|
return maskKey + strings.Repeat("*", len(listenKey)-1-5)
|
|
|
|
}
|
2020-10-05 06:16:55 +00:00
|
|
|
|
|
|
|
//go:generate callbackgen -type DepthFrame
|