2020-07-11 05:02:53 +00:00
|
|
|
package binance
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2020-07-15 13:02:08 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/util"
|
2020-07-13 08:03:47 +00:00
|
|
|
"time"
|
|
|
|
|
2020-07-11 05:02:53 +00:00
|
|
|
"github.com/adshao/go-binance"
|
|
|
|
"github.com/gorilla/websocket"
|
2020-07-11 08:07:09 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
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 {
|
2020-07-15 13:02:08 +00:00
|
|
|
types.StandardPrivateStream
|
|
|
|
|
2020-07-11 05:02:53 +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(event *KLineEvent)
|
|
|
|
kLineClosedEventCallbacks []func(event *KLineEvent)
|
|
|
|
|
|
|
|
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
|
|
|
|
2020-07-12 14:52:24 +00:00
|
|
|
func (s *PrivateStream) Connect(ctx context.Context, eventC chan interface{}) error {
|
|
|
|
err := s.connect(ctx)
|
2020-07-11 05:02:53 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
go s.read(ctx, eventC)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *PrivateStream) read(ctx context.Context, eventC chan interface{}) {
|
|
|
|
defer close(eventC)
|
|
|
|
|
2020-07-14 06:54:23 +00:00
|
|
|
ticker := time.NewTicker(10 * time.Minute)
|
2020-07-11 05:02:53 +00:00
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
|
|
|
|
case <-ticker.C:
|
2020-07-18 02:43:27 +00:00
|
|
|
if err := s.Conn.WriteControl(websocket.PingMessage, []byte("hb"), time.Now().Add(1 * time.Second)) ; err != nil {
|
|
|
|
log.WithError(err).Error("ping error", err)
|
|
|
|
}
|
|
|
|
|
2020-07-11 05:02:53 +00:00
|
|
|
err := s.Client.NewKeepaliveUserStreamService().ListenKey(s.ListenKey).Do(ctx)
|
|
|
|
if err != nil {
|
2020-07-11 08:07:09 +00:00
|
|
|
log.WithError(err).Error("listen key keep-alive 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)
|
|
|
|
|
2020-07-15 13:02:08 +00:00
|
|
|
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)
|
2020-07-15 13:02:08 +00:00
|
|
|
s.EmitKLineClosed(e.KLine)
|
2020-07-11 08:07:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
case *ExecutionReportEvent:
|
2020-07-11 08:40:07 +00:00
|
|
|
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
|
|
|
eventC <- e
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
}
|