bbgo_origin/pkg/exchange/kucoin/stream.go

314 lines
8.0 KiB
Go
Raw Permalink Normal View History

2021-12-22 13:06:21 +00:00
package kucoin
import (
"context"
"time"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
"github.com/c9s/bbgo/pkg/depth"
2021-12-22 13:06:21 +00:00
"github.com/c9s/bbgo/pkg/exchange/kucoin/kucoinapi"
"github.com/c9s/bbgo/pkg/fixedpoint"
2021-12-22 13:06:21 +00:00
"github.com/c9s/bbgo/pkg/types"
"github.com/c9s/bbgo/pkg/util"
2021-12-22 13:06:21 +00:00
)
const readTimeout = 30 * time.Second
2021-12-22 13:06:21 +00:00
//go:generate callbackgen -type Stream -interface
type Stream struct {
types.StandardStream
client *kucoinapi.RestClient
exchange *Exchange
2021-12-22 13:06:21 +00:00
bullet *kucoinapi.Bullet
candleEventCallbacks []func(candle *WebSocketCandleEvent, e *WebSocketEvent)
orderBookL2EventCallbacks []func(e *WebSocketOrderBookL2Event)
tickerEventCallbacks []func(e *WebSocketTickerEvent)
accountBalanceEventCallbacks []func(e *WebSocketAccountBalanceEvent)
privateOrderEventCallbacks []func(e *WebSocketPrivateOrderEvent)
2021-12-23 03:04:22 +00:00
lastCandle map[string]types.KLine
depthBuffers map[string]*depth.Buffer
2021-12-22 13:06:21 +00:00
}
func NewStream(client *kucoinapi.RestClient, ex *Exchange) *Stream {
2021-12-22 13:06:21 +00:00
stream := &Stream{
StandardStream: types.NewStandardStream(),
client: client,
exchange: ex,
lastCandle: make(map[string]types.KLine),
depthBuffers: make(map[string]*depth.Buffer),
2021-12-22 13:06:21 +00:00
}
stream.SetParser(parseWebSocketEvent)
stream.SetDispatcher(stream.dispatchEvent)
stream.SetEndpointCreator(stream.getEndpoint)
2021-12-22 17:32:02 +00:00
stream.OnConnect(stream.handleConnect)
2021-12-23 03:28:59 +00:00
stream.OnCandleEvent(stream.handleCandleEvent)
stream.OnOrderBookL2Event(stream.handleOrderBookL2Event)
stream.OnTickerEvent(stream.handleTickerEvent)
stream.OnPrivateOrderEvent(stream.handlePrivateOrderEvent)
stream.OnAccountBalanceEvent(stream.handleAccountBalanceEvent)
2021-12-22 17:32:02 +00:00
return stream
}
2021-12-22 13:06:21 +00:00
func (s *Stream) handleCandleEvent(candle *WebSocketCandleEvent, e *WebSocketEvent) {
kline := candle.KLine()
last, ok := s.lastCandle[e.Topic]
if ok && kline.StartTime.After(last.StartTime.Time()) || e.Subject == WebSocketSubjectTradeCandlesAdd {
last.Closed = true
s.EmitKLineClosed(last)
}
s.EmitKLine(kline)
s.lastCandle[e.Topic] = kline
}
2021-12-22 13:06:21 +00:00
func (s *Stream) handleOrderBookL2Event(e *WebSocketOrderBookL2Event) {
f, ok := s.depthBuffers[e.Symbol]
if ok {
f.AddUpdate(types.SliceOrderBook{
Symbol: toGlobalSymbol(e.Symbol),
Bids: e.Changes.Bids,
Asks: e.Changes.Asks,
}, e.SequenceStart, e.SequenceEnd)
} else {
f = depth.NewBuffer(func() (types.SliceOrderBook, int64, error) {
return s.exchange.QueryDepth(context.Background(), e.Symbol)
})
s.depthBuffers[e.Symbol] = f
f.SetBufferingPeriod(time.Second)
f.OnReady(func(snapshot types.SliceOrderBook, updates []depth.Update) {
if valid, err := snapshot.IsValid(); !valid {
log.Errorf("depth snapshot is invalid, error: %v", err)
return
}
s.EmitBookSnapshot(snapshot)
for _, u := range updates {
s.EmitBookUpdate(u.Object)
}
})
f.OnPush(func(update depth.Update) {
s.EmitBookUpdate(update.Object)
})
}
}
2021-12-22 13:06:21 +00:00
func (s *Stream) handleTickerEvent(e *WebSocketTickerEvent) {}
2021-12-23 03:28:59 +00:00
func (s *Stream) handleAccountBalanceEvent(e *WebSocketAccountBalanceEvent) {
bm := types.BalanceMap{}
bm[e.Currency] = types.Balance{
Currency: e.Currency,
Available: e.Available,
Locked: e.Hold,
}
s.StandardStream.EmitBalanceUpdate(bm)
}
func (s *Stream) handlePrivateOrderEvent(e *WebSocketPrivateOrderEvent) {
if e.Type == "match" {
s.StandardStream.EmitTradeUpdate(types.Trade{
OrderID: hashStringID(e.OrderId),
ID: hashStringID(e.TradeId),
Exchange: types.ExchangeKucoin,
Price: e.MatchPrice,
Quantity: e.MatchSize,
QuoteQuantity: e.MatchPrice.Mul(e.MatchSize),
Symbol: toGlobalSymbol(e.Symbol),
Side: toGlobalSide(e.Side),
IsBuyer: e.Side == "buy",
IsMaker: e.Liquidity == "maker",
Time: types.Time(e.Ts.Time()),
Fee: fixedpoint.Zero, // not supported
FeeCurrency: "", // not supported
})
}
switch e.Type {
case "open", "match", "filled", "canceled":
status := types.OrderStatusNew
if e.Status == "done" {
if e.FilledSize == e.Size {
status = types.OrderStatusFilled
} else {
status = types.OrderStatusCanceled
}
} else if e.Status == "open" {
if e.FilledSize.Sign() > 0 {
status = types.OrderStatusPartiallyFilled
}
}
s.StandardStream.EmitOrderUpdate(types.Order{
SubmitOrder: types.SubmitOrder{
ClientOrderID: e.ClientOid,
Symbol: toGlobalSymbol(e.Symbol),
Side: toGlobalSide(e.Side),
Type: toGlobalOrderType(e.OrderType),
Quantity: e.Size,
Price: e.Price,
},
Exchange: types.ExchangeKucoin,
OrderID: hashStringID(e.OrderId),
UUID: e.OrderId,
Status: status,
ExecutedQuantity: e.FilledSize,
IsWorking: e.Status == "open",
CreationTime: types.Time(e.OrderTime.Time()),
UpdateTime: types.Time(e.Ts.Time()),
})
default:
log.Warnf("unhandled private order type: %s, payload: %+v", e.Type, e)
2021-12-23 03:28:59 +00:00
}
}
2021-12-22 13:06:21 +00:00
2021-12-22 17:32:02 +00:00
func (s *Stream) handleConnect() {
2021-12-23 06:14:48 +00:00
if s.PublicOnly {
if err := s.sendSubscriptions(); err != nil {
2021-12-22 17:32:02 +00:00
log.WithError(err).Errorf("subscription error")
return
2021-12-22 13:06:21 +00:00
}
2021-12-22 18:49:56 +00:00
} else {
2021-12-23 13:09:40 +00:00
id := time.Now().UnixNano() / int64(time.Millisecond)
cmds := []WebSocketCommand{
2021-12-22 18:49:56 +00:00
{
Id: id,
Type: WebSocketMessageTypeSubscribe,
2021-12-22 18:49:56 +00:00
Topic: "/spotMarket/tradeOrders",
PrivateChannel: true,
Response: true,
},
{
Id: id + 1,
Type: WebSocketMessageTypeSubscribe,
2021-12-22 18:49:56 +00:00
Topic: "/account/balance",
PrivateChannel: true,
Response: true,
},
}
for _, cmd := range cmds {
2022-01-01 18:11:36 +00:00
if err := s.Conn.WriteJSON(cmd); err != nil {
2021-12-22 18:49:56 +00:00
log.WithError(err).Errorf("private subscribe write error, cmd: %+v", cmd)
}
}
2021-12-22 17:32:02 +00:00
}
2021-12-22 13:06:21 +00:00
}
2021-12-23 03:28:59 +00:00
func (s *Stream) sendSubscriptions() error {
cmds, err := convertSubscriptions(s.Subscriptions)
if err != nil {
return errors.Wrapf(err, "subscription convert error, subscriptions: %+v", s.Subscriptions)
}
for _, cmd := range cmds {
2022-01-01 18:11:36 +00:00
if err := s.Conn.WriteJSON(cmd); err != nil {
2021-12-23 03:28:59 +00:00
return errors.Wrapf(err, "subscribe write error, cmd: %+v", cmd)
}
}
return nil
}
2021-12-23 06:14:48 +00:00
// getEndpoint use the PublicOnly flag to check whether we should allocate a public bullet or private bullet
func (s *Stream) getEndpoint(ctx context.Context) (string, error) {
2021-12-22 16:45:59 +00:00
var bullet *kucoinapi.Bullet
var err error
2021-12-23 06:14:48 +00:00
if s.PublicOnly {
bullet, err = s.client.BulletService.NewGetPublicBulletRequest().Do(ctx)
2021-12-22 13:06:21 +00:00
} else {
bullet, err = s.client.BulletService.NewGetPrivateBulletRequest().Do(ctx)
2021-12-22 13:06:21 +00:00
}
2021-12-22 16:45:59 +00:00
if err != nil {
return "", err
}
url, err := bullet.URL()
if err != nil {
return "", err
}
2021-12-22 16:51:50 +00:00
s.bullet = bullet
log.Debugf("bullet: %+v", bullet)
2021-12-22 16:45:59 +00:00
return url.String(), nil
2021-12-22 13:06:21 +00:00
}
func (s *Stream) dispatchEvent(event interface{}) {
e, ok := event.(*WebSocketEvent)
if !ok {
return
2021-12-22 16:45:59 +00:00
}
2021-12-22 13:06:21 +00:00
if e.Object == nil {
return
2021-12-22 13:06:21 +00:00
}
2021-12-23 03:04:22 +00:00
switch et := e.Object.(type) {
2021-12-22 13:06:21 +00:00
case *WebSocketTickerEvent:
2021-12-23 03:04:22 +00:00
s.EmitTickerEvent(et)
case *WebSocketOrderBookL2Event:
2021-12-23 03:04:22 +00:00
s.EmitOrderBookL2Event(et)
case *WebSocketCandleEvent:
s.EmitCandleEvent(et, e)
2021-12-23 03:04:22 +00:00
case *WebSocketAccountBalanceEvent:
2021-12-23 03:04:22 +00:00
s.EmitAccountBalanceEvent(et)
case *WebSocketPrivateOrderEvent:
2021-12-23 03:04:22 +00:00
s.EmitPrivateOrderEvent(et)
default:
log.Warnf("unhandled event: %+v", et)
2021-12-22 13:06:21 +00:00
}
}
2021-12-22 16:53:55 +00:00
type WebSocketConnector interface {
Conn() *websocket.Conn
Reconnect()
}
func ping(ctx context.Context, w WebSocketConnector, interval time.Duration) {
log.Infof("starting websocket ping worker with interval %s", interval)
2021-12-22 16:51:50 +00:00
pingTicker := time.NewTicker(interval)
2021-12-22 13:06:21 +00:00
defer pingTicker.Stop()
for {
select {
case <-ctx.Done():
log.Debug("ping worker stopped")
return
case <-pingTicker.C:
2021-12-22 16:53:55 +00:00
conn := w.Conn()
if err := conn.WriteJSON(WebSocketCommand{
Id: util.UnixMilli(),
Type: "ping",
}); err != nil {
log.WithError(err).Error("websocket ping error", err)
w.Reconnect()
}
2021-12-22 13:06:21 +00:00
if err := conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(3*time.Second)); err != nil {
log.WithError(err).Error("ping error", err)
2021-12-22 16:53:55 +00:00
w.Reconnect()
2021-12-22 13:06:21 +00:00
}
}
}
}