bbgo_origin/bbgo/exchange/binance/stream.go

237 lines
5.4 KiB
Go
Raw Normal View History

2020-07-11 05:02:53 +00:00
package binance
import (
"context"
2020-08-07 01:15:50 +00:00
"strings"
2020-07-13 08:03:47 +00:00
"time"
"github.com/c9s/bbgo/pkg/util"
2020-07-11 05:02:53 +00:00
"github.com/adshao/go-binance"
"github.com/gorilla/websocket"
2020-07-13 08:03:47 +00:00
"github.com/c9s/bbgo/pkg/bbgo/types"
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-07-11 08:07:09 +00:00
//go:generate callbackgen -type PrivateStream -interface
2020-07-11 05:02:53 +00:00
type PrivateStream struct {
types.StandardPrivateStream
2020-08-07 01:15:50 +00:00
Client *binance.Client
ListenKey string
Conn *websocket.Conn
2020-07-11 08:07:09 +00:00
connectCallbacks []func(stream *PrivateStream)
// custom callbacks
kLineEventCallbacks []func(e *KLineEvent)
kLineClosedEventCallbacks []func(e *KLineEvent)
2020-07-11 08:07:09 +00:00
balanceUpdateEventCallbacks []func(event *BalanceUpdateEvent)
outboundAccountInfoEventCallbacks []func(event *OutboundAccountInfoEvent)
executionReportEventCallbacks []func(event *ExecutionReportEvent)
2020-07-11 05:02:53 +00:00
}
2020-07-12 14:52:24 +00:00
func (s *PrivateStream) dial(listenKey string) (*websocket.Conn, error) {
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
}
return conn, nil
}
func (s *PrivateStream) connect(ctx context.Context) error {
log.Infof("[binance] creating user data stream...")
listenKey, err := s.Client.NewStartUserStreamService().Do(ctx)
if err != nil {
return err
}
s.ListenKey = listenKey
log.Infof("[binance] user data stream created. listenKey: %s", s.ListenKey)
conn, err := s.dial(s.ListenKey)
2020-07-11 05:02:53 +00:00
if err != nil {
return err
}
2020-07-11 08:07:09 +00:00
log.Infof("[binance] websocket connected")
2020-07-11 05:02:53 +00:00
s.Conn = conn
2020-07-11 08:07:09 +00:00
s.EmitConnect(s)
2020-07-11 05:02:53 +00:00
var params []string
for _, subscription := range s.Subscriptions {
params = append(params, subscription.String())
}
2020-07-11 08:07:09 +00:00
log.Infof("[binance] subscribing channels: %+v", params)
2020-07-12 14:52:24 +00:00
return conn.WriteJSON(StreamRequest{
2020-07-11 05:02:53 +00:00
Method: "SUBSCRIBE",
Params: params,
ID: 1,
})
2020-07-12 14:52:24 +00:00
}
2020-07-11 05:02:53 +00:00
func (s *PrivateStream) Connect(ctx context.Context) error {
2020-07-12 14:52:24 +00:00
err := s.connect(ctx)
2020-07-11 05:02:53 +00:00
if err != nil {
return err
}
go s.read(ctx)
2020-07-11 05:02:53 +00:00
return nil
}
func (s *PrivateStream) read(ctx context.Context) {
2020-07-11 05:02:53 +00:00
2020-08-07 01:17:35 +00:00
pingTicker := time.NewTicker(1 * time.Minute)
defer pingTicker.Stop()
keepAliveTicker := time.NewTicker(5 * time.Minute)
defer keepAliveTicker.Stop()
2020-07-11 05:02:53 +00:00
for {
select {
case <-ctx.Done():
return
2020-08-07 01:17:35 +00:00
case <-keepAliveTicker.C:
err := s.Client.NewKeepaliveUserStreamService().ListenKey(s.ListenKey).Do(ctx)
if err != nil {
log.WithError(err).Errorf("listen key keep-alive error: %v key: %s", err, maskListenKey(s.ListenKey))
}
case <-pingTicker.C:
2020-08-07 01:15:50 +00:00
if err := s.Conn.WriteControl(websocket.PingMessage, []byte("hb"), time.Now().Add(1*time.Second)); err != nil {
2020-07-18 02:43:27 +00:00
log.WithError(err).Error("ping error", err)
}
2020-07-11 05:02:53 +00:00
default:
2020-07-13 05:25:48 +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()
if err != nil {
2020-07-12 17:06:04 +00:00
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
log.WithError(err).Errorf("read error: %s", err.Error())
}
2020-07-12 14:52:24 +00:00
// reconnect
for err != nil {
2020-07-12 17:06:04 +00:00
select {
case <-ctx.Done():
return
default:
2020-07-13 05:25:48 +00:00
_ = s.invalidateListenKey(ctx, s.ListenKey)
2020-07-12 17:06:04 +00:00
err = s.connect(ctx)
time.Sleep(5 * time.Second)
}
2020-07-12 14:52:24 +00:00
}
continue
2020-07-11 05:02:53 +00:00
}
// skip non-text messages
if mt != websocket.TextMessage {
continue
}
2020-07-11 08:07:09 +00:00
log.Debugf("[binance] recv: %s", message)
2020-07-11 05:02:53 +00:00
e, err := ParseEvent(string(message))
if err != nil {
2020-07-11 08:07:09 +00:00
log.WithError(err).Errorf("[binance] event parse error")
2020-07-11 05:02:53 +00:00
continue
}
2020-07-13 05:25:48 +00:00
// log.Notify("[binance] event: %+v", e)
2020-07-11 08:07:09 +00:00
switch e := e.(type) {
case *OutboundAccountInfoEvent:
log.Info(e.Event, " ", e.Balances)
s.EmitOutboundAccountInfoEvent(e)
snapshot := map[string]types.Balance{}
for _, balance := range e.Balances {
available := util.MustParseFloat(balance.Free)
locked := util.MustParseFloat(balance.Locked)
snapshot[balance.Asset] = types.Balance{
Currency: balance.Asset,
Available: available,
Locked: locked,
}
}
s.EmitBalanceSnapshot(snapshot)
2020-07-11 08:07:09 +00:00
case *BalanceUpdateEvent:
log.Info(e.Event, " ", e.Asset, " ", e.Delta)
s.EmitBalanceUpdateEvent(e)
case *KLineEvent:
log.Info(e.Event, " ", e.KLine, " ", e.KLine.Interval)
s.EmitKLineEvent(e)
if e.KLine.Closed {
s.EmitKLineClosedEvent(e)
s.EmitKLineClosed(e.KLine.KLine())
2020-07-11 08:07:09 +00:00
}
case *ExecutionReportEvent:
log.Info(e.Event, " ", e)
2020-07-11 08:07:09 +00:00
s.EmitExecutionReportEvent(e)
switch e.CurrentExecutionType {
case "TRADE":
trade, err := e.Trade()
if err != nil {
break
}
s.EmitTrade(trade)
}
}
2020-07-11 05:02:53 +00:00
}
}
}
2020-07-12 14:52:24 +00:00
func (s *PrivateStream) invalidateListenKey(ctx context.Context, listenKey string) error {
// use background context to invalidate the user stream
err := s.Client.NewCloseUserStreamService().ListenKey(listenKey).Do(ctx)
2020-07-11 05:02:53 +00:00
if err != nil {
2020-07-12 14:52:24 +00:00
log.WithError(err).Error("[binance] 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
func (s *PrivateStream) Close() error {
log.Infof("[binance] closing user data stream...")
defer s.Conn.Close()
err := s.invalidateListenKey(context.Background(), s.ListenKey)
log.Infof("[binance] user data stream closed")
return err
}
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)
}