2020-07-11 05:02:53 +00:00
|
|
|
package binance
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-05-25 11:13:10 +00:00
|
|
|
"net"
|
2021-06-07 08:57:49 +00:00
|
|
|
"net/http"
|
2021-01-23 08:59:51 +00:00
|
|
|
"os"
|
|
|
|
"strconv"
|
2021-01-25 05:53:11 +00:00
|
|
|
"sync"
|
2020-07-13 08:03:47 +00:00
|
|
|
"time"
|
|
|
|
|
2021-12-30 07:47:13 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
|
2021-12-24 17:57:05 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/depth"
|
|
|
|
"github.com/c9s/bbgo/pkg/util"
|
|
|
|
|
2021-01-11 05:36:49 +00:00
|
|
|
"github.com/adshao/go-binance/v2"
|
2021-12-12 07:40:03 +00:00
|
|
|
"github.com/adshao/go-binance/v2/futures"
|
|
|
|
|
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
|
|
|
|
|
2021-06-07 08:57:49 +00:00
|
|
|
var defaultDialer = &websocket.Dialer{
|
|
|
|
Proxy: http.ProxyFromEnvironment,
|
2021-12-29 09:27:37 +00:00
|
|
|
HandshakeTimeout: 10 * time.Second,
|
|
|
|
ReadBufferSize: 4096,
|
2021-06-07 08:57:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// from Binance document:
|
|
|
|
// The websocket server will send a ping frame every 3 minutes.
|
|
|
|
// If the websocket server does not receive a pong frame back from the connection within a 10 minute period, the connection will be disconnected.
|
|
|
|
// Unsolicited pong frames are allowed.
|
|
|
|
|
|
|
|
// WebSocket connections have a limit of 5 incoming messages per second. A message is considered:
|
|
|
|
// A PING frame
|
|
|
|
// A PONG frame
|
|
|
|
// A JSON controlled message (e.g. subscribe, unsubscribe)
|
2021-12-30 07:47:13 +00:00
|
|
|
|
|
|
|
// The connect() method dials and creates the connection object, then it starts 2 go-routine, 1 for reading message, 2 for writing ping messages.
|
|
|
|
// The re-connector uses the ReconnectC signal channel to start a new websocket connection.
|
|
|
|
// When ReconnectC is triggered
|
|
|
|
// - The context created for the connection must be canceled
|
|
|
|
// - The read goroutine must close the connection and exit
|
|
|
|
// - The ping goroutine must stop the ticker and exit
|
|
|
|
// - the re-connector calls connect() to create the new connection object, go to the 1 step.
|
|
|
|
// When stream.Close() is called, a close message must be written to the websocket connection.
|
|
|
|
|
2021-12-30 08:47:39 +00:00
|
|
|
const readTimeout = 1 * time.Minute
|
2021-12-29 09:27:37 +00:00
|
|
|
const writeTimeout = 10 * time.Second
|
2021-12-30 08:47:39 +00:00
|
|
|
const pingInterval = readTimeout / 3
|
2021-12-29 09:27:37 +00:00
|
|
|
const listenKeyKeepAliveInterval = 10 * time.Minute
|
2021-12-30 08:47:39 +00:00
|
|
|
const reconnectCoolDownPeriod = 15 * time.Second
|
2021-05-29 12:40:47 +00:00
|
|
|
|
2020-12-21 06:43:40 +00:00
|
|
|
func init() {
|
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
|
|
|
}
|
|
|
|
|
2021-12-30 08:49:07 +00:00
|
|
|
type WebSocketCommand struct {
|
2020-07-11 05:02:53 +00:00
|
|
|
// 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
|
2021-11-15 17:24:36 +00:00
|
|
|
types.FuturesSettings
|
2020-10-03 10:35:28 +00:00
|
|
|
types.StandardStream
|
2020-07-15 13:02:08 +00:00
|
|
|
|
2021-12-12 07:40:03 +00:00
|
|
|
Client *binance.Client
|
|
|
|
futuresClient *futures.Client
|
|
|
|
|
2021-05-30 07:51:14 +00:00
|
|
|
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
|
|
|
|
|
|
|
// 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
|
|
|
|
2021-11-16 06:26:27 +00:00
|
|
|
markPriceUpdateEventCallbacks []func(e *MarkPriceUpdateEvent)
|
2021-12-12 07:40:03 +00:00
|
|
|
|
|
|
|
continuousKLineEventCallbacks []func(e *ContinuousKLineEvent)
|
|
|
|
continuousKLineClosedEventCallbacks []func(e *ContinuousKLineEvent)
|
2021-11-15 17:24:36 +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-12-22 13:01:11 +00:00
|
|
|
bookTickerEventCallbacks []func(event *BookTickerEvent)
|
2021-01-24 02:02:38 +00:00
|
|
|
|
2021-12-12 07:40:03 +00:00
|
|
|
orderTradeUpdateEventCallbacks []func(e *OrderTradeUpdateEvent)
|
|
|
|
|
2021-12-24 18:10:13 +00:00
|
|
|
depthBuffers map[string]*depth.Buffer
|
2020-07-11 05:02:53 +00:00
|
|
|
}
|
|
|
|
|
2021-12-24 18:10:13 +00:00
|
|
|
func NewStream(ex *Exchange, client *binance.Client, futuresClient *futures.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-12-30 08:20:32 +00:00
|
|
|
CloseC: make(chan struct{}),
|
2021-05-27 06:42:14 +00:00
|
|
|
},
|
2021-12-12 07:40:03 +00:00
|
|
|
Client: client,
|
|
|
|
futuresClient: futuresClient,
|
2021-12-24 18:10:13 +00:00
|
|
|
depthBuffers: make(map[string]*depth.Buffer),
|
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-12-24 18:10:13 +00:00
|
|
|
f, ok := stream.depthBuffers[e.Symbol]
|
2021-12-25 15:53:34 +00:00
|
|
|
if ok {
|
|
|
|
f.AddUpdate(types.SliceOrderBook{
|
|
|
|
Symbol: e.Symbol,
|
|
|
|
Bids: e.Bids,
|
|
|
|
Asks: e.Asks,
|
|
|
|
}, e.FirstUpdateID, e.FinalUpdateID)
|
|
|
|
} else {
|
2021-12-24 18:10:13 +00:00
|
|
|
f = depth.NewBuffer(func() (types.SliceOrderBook, int64, error) {
|
|
|
|
return ex.QueryDepth(context.Background(), e.Symbol)
|
2020-10-05 06:16:55 +00:00
|
|
|
})
|
2021-12-24 18:10:13 +00:00
|
|
|
stream.depthBuffers[e.Symbol] = f
|
2021-12-24 17:57:05 +00:00
|
|
|
|
2021-12-25 11:34:27 +00:00
|
|
|
f.SetBufferingPeriod(time.Second)
|
2021-12-24 17:57:05 +00:00
|
|
|
f.OnReady(func(snapshot types.SliceOrderBook, updates []depth.Update) {
|
|
|
|
if valid, err := snapshot.IsValid(); !valid {
|
|
|
|
log.Errorf("depth snapshot is invalid, error: %v", err)
|
2020-10-05 06:16:55 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-12-24 17:57:05 +00:00
|
|
|
stream.EmitBookSnapshot(snapshot)
|
|
|
|
for _, u := range updates {
|
|
|
|
stream.EmitBookUpdate(u.Object)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
f.OnPush(func(update depth.Update) {
|
|
|
|
stream.EmitBookUpdate(update.Object)
|
2020-10-05 06:16:55 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2021-12-30 06:02:36 +00:00
|
|
|
stream.OnOutboundAccountPositionEvent(stream.handleOutboundAccountPositionEvent)
|
|
|
|
stream.OnKLineEvent(stream.handleKLineEvent)
|
|
|
|
stream.OnBookTickerEvent(stream.handleBookTickerEvent)
|
|
|
|
stream.OnExecutionReportEvent(stream.handleExecutionReportEvent)
|
|
|
|
stream.OnContinuousKLineEvent(stream.handleContinuousKLineEvent)
|
2021-12-12 07:40:03 +00:00
|
|
|
|
|
|
|
stream.OnOrderTradeUpdateEvent(func(e *OrderTradeUpdateEvent) {
|
|
|
|
switch e.OrderTrade.CurrentExecutionType {
|
|
|
|
|
|
|
|
case "NEW", "CANCELED", "EXPIRED":
|
|
|
|
order, err := e.OrderFutures()
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("order convert error")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
stream.EmitOrderUpdate(*order)
|
|
|
|
|
|
|
|
case "TRADE":
|
|
|
|
// TODO
|
|
|
|
|
|
|
|
// trade, err := e.Trade()
|
|
|
|
// if err != nil {
|
|
|
|
// log.WithError(err).Error("trade convert error")
|
|
|
|
// return
|
|
|
|
// }
|
|
|
|
|
|
|
|
// stream.EmitTradeUpdate(*trade)
|
|
|
|
|
|
|
|
// order, err := e.OrderFutures()
|
|
|
|
// if err != nil {
|
|
|
|
// log.WithError(err).Error("order convert error")
|
|
|
|
// return
|
|
|
|
// }
|
|
|
|
|
|
|
|
// Update Order with FILLED event
|
|
|
|
// if order.Status == types.OrderStatusFilled {
|
|
|
|
// stream.EmitOrderUpdate(*order)
|
|
|
|
// }
|
|
|
|
case "CALCULATED - Liquidation Execution":
|
|
|
|
log.Infof("CALCULATED - Liquidation Execution not support yet.")
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
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-12-24 18:10:13 +00:00
|
|
|
for _, f := range stream.depthBuffers {
|
2021-12-24 17:57:05 +00:00
|
|
|
f.Reset()
|
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)
|
2021-12-30 08:49:07 +00:00
|
|
|
err := stream.Conn.WriteJSON(WebSocketCommand{
|
2020-10-03 12:09:22 +00:00
|
|
|
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
|
|
|
|
2021-12-30 06:02:36 +00:00
|
|
|
func (s *Stream) handleContinuousKLineEvent(e *ContinuousKLineEvent) {
|
|
|
|
kline := e.KLine.KLine()
|
|
|
|
if e.KLine.Closed {
|
|
|
|
s.EmitContinuousKLineClosedEvent(e)
|
|
|
|
s.EmitKLineClosed(kline)
|
|
|
|
} else {
|
|
|
|
s.EmitKLine(kline)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Stream) handleExecutionReportEvent(e *ExecutionReportEvent) {
|
|
|
|
switch e.CurrentExecutionType {
|
|
|
|
|
|
|
|
case "NEW", "CANCELED", "REJECTED", "EXPIRED", "REPLACED":
|
|
|
|
order, err := e.Order()
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("order convert error")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
s.EmitOrderUpdate(*order)
|
|
|
|
|
|
|
|
case "TRADE":
|
|
|
|
trade, err := e.Trade()
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("trade convert error")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
s.EmitTradeUpdate(*trade)
|
|
|
|
|
|
|
|
order, err := e.Order()
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("order convert error")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update Order with FILLED event
|
|
|
|
if order.Status == types.OrderStatusFilled {
|
|
|
|
s.EmitOrderUpdate(*order)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Stream) handleBookTickerEvent(e *BookTickerEvent) {
|
|
|
|
s.EmitBookTickerUpdate(e.BookTicker())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Stream) handleKLineEvent(e *KLineEvent) {
|
|
|
|
kline := e.KLine.KLine()
|
|
|
|
if e.KLine.Closed {
|
|
|
|
s.EmitKLineClosedEvent(e)
|
|
|
|
s.EmitKLineClosed(kline)
|
|
|
|
} else {
|
|
|
|
s.EmitKLine(kline)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Stream) handleOutboundAccountPositionEvent(e *OutboundAccountPositionEvent) {
|
|
|
|
snapshot := types.BalanceMap{}
|
|
|
|
for _, balance := range e.Balances {
|
|
|
|
snapshot[balance.Asset] = types.Balance{
|
|
|
|
Currency: balance.Asset,
|
|
|
|
Available: balance.Free,
|
|
|
|
Locked: balance.Locked,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
s.EmitBalanceSnapshot(snapshot)
|
|
|
|
}
|
|
|
|
|
2021-12-30 08:22:29 +00:00
|
|
|
func (s *Stream) getEndpointUrl(listenKey string) string {
|
2020-12-21 07:43:54 +00:00
|
|
|
var url string
|
2021-12-23 06:14:48 +00:00
|
|
|
if s.PublicOnly {
|
2021-12-12 07:40:03 +00:00
|
|
|
if s.IsFutures {
|
|
|
|
url = "wss://fstream.binance.com/ws/"
|
|
|
|
} else {
|
|
|
|
url = "wss://stream.binance.com:9443/ws"
|
|
|
|
}
|
2020-12-21 07:43:54 +00:00
|
|
|
} else {
|
2021-12-12 07:40:03 +00:00
|
|
|
if s.IsFutures {
|
|
|
|
url = "wss://fstream.binance.com/ws/" + listenKey
|
|
|
|
} else {
|
|
|
|
url = "wss://stream.binance.com:9443/ws/" + listenKey
|
|
|
|
}
|
2020-12-21 07:43:54 +00:00
|
|
|
}
|
|
|
|
|
2021-12-30 08:22:29 +00:00
|
|
|
return url
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Stream) dial(listenKey string) (*websocket.Conn, error) {
|
|
|
|
url := s.getEndpointUrl(listenKey)
|
2021-06-07 08:57:49 +00:00
|
|
|
conn, _, err := 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
|
2021-05-29 12:40:47 +00:00
|
|
|
// The websocket server will send a ping frame every 3 minutes.
|
2021-12-29 07:25:42 +00:00
|
|
|
// If the websocket server does not receive a pong frame back from the connection within a 10 minutes period,
|
2021-05-29 12:40:47 +00:00
|
|
|
// the connection will be disconnected.
|
|
|
|
// Unsolicited pong frames are allowed.
|
2021-02-11 00:13:50 +00:00
|
|
|
conn.SetPingHandler(nil)
|
2021-12-29 09:27:37 +00:00
|
|
|
conn.SetPongHandler(func(string) error {
|
2021-12-29 09:28:45 +00:00
|
|
|
log.Debugf("websocket <- received pong")
|
2021-12-29 09:27:37 +00:00
|
|
|
if err := conn.SetReadDeadline(time.Now().Add(readTimeout * 2)); err != nil {
|
|
|
|
log.WithError(err).Error("pong handler can not set read deadline")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
2021-02-11 00:13:50 +00:00
|
|
|
|
2020-07-12 14:52:24 +00:00
|
|
|
return conn, nil
|
|
|
|
}
|
|
|
|
|
2021-12-30 07:47:13 +00:00
|
|
|
// Connect starts the stream and create the websocket connection
|
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 {
|
2021-12-30 07:47:13 +00:00
|
|
|
|
2021-05-25 11:13:10 +00:00
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
|
2021-12-30 07:47:13 +00:00
|
|
|
case <-s.CloseC:
|
|
|
|
return
|
|
|
|
|
2021-05-27 06:42:14 +00:00
|
|
|
case <-s.ReconnectC:
|
2021-12-30 07:47:13 +00:00
|
|
|
log.Warnf("received reconnect signal")
|
2021-12-30 08:47:39 +00:00
|
|
|
time.Sleep(reconnectCoolDownPeriod)
|
2021-05-25 11:13:10 +00:00
|
|
|
|
2021-12-30 07:47:13 +00:00
|
|
|
log.Warnf("re-connecting...")
|
2021-05-25 11:13:10 +00:00
|
|
|
if err := s.connect(ctx); err != nil {
|
2021-12-30 08:47:39 +00:00
|
|
|
log.WithError(err).Errorf("re-connect error, try to reconnect after %s...", reconnectCoolDownPeriod)
|
|
|
|
|
|
|
|
// re-emit the re-connect signal if error
|
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-30 10:20:14 +00:00
|
|
|
var err error
|
2021-05-30 07:51:14 +00:00
|
|
|
var listenKey string
|
2021-12-23 06:14:48 +00:00
|
|
|
if s.PublicOnly {
|
2020-12-21 07:26:05 +00:00
|
|
|
log.Infof("stream is set to public only mode")
|
|
|
|
} else {
|
2021-05-30 10:20:14 +00:00
|
|
|
listenKey, err = s.fetchListenKey(ctx)
|
2020-12-21 07:26:05 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-07-12 14:52:24 +00:00
|
|
|
|
2021-12-22 17:16:08 +00:00
|
|
|
log.Infof("listen key is created: %s", util.MaskKey(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
|
2021-05-30 07:51:14 +00:00
|
|
|
conn, err := s.dial(listenKey)
|
2020-07-11 05:02:53 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-12-21 06:53:34 +00:00
|
|
|
log.Infof("websocket connected")
|
2021-01-25 05:53:11 +00:00
|
|
|
|
2021-05-30 10:20:14 +00:00
|
|
|
// should only start one connection one time, so we lock the mutex
|
|
|
|
s.ConnLock.Lock()
|
2021-05-30 07:51:14 +00:00
|
|
|
|
2021-05-30 07:53:01 +00:00
|
|
|
// ensure the previous context is cancelled
|
|
|
|
if s.connCancel != nil {
|
|
|
|
s.connCancel()
|
|
|
|
}
|
|
|
|
|
2021-12-30 07:47:13 +00:00
|
|
|
// create a new context for this connection
|
2021-05-30 07:51:14 +00:00
|
|
|
s.connCtx, s.connCancel = context.WithCancel(ctx)
|
2020-07-11 05:02:53 +00:00
|
|
|
s.Conn = conn
|
2021-05-27 06:42:14 +00:00
|
|
|
s.ConnLock.Unlock()
|
2021-12-30 07:47:13 +00:00
|
|
|
|
2020-11-07 04:38:57 +00:00
|
|
|
s.EmitConnect()
|
2021-05-25 11:13:10 +00:00
|
|
|
|
2021-12-23 06:14:48 +00:00
|
|
|
if !s.PublicOnly {
|
2021-05-30 07:51:14 +00:00
|
|
|
go s.listenKeyKeepAlive(s.connCtx, listenKey)
|
|
|
|
}
|
|
|
|
|
2021-12-30 07:47:13 +00:00
|
|
|
go s.read(s.connCtx, conn)
|
2021-12-30 08:47:39 +00:00
|
|
|
go s.ping(s.connCtx, conn, pingInterval)
|
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-12-30 07:47:13 +00:00
|
|
|
func (s *Stream) ping(ctx context.Context, conn *websocket.Conn, interval time.Duration) {
|
|
|
|
defer log.Debug("ping worker stopped")
|
|
|
|
|
|
|
|
var pingTicker = time.NewTicker(interval)
|
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():
|
|
|
|
return
|
2020-10-03 11:14:15 +00:00
|
|
|
|
2021-12-30 07:47:13 +00:00
|
|
|
case <-s.CloseC:
|
|
|
|
return
|
2021-05-29 12:40:47 +00:00
|
|
|
|
2021-12-30 07:47:13 +00:00
|
|
|
case <-pingTicker.C:
|
2021-12-29 09:28:45 +00:00
|
|
|
log.Debugf("websocket -> ping")
|
2021-12-29 09:27:37 +00:00
|
|
|
if err := conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(writeTimeout)); 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-12-30 07:47:13 +00:00
|
|
|
func (s *Stream) read(ctx context.Context, conn *websocket.Conn) {
|
2021-05-25 11:13:10 +00:00
|
|
|
defer func() {
|
2021-12-30 07:47:13 +00:00
|
|
|
// if we failed to read, we need to cancel the context
|
2021-05-25 11:13:10 +00:00
|
|
|
if s.connCancel != nil {
|
|
|
|
s.connCancel()
|
2021-01-15 06:56:11 +00:00
|
|
|
}
|
2021-12-30 07:47:13 +00:00
|
|
|
_ = conn.Close()
|
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
|
|
|
|
2021-12-30 07:47:13 +00:00
|
|
|
case <-s.CloseC:
|
|
|
|
return
|
2021-05-29 12:40:47 +00:00
|
|
|
|
2021-12-30 07:47:13 +00:00
|
|
|
default:
|
2021-05-29 12:40:47 +00:00
|
|
|
if err := conn.SetReadDeadline(time.Now().Add(readTimeout)); 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
|
|
|
}
|
|
|
|
|
2021-05-29 12:40:47 +00:00
|
|
|
mt, message, err := conn.ReadMessage()
|
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-12-30 07:47:13 +00:00
|
|
|
log.WithError(err).Errorf("websocket error abnormal close: %+v", err)
|
|
|
|
|
2021-06-07 08:57:49 +00:00
|
|
|
_ = conn.Close()
|
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:
|
2021-12-30 07:47:13 +00:00
|
|
|
log.WithError(err).Error("websocket read network error")
|
2021-06-07 08:57:49 +00:00
|
|
|
_ = conn.Close()
|
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:
|
2021-12-30 07:47:13 +00:00
|
|
|
log.WithError(err).Error("unexpected websocket error")
|
2021-06-07 08:57:49 +00:00
|
|
|
_ = conn.Close()
|
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
|
|
|
|
}
|
|
|
|
|
2021-12-30 08:30:02 +00:00
|
|
|
s.dispatchEvent(e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-07-11 08:07:09 +00:00
|
|
|
|
2021-12-30 08:30:02 +00:00
|
|
|
func (s *Stream) dispatchEvent(e interface{}) {
|
|
|
|
switch e := e.(type) {
|
2020-12-21 09:48:30 +00:00
|
|
|
|
2021-12-30 08:30:02 +00:00
|
|
|
case *OutboundAccountPositionEvent:
|
|
|
|
s.EmitOutboundAccountPositionEvent(e)
|
2020-07-11 08:07:09 +00:00
|
|
|
|
2021-12-30 08:30:02 +00:00
|
|
|
case *OutboundAccountInfoEvent:
|
|
|
|
s.EmitOutboundAccountInfoEvent(e)
|
2020-07-11 08:07:09 +00:00
|
|
|
|
2021-12-30 08:30:02 +00:00
|
|
|
case *BalanceUpdateEvent:
|
|
|
|
s.EmitBalanceUpdateEvent(e)
|
2020-07-11 08:07:09 +00:00
|
|
|
|
2021-12-30 08:30:02 +00:00
|
|
|
case *KLineEvent:
|
|
|
|
s.EmitKLineEvent(e)
|
2021-12-22 13:01:11 +00:00
|
|
|
|
2021-12-30 08:30:02 +00:00
|
|
|
case *BookTickerEvent:
|
|
|
|
s.EmitBookTickerEvent(e)
|
2020-10-03 12:09:22 +00:00
|
|
|
|
2021-12-30 08:30:02 +00:00
|
|
|
case *DepthEvent:
|
|
|
|
s.EmitDepthEvent(e)
|
2021-12-12 07:40:03 +00:00
|
|
|
|
2021-12-30 08:30:02 +00:00
|
|
|
case *ExecutionReportEvent:
|
|
|
|
s.EmitExecutionReportEvent(e)
|
2021-12-12 07:40:03 +00:00
|
|
|
|
2021-12-30 08:30:02 +00:00
|
|
|
case *MarkPriceUpdateEvent:
|
|
|
|
s.EmitMarkPriceUpdateEvent(e)
|
2021-12-12 07:40:03 +00:00
|
|
|
|
2021-12-30 08:30:02 +00:00
|
|
|
case *ContinuousKLineEvent:
|
|
|
|
s.EmitContinuousKLineEvent(e)
|
|
|
|
|
|
|
|
case *OrderTradeUpdateEvent:
|
|
|
|
s.EmitOrderTradeUpdateEvent(e)
|
2020-07-11 05:02:53 +00:00
|
|
|
}
|
2021-12-30 08:30:02 +00:00
|
|
|
|
2020-07-11 05:02:53 +00:00
|
|
|
}
|
|
|
|
|
2021-12-29 09:30:04 +00:00
|
|
|
func (s *Stream) Close() error {
|
|
|
|
log.Infof("closing stream...")
|
|
|
|
|
2021-12-30 07:47:13 +00:00
|
|
|
// close the close signal channel
|
|
|
|
close(s.CloseC)
|
|
|
|
|
|
|
|
// get the connection object before call the context cancel function
|
|
|
|
s.ConnLock.Lock()
|
|
|
|
conn := s.Conn
|
2021-12-30 08:30:02 +00:00
|
|
|
connCancel := s.connCancel
|
2021-12-30 07:47:13 +00:00
|
|
|
s.ConnLock.Unlock()
|
|
|
|
|
|
|
|
// cancel the context so that the ticker loop and listen key updater will be stopped.
|
2021-12-30 08:30:02 +00:00
|
|
|
if connCancel != nil {
|
|
|
|
connCancel()
|
2021-12-29 09:30:04 +00:00
|
|
|
}
|
|
|
|
|
2021-12-30 07:47:13 +00:00
|
|
|
// gracefully write the close message to the connection
|
|
|
|
err := conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "websocket write close message error")
|
|
|
|
}
|
|
|
|
|
2021-12-30 08:47:39 +00:00
|
|
|
// let the reader close the connection
|
|
|
|
<-time.After(time.Second)
|
|
|
|
return nil
|
2021-12-29 09:30:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Stream) fetchListenKey(ctx context.Context) (string, error) {
|
|
|
|
if s.IsMargin {
|
|
|
|
if s.IsIsolatedMargin {
|
|
|
|
log.Debugf("isolated margin %s is enabled, requesting margin user stream listen key...", s.IsolatedMarginSymbol)
|
|
|
|
req := s.Client.NewStartIsolatedMarginUserStreamService()
|
|
|
|
req.Symbol(s.IsolatedMarginSymbol)
|
|
|
|
return req.Do(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Debugf("margin mode is enabled, requesting margin user stream listen key...")
|
|
|
|
req := s.Client.NewStartMarginUserStreamService()
|
|
|
|
return req.Do(ctx)
|
|
|
|
} else if s.IsFutures {
|
|
|
|
log.Debugf("futures mode is enabled, requesting futures user stream listen key...")
|
|
|
|
req := s.futuresClient.NewStartUserStreamService()
|
|
|
|
return req.Do(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Debugf("spot mode is enabled, requesting user stream listen key...")
|
|
|
|
return s.Client.NewStartUserStreamService().Do(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Stream) keepaliveListenKey(ctx context.Context, listenKey string) error {
|
|
|
|
log.Debugf("keepalive listen key: %s", util.MaskKey(listenKey))
|
|
|
|
if s.IsMargin {
|
|
|
|
if s.IsIsolatedMargin {
|
|
|
|
req := s.Client.NewKeepaliveIsolatedMarginUserStreamService().ListenKey(listenKey)
|
|
|
|
req.Symbol(s.IsolatedMarginSymbol)
|
|
|
|
return req.Do(ctx)
|
|
|
|
}
|
|
|
|
req := s.Client.NewKeepaliveMarginUserStreamService().ListenKey(listenKey)
|
|
|
|
return req.Do(ctx)
|
|
|
|
} else if s.IsFutures {
|
|
|
|
req := s.futuresClient.NewKeepaliveUserStreamService().ListenKey(listenKey)
|
|
|
|
return req.Do(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
return s.Client.NewKeepaliveUserStreamService().ListenKey(listenKey).Do(ctx)
|
|
|
|
}
|
|
|
|
|
2021-12-30 08:47:39 +00:00
|
|
|
func (s *Stream) closeListenKey(ctx context.Context, listenKey string) (err error) {
|
2020-12-02 14:19:31 +00:00
|
|
|
// should use background context to invalidate the user stream
|
2021-12-29 09:30:04 +00:00
|
|
|
log.Debugf("closing listen key: %s", util.MaskKey(listenKey))
|
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
|
|
|
}
|
|
|
|
|
2021-12-12 07:40:03 +00:00
|
|
|
} else if s.IsFutures {
|
|
|
|
req := s.futuresClient.NewCloseUserStreamService().ListenKey(listenKey)
|
|
|
|
err = req.Do(ctx)
|
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 {
|
2021-12-22 17:16:08 +00:00
|
|
|
log.WithError(err).Errorf("error deleting listen key: %s", util.MaskKey(listenKey))
|
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
|
|
|
}
|
2021-12-30 08:30:02 +00:00
|
|
|
|
|
|
|
// listenKeyKeepAlive
|
|
|
|
// From Binance
|
|
|
|
// Keepalive a user data stream to prevent a time out. User data streams will close after 60 minutes.
|
|
|
|
// It's recommended to send a ping about every 30 minutes.
|
|
|
|
func (s *Stream) listenKeyKeepAlive(ctx context.Context, listenKey string) {
|
|
|
|
keepAliveTicker := time.NewTicker(listenKeyKeepAliveInterval)
|
|
|
|
defer keepAliveTicker.Stop()
|
|
|
|
|
|
|
|
// if we exit, we should invalidate the existing listen key
|
|
|
|
defer func() {
|
|
|
|
log.Debugf("keepalive worker stopped")
|
2021-12-30 08:47:39 +00:00
|
|
|
if err := s.closeListenKey(context.Background(), listenKey); err != nil {
|
2021-12-30 08:30:02 +00:00
|
|
|
log.WithError(err).Errorf("invalidate listen key error: %v key: %s", err, util.MaskKey(listenKey))
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
|
|
|
|
case <-s.CloseC:
|
|
|
|
return
|
|
|
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
|
|
|
|
case <-keepAliveTicker.C:
|
|
|
|
for i := 0; i < 5; i++ {
|
|
|
|
err := s.keepaliveListenKey(ctx, listenKey)
|
|
|
|
if err == nil {
|
|
|
|
break
|
|
|
|
} else {
|
|
|
|
switch err.(type) {
|
|
|
|
case net.Error:
|
|
|
|
log.WithError(err).Errorf("listen key keep-alive network error: %v key: %s", err, util.MaskKey(listenKey))
|
|
|
|
time.Sleep(5 * time.Second)
|
|
|
|
continue
|
|
|
|
|
|
|
|
default:
|
|
|
|
log.WithError(err).Errorf("listen key keep-alive unexpected error: %v key: %s", err, util.MaskKey(listenKey))
|
|
|
|
s.Reconnect()
|
|
|
|
return
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|