2021-12-22 13:06:21 +00:00
|
|
|
package kucoin
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
|
2021-12-25 17:27:22 +00:00
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
|
2021-12-25 11:34:27 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/depth"
|
2021-12-22 13:06:21 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/exchange/kucoin/kucoinapi"
|
2022-06-17 04:01:15 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
2021-12-22 13:06:21 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
2021-12-23 14:20:47 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/util"
|
2021-12-22 13:06:21 +00:00
|
|
|
)
|
|
|
|
|
2021-12-23 05:39:15 +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
|
|
|
|
|
2022-06-17 04:01:15 +00:00
|
|
|
client *kucoinapi.RestClient
|
|
|
|
exchange *Exchange
|
2021-12-22 13:06:21 +00:00
|
|
|
|
2021-12-25 17:27:22 +00:00
|
|
|
bullet *kucoinapi.Bullet
|
2021-12-23 09:32:56 +00:00
|
|
|
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
|
|
|
|
2021-12-25 11:34:27 +00:00
|
|
|
lastCandle map[string]types.KLine
|
|
|
|
depthBuffers map[string]*depth.Buffer
|
2021-12-22 13:06:21 +00:00
|
|
|
}
|
|
|
|
|
2021-12-25 15:53:34 +00:00
|
|
|
func NewStream(client *kucoinapi.RestClient, ex *Exchange) *Stream {
|
2021-12-22 13:06:21 +00:00
|
|
|
stream := &Stream{
|
2022-01-01 17:54:47 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2022-01-01 17:54:47 +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)
|
2021-12-23 05:39:15 +00:00
|
|
|
stream.OnPrivateOrderEvent(stream.handlePrivateOrderEvent)
|
2021-12-23 09:32:56 +00:00
|
|
|
stream.OnAccountBalanceEvent(stream.handleAccountBalanceEvent)
|
2021-12-22 17:32:02 +00:00
|
|
|
return stream
|
|
|
|
}
|
2021-12-22 13:06:21 +00:00
|
|
|
|
2021-12-23 09:32:56 +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
|
|
|
|
2021-12-25 11:34:27 +00:00
|
|
|
func (s *Stream) handleOrderBookL2Event(e *WebSocketOrderBookL2Event) {
|
|
|
|
f, ok := s.depthBuffers[e.Symbol]
|
2021-12-25 15:53:34 +00:00
|
|
|
if ok {
|
|
|
|
f.AddUpdate(types.SliceOrderBook{
|
|
|
|
Symbol: toGlobalSymbol(e.Symbol),
|
2023-09-01 09:02:08 +00:00
|
|
|
Time: e.Time.Time(),
|
2021-12-25 15:53:34 +00:00
|
|
|
Bids: e.Changes.Bids,
|
|
|
|
Asks: e.Changes.Asks,
|
|
|
|
}, e.SequenceStart, e.SequenceEnd)
|
|
|
|
} else {
|
2021-12-25 11:34:27 +00:00
|
|
|
f = depth.NewBuffer(func() (types.SliceOrderBook, int64, error) {
|
2021-12-25 15:53:34 +00:00
|
|
|
return s.exchange.QueryDepth(context.Background(), e.Symbol)
|
2024-11-16 06:58:05 +00:00
|
|
|
}, 3*time.Second)
|
2021-12-25 11:34:27 +00:00
|
|
|
s.depthBuffers[e.Symbol] = f
|
|
|
|
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
|
|
|
|
2021-12-23 09:32:56 +00:00
|
|
|
func (s *Stream) handleTickerEvent(e *WebSocketTickerEvent) {}
|
2021-12-23 03:28:59 +00:00
|
|
|
|
2021-12-23 09:32:56 +00:00
|
|
|
func (s *Stream) handleAccountBalanceEvent(e *WebSocketAccountBalanceEvent) {
|
2021-12-23 05:39:15 +00:00
|
|
|
bm := types.BalanceMap{}
|
|
|
|
bm[e.Currency] = types.Balance{
|
|
|
|
Currency: e.Currency,
|
|
|
|
Available: e.Available,
|
|
|
|
Locked: e.Hold,
|
|
|
|
}
|
|
|
|
s.StandardStream.EmitBalanceUpdate(bm)
|
|
|
|
}
|
|
|
|
|
2021-12-23 09:32:56 +00:00
|
|
|
func (s *Stream) handlePrivateOrderEvent(e *WebSocketPrivateOrderEvent) {
|
2021-12-23 05:39:15 +00:00
|
|
|
if e.Type == "match" {
|
|
|
|
s.StandardStream.EmitTradeUpdate(types.Trade{
|
|
|
|
OrderID: hashStringID(e.OrderId),
|
|
|
|
ID: hashStringID(e.TradeId),
|
|
|
|
Exchange: types.ExchangeKucoin,
|
2022-02-03 04:55:25 +00:00
|
|
|
Price: e.MatchPrice,
|
|
|
|
Quantity: e.MatchSize,
|
|
|
|
QuoteQuantity: e.MatchPrice.Mul(e.MatchSize),
|
2021-12-23 05:39:15 +00:00
|
|
|
Symbol: toGlobalSymbol(e.Symbol),
|
|
|
|
Side: toGlobalSide(e.Side),
|
|
|
|
IsBuyer: e.Side == "buy",
|
|
|
|
IsMaker: e.Liquidity == "maker",
|
|
|
|
Time: types.Time(e.Ts.Time()),
|
2022-06-17 04:01:15 +00:00
|
|
|
Fee: fixedpoint.Zero, // not supported
|
|
|
|
FeeCurrency: "", // not supported
|
2021-12-23 05:39:15 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
switch e.Type {
|
2021-12-30 14:02:50 +00:00
|
|
|
case "open", "match", "filled", "canceled":
|
2021-12-23 05:39:15 +00:00
|
|
|
status := types.OrderStatusNew
|
|
|
|
if e.Status == "done" {
|
2021-12-25 17:27:22 +00:00
|
|
|
if e.FilledSize == e.Size {
|
|
|
|
status = types.OrderStatusFilled
|
|
|
|
} else {
|
|
|
|
status = types.OrderStatusCanceled
|
|
|
|
}
|
|
|
|
} else if e.Status == "open" {
|
2022-02-03 04:55:25 +00:00
|
|
|
if e.FilledSize.Sign() > 0 {
|
2021-12-25 17:27:22 +00:00
|
|
|
status = types.OrderStatusPartiallyFilled
|
|
|
|
}
|
2021-12-23 05:39:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
s.StandardStream.EmitOrderUpdate(types.Order{
|
|
|
|
SubmitOrder: types.SubmitOrder{
|
2021-12-30 13:39:50 +00:00
|
|
|
ClientOrderID: e.ClientOid,
|
2021-12-30 14:02:50 +00:00
|
|
|
Symbol: toGlobalSymbol(e.Symbol),
|
|
|
|
Side: toGlobalSide(e.Side),
|
|
|
|
Type: toGlobalOrderType(e.OrderType),
|
2022-02-03 04:55:25 +00:00
|
|
|
Quantity: e.Size,
|
|
|
|
Price: e.Price,
|
2021-12-23 05:39:15 +00:00
|
|
|
},
|
|
|
|
Exchange: types.ExchangeKucoin,
|
|
|
|
OrderID: hashStringID(e.OrderId),
|
2021-12-25 17:27:22 +00:00
|
|
|
UUID: e.OrderId,
|
2021-12-23 05:39:15 +00:00
|
|
|
Status: status,
|
2022-02-03 04:55:25 +00:00
|
|
|
ExecutedQuantity: e.FilledSize,
|
2021-12-25 17:27:22 +00:00
|
|
|
IsWorking: e.Status == "open",
|
2021-12-23 05:39:15 +00:00
|
|
|
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-23 05:39:15 +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 {
|
2021-12-22 17:54:53 +00:00
|
|
|
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 {
|
2023-09-14 03:01:20 +00:00
|
|
|
// Emit Auth before establishing the connection to prevent the caller from missing the Update data after
|
|
|
|
// creating the order.
|
|
|
|
s.EmitAuth()
|
2021-12-23 13:09:40 +00:00
|
|
|
id := time.Now().UnixNano() / int64(time.Millisecond)
|
2021-12-23 09:32:56 +00:00
|
|
|
cmds := []WebSocketCommand{
|
2021-12-22 18:49:56 +00:00
|
|
|
{
|
|
|
|
Id: id,
|
2021-12-23 09:32:56 +00:00
|
|
|
Type: WebSocketMessageTypeSubscribe,
|
2021-12-22 18:49:56 +00:00
|
|
|
Topic: "/spotMarket/tradeOrders",
|
|
|
|
PrivateChannel: true,
|
|
|
|
Response: true,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
Id: id + 1,
|
2021-12-23 09:32:56 +00:00
|
|
|
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
|
2022-01-01 17:54:47 +00:00
|
|
|
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 {
|
2022-01-01 17:54:47 +00:00
|
|
|
bullet, err = s.client.BulletService.NewGetPublicBulletRequest().Do(ctx)
|
2021-12-22 13:06:21 +00:00
|
|
|
} else {
|
2022-01-01 17:54:47 +00:00
|
|
|
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
|
|
|
|
|
2022-01-01 17:54:47 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2022-01-01 17:54:47 +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
|
|
|
|
2022-01-01 17:54:47 +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
|
|
|
|
2021-12-23 09:32:56 +00:00
|
|
|
case *WebSocketTickerEvent:
|
2021-12-23 03:04:22 +00:00
|
|
|
s.EmitTickerEvent(et)
|
|
|
|
|
2021-12-23 09:32:56 +00:00
|
|
|
case *WebSocketOrderBookL2Event:
|
2021-12-23 03:04:22 +00:00
|
|
|
s.EmitOrderBookL2Event(et)
|
|
|
|
|
2021-12-23 09:32:56 +00:00
|
|
|
case *WebSocketCandleEvent:
|
|
|
|
s.EmitCandleEvent(et, e)
|
2021-12-23 03:04:22 +00:00
|
|
|
|
2021-12-23 09:32:56 +00:00
|
|
|
case *WebSocketAccountBalanceEvent:
|
2021-12-23 03:04:22 +00:00
|
|
|
s.EmitAccountBalanceEvent(et)
|
|
|
|
|
2021-12-23 09:32:56 +00:00
|
|
|
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) {
|
2021-12-23 14:20:47 +00:00
|
|
|
log.Infof("starting websocket ping worker with interval %s", interval)
|
2021-12-22 17:54:53 +00:00
|
|
|
|
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()
|
2021-12-22 17:54:53 +00:00
|
|
|
|
2021-12-23 09:32:56 +00:00
|
|
|
if err := conn.WriteJSON(WebSocketCommand{
|
2021-12-23 14:20:47 +00:00
|
|
|
Id: util.UnixMilli(),
|
2021-12-22 17:54:53 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|