2023-10-18 03:25:50 +00:00
|
|
|
package bitget
|
|
|
|
|
|
|
|
import (
|
2023-10-24 14:17:08 +00:00
|
|
|
"bytes"
|
2023-10-18 03:25:50 +00:00
|
|
|
"context"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2023-11-10 13:56:18 +00:00
|
|
|
"strconv"
|
2023-10-31 13:53:13 +00:00
|
|
|
"strings"
|
2023-11-10 13:56:18 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
2023-10-18 03:25:50 +00:00
|
|
|
|
|
|
|
"github.com/c9s/bbgo/pkg/exchange/bitget/bitgetapi"
|
2023-11-10 13:56:18 +00:00
|
|
|
v2 "github.com/c9s/bbgo/pkg/exchange/bitget/bitgetapi/v2"
|
2023-10-18 03:25:50 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
2023-10-24 14:17:08 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
pingBytes = []byte("ping")
|
|
|
|
pongBytes = []byte("pong")
|
2023-10-18 03:25:50 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
//go:generate callbackgen -type Stream
|
|
|
|
type Stream struct {
|
|
|
|
types.StandardStream
|
|
|
|
|
2023-11-14 03:23:30 +00:00
|
|
|
privateChannelSymbols []string
|
|
|
|
|
2023-11-10 13:56:18 +00:00
|
|
|
key, secret, passphrase string
|
2023-10-19 10:12:05 +00:00
|
|
|
bookEventCallbacks []func(o BookEvent)
|
|
|
|
marketTradeEventCallbacks []func(o MarketTradeEvent)
|
2023-10-31 13:53:13 +00:00
|
|
|
KLineEventCallbacks []func(o KLineEvent)
|
|
|
|
|
2023-11-14 03:23:30 +00:00
|
|
|
accountEventCallbacks []func(e AccountEvent)
|
|
|
|
orderTradeEventCallbacks []func(e OrderTradeEvent)
|
2023-11-10 14:35:39 +00:00
|
|
|
|
2023-10-31 13:53:13 +00:00
|
|
|
lastCandle map[string]types.KLine
|
2023-10-18 03:25:50 +00:00
|
|
|
}
|
|
|
|
|
2023-11-10 13:56:18 +00:00
|
|
|
func NewStream(key, secret, passphrase string) *Stream {
|
2023-10-18 03:25:50 +00:00
|
|
|
stream := &Stream{
|
|
|
|
StandardStream: types.NewStandardStream(),
|
2023-10-31 13:53:13 +00:00
|
|
|
lastCandle: map[string]types.KLine{},
|
2023-11-10 13:56:18 +00:00
|
|
|
key: key,
|
|
|
|
secret: secret,
|
|
|
|
passphrase: passphrase,
|
2023-10-18 03:25:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
stream.SetEndpointCreator(stream.createEndpoint)
|
|
|
|
stream.SetParser(parseWebSocketEvent)
|
|
|
|
stream.SetDispatcher(stream.dispatchEvent)
|
2023-10-24 14:17:08 +00:00
|
|
|
stream.SetHeartBeat(stream.ping)
|
2023-10-18 03:25:50 +00:00
|
|
|
stream.OnConnect(stream.handlerConnect)
|
|
|
|
|
|
|
|
stream.OnBookEvent(stream.handleBookEvent)
|
2023-10-19 10:12:05 +00:00
|
|
|
stream.OnMarketTradeEvent(stream.handleMaretTradeEvent)
|
2023-10-31 13:53:13 +00:00
|
|
|
stream.OnKLineEvent(stream.handleKLineEvent)
|
2023-11-10 14:35:39 +00:00
|
|
|
|
|
|
|
stream.OnAuth(stream.handleAuth)
|
|
|
|
stream.OnAccountEvent(stream.handleAccountEvent)
|
2023-11-14 03:23:30 +00:00
|
|
|
stream.OnOrderTradeEvent(stream.handleOrderTradeEvent)
|
2023-10-18 03:25:50 +00:00
|
|
|
return stream
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Stream) syncSubscriptions(opType WsEventType) error {
|
|
|
|
if opType != WsEventUnsubscribe && opType != WsEventSubscribe {
|
|
|
|
return fmt.Errorf("unexpected subscription type: %v", opType)
|
|
|
|
}
|
|
|
|
|
|
|
|
logger := log.WithField("opType", opType)
|
|
|
|
args := []WsArg{}
|
|
|
|
for _, subscription := range s.Subscriptions {
|
|
|
|
arg, err := convertSubscription(subscription)
|
|
|
|
if err != nil {
|
|
|
|
logger.WithError(err).Errorf("convert error, subscription: %+v", subscription)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
args = append(args, arg)
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.Infof("%s channels: %+v", opType, args)
|
|
|
|
if err := s.Conn.WriteJSON(WsOp{
|
|
|
|
Op: opType,
|
|
|
|
Args: args,
|
|
|
|
}); err != nil {
|
|
|
|
logger.WithError(err).Error("failed to send request")
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Stream) Unsubscribe() {
|
|
|
|
// errors are handled in the syncSubscriptions, so they are skipped here.
|
|
|
|
_ = s.syncSubscriptions(WsEventUnsubscribe)
|
|
|
|
s.Resubscribe(func(old []types.Subscription) (new []types.Subscription, err error) {
|
|
|
|
// clear the subscriptions
|
|
|
|
return []types.Subscription{}, nil
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Stream) createEndpoint(_ context.Context) (string, error) {
|
|
|
|
var url string
|
|
|
|
if s.PublicOnly {
|
|
|
|
url = bitgetapi.PublicWebSocketURL
|
|
|
|
} else {
|
2023-11-10 13:56:18 +00:00
|
|
|
url = v2.PrivateWebSocketURL
|
2023-10-18 03:25:50 +00:00
|
|
|
}
|
|
|
|
return url, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Stream) dispatchEvent(event interface{}) {
|
|
|
|
switch e := event.(type) {
|
|
|
|
case *WsEvent:
|
|
|
|
if err := e.IsValid(); err != nil {
|
|
|
|
log.Errorf("invalid event: %v", err)
|
|
|
|
}
|
2023-11-10 14:35:39 +00:00
|
|
|
if e.IsAuthenticated() {
|
|
|
|
s.EmitAuth()
|
|
|
|
}
|
2023-10-18 03:25:50 +00:00
|
|
|
|
|
|
|
case *BookEvent:
|
|
|
|
s.EmitBookEvent(*e)
|
2023-10-19 10:12:05 +00:00
|
|
|
|
|
|
|
case *MarketTradeEvent:
|
|
|
|
s.EmitMarketTradeEvent(*e)
|
2023-10-24 14:17:08 +00:00
|
|
|
|
2023-10-31 13:53:13 +00:00
|
|
|
case *KLineEvent:
|
|
|
|
s.EmitKLineEvent(*e)
|
|
|
|
|
2023-11-10 14:35:39 +00:00
|
|
|
case *AccountEvent:
|
|
|
|
s.EmitAccountEvent(*e)
|
|
|
|
|
2023-11-14 03:23:30 +00:00
|
|
|
case *OrderTradeEvent:
|
|
|
|
s.EmitOrderTradeEvent(*e)
|
|
|
|
|
|
|
|
case []byte:
|
|
|
|
// We only handle the 'pong' case. Others are unexpected.
|
|
|
|
if !bytes.Equal(e, pongBytes) {
|
|
|
|
log.Errorf("invalid event: %q", e)
|
|
|
|
}
|
2023-10-18 03:25:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-14 03:23:30 +00:00
|
|
|
// handleAuth subscribe private stream channels. Because Bitget doesn't allow authentication and subscription to be used
|
|
|
|
// consecutively, we subscribe after authentication confirmation.
|
2023-11-10 14:35:39 +00:00
|
|
|
func (s *Stream) handleAuth() {
|
2023-11-14 03:23:30 +00:00
|
|
|
op := WsOp{
|
2023-11-10 14:35:39 +00:00
|
|
|
Op: WsEventSubscribe,
|
|
|
|
Args: []WsArg{
|
|
|
|
{
|
|
|
|
InstType: instSpV2,
|
|
|
|
Channel: ChannelAccount,
|
2023-11-14 03:23:30 +00:00
|
|
|
Coin: "default", // all coins
|
2023-11-10 14:35:39 +00:00
|
|
|
},
|
|
|
|
},
|
2023-11-14 03:23:30 +00:00
|
|
|
}
|
|
|
|
if len(s.privateChannelSymbols) > 0 {
|
|
|
|
for _, symbol := range s.privateChannelSymbols {
|
|
|
|
op.Args = append(op.Args, WsArg{
|
|
|
|
InstType: instSpV2,
|
|
|
|
Channel: ChannelOrders,
|
|
|
|
InstId: symbol,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
log.Warnf("you have not subscribed to any order channels")
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := s.Conn.WriteJSON(op); err != nil {
|
2023-11-10 14:35:39 +00:00
|
|
|
log.WithError(err).Error("failed to send subscription request")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-14 03:23:30 +00:00
|
|
|
func (s *Stream) SetPrivateChannelSymbols(symbols []string) {
|
|
|
|
s.privateChannelSymbols = symbols
|
|
|
|
}
|
|
|
|
|
2023-10-18 03:25:50 +00:00
|
|
|
func (s *Stream) handlerConnect() {
|
|
|
|
if s.PublicOnly {
|
|
|
|
// errors are handled in the syncSubscriptions, so they are skipped here.
|
|
|
|
_ = s.syncSubscriptions(WsEventSubscribe)
|
|
|
|
} else {
|
2023-11-10 13:56:18 +00:00
|
|
|
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
|
|
|
|
|
|
|
|
if err := s.Conn.WriteJSON(WsOp{
|
|
|
|
Op: WsEventLogin,
|
|
|
|
Args: []WsArg{
|
|
|
|
{
|
|
|
|
ApiKey: s.key,
|
|
|
|
Passphrase: s.passphrase,
|
|
|
|
Timestamp: timestamp,
|
|
|
|
Sign: bitgetapi.Sign(fmt.Sprintf("%sGET/user/verify", timestamp), s.secret),
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}); err != nil {
|
|
|
|
log.WithError(err).Error("failed to auth request")
|
|
|
|
return
|
|
|
|
}
|
2023-10-18 03:25:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Stream) handleBookEvent(o BookEvent) {
|
|
|
|
for _, book := range o.ToGlobalOrderBooks() {
|
2023-10-19 10:12:05 +00:00
|
|
|
switch o.actionType {
|
2023-10-18 03:25:50 +00:00
|
|
|
case ActionTypeSnapshot:
|
|
|
|
s.EmitBookSnapshot(book)
|
|
|
|
|
|
|
|
case ActionTypeUpdate:
|
|
|
|
s.EmitBookUpdate(book)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-24 14:17:08 +00:00
|
|
|
// ping implements the bitget text message of WebSocket PingPong.
|
|
|
|
func (s *Stream) ping(conn *websocket.Conn) error {
|
|
|
|
err := conn.WriteMessage(websocket.TextMessage, pingBytes)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("ping error", err)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-10-18 03:25:50 +00:00
|
|
|
func convertSubscription(sub types.Subscription) (WsArg, error) {
|
|
|
|
arg := WsArg{
|
|
|
|
// support spot only
|
|
|
|
InstType: instSp,
|
|
|
|
Channel: "",
|
|
|
|
InstId: sub.Symbol,
|
|
|
|
}
|
|
|
|
|
|
|
|
switch sub.Channel {
|
|
|
|
case types.BookChannel:
|
|
|
|
arg.Channel = ChannelOrderBook5
|
|
|
|
|
|
|
|
switch sub.Options.Depth {
|
|
|
|
case types.DepthLevel15:
|
|
|
|
arg.Channel = ChannelOrderBook15
|
|
|
|
case types.DepthLevel200:
|
|
|
|
log.Warn("*** The subscription events for the order book may return fewer than 200 bids/asks at a depth of 200. ***")
|
|
|
|
arg.Channel = ChannelOrderBook
|
|
|
|
}
|
|
|
|
return arg, nil
|
2023-10-19 10:12:05 +00:00
|
|
|
|
|
|
|
case types.MarketTradeChannel:
|
|
|
|
arg.Channel = ChannelTrade
|
|
|
|
return arg, nil
|
2023-10-31 13:53:13 +00:00
|
|
|
|
|
|
|
case types.KLineChannel:
|
|
|
|
interval, found := toLocalInterval[sub.Options.Interval]
|
|
|
|
if !found {
|
|
|
|
return WsArg{}, fmt.Errorf("interval %s not supported on KLine subscription", sub.Options.Interval)
|
|
|
|
}
|
|
|
|
|
|
|
|
arg.Channel = ChannelType(interval)
|
|
|
|
return arg, nil
|
2023-10-18 03:25:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return arg, fmt.Errorf("unsupported stream channel: %s", sub.Channel)
|
|
|
|
}
|
|
|
|
|
|
|
|
func parseWebSocketEvent(in []byte) (interface{}, error) {
|
2023-10-24 14:17:08 +00:00
|
|
|
switch {
|
|
|
|
case bytes.Equal(in, pongBytes):
|
2023-11-14 10:13:54 +00:00
|
|
|
// return global pong event to avoid emit raw message
|
|
|
|
return types.WebsocketPongEvent{}, nil
|
|
|
|
|
2023-10-24 14:17:08 +00:00
|
|
|
default:
|
|
|
|
return parseEvent(in)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func parseEvent(in []byte) (interface{}, error) {
|
2023-10-18 03:25:50 +00:00
|
|
|
var event WsEvent
|
|
|
|
|
|
|
|
err := json.Unmarshal(in, &event)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if event.IsOp() {
|
|
|
|
return &event, nil
|
|
|
|
}
|
|
|
|
|
2023-10-31 13:53:13 +00:00
|
|
|
ch := event.Arg.Channel
|
|
|
|
switch ch {
|
2023-11-10 14:35:39 +00:00
|
|
|
case ChannelAccount:
|
|
|
|
var acct AccountEvent
|
|
|
|
err = json.Unmarshal(event.Data, &acct.Balances)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to unmarshal data into AccountEvent, Arg: %+v Data: %s, err: %w", event.Arg, string(event.Data), err)
|
|
|
|
}
|
|
|
|
|
|
|
|
acct.actionType = event.Action
|
|
|
|
acct.instId = event.Arg.InstId
|
|
|
|
return &acct, nil
|
|
|
|
|
2023-10-18 03:25:50 +00:00
|
|
|
case ChannelOrderBook, ChannelOrderBook5, ChannelOrderBook15:
|
|
|
|
var book BookEvent
|
|
|
|
err = json.Unmarshal(event.Data, &book.Events)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to unmarshal data into BookEvent, Arg: %+v Data: %s, err: %w", event.Arg, string(event.Data), err)
|
|
|
|
}
|
|
|
|
|
2023-10-19 10:12:05 +00:00
|
|
|
book.actionType = event.Action
|
|
|
|
book.instId = event.Arg.InstId
|
2023-10-18 03:25:50 +00:00
|
|
|
return &book, nil
|
2023-10-19 10:12:05 +00:00
|
|
|
|
2023-11-14 03:23:30 +00:00
|
|
|
case ChannelOrders:
|
|
|
|
var order OrderTradeEvent
|
|
|
|
err = json.Unmarshal(event.Data, &order.Orders)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to unmarshal data into OrderTradeEvent, Arg: %+v Data: %s, err: %w", event.Arg, string(event.Data), err)
|
|
|
|
}
|
|
|
|
|
|
|
|
order.actionType = event.Action
|
|
|
|
order.instId = event.Arg.InstId
|
|
|
|
return &order, nil
|
|
|
|
|
2023-10-19 10:12:05 +00:00
|
|
|
case ChannelTrade:
|
|
|
|
var trade MarketTradeEvent
|
|
|
|
err = json.Unmarshal(event.Data, &trade.Events)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to unmarshal data into MarketTradeEvent, Arg: %+v Data: %s, err: %w", event.Arg, string(event.Data), err)
|
|
|
|
}
|
|
|
|
|
|
|
|
trade.actionType = event.Action
|
|
|
|
trade.instId = event.Arg.InstId
|
|
|
|
return &trade, nil
|
2023-10-18 03:25:50 +00:00
|
|
|
|
2023-10-31 13:53:13 +00:00
|
|
|
default:
|
|
|
|
|
|
|
|
// handle the `KLine` case here to avoid complicating the code structure.
|
|
|
|
if strings.HasPrefix(string(ch), "candle") {
|
|
|
|
var kline KLineEvent
|
|
|
|
err = json.Unmarshal(event.Data, &kline.Events)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to unmarshal data into KLineEvent, Arg: %+v Data: %s, err: %w", event.Arg, string(event.Data), err)
|
|
|
|
}
|
|
|
|
|
|
|
|
kline.actionType = event.Action
|
|
|
|
kline.channel = ch
|
|
|
|
kline.instId = event.Arg.InstId
|
|
|
|
return &kline, nil
|
|
|
|
}
|
|
|
|
// return an error for any other case
|
|
|
|
|
|
|
|
return nil, fmt.Errorf("unhandled websocket event: %+v", string(in))
|
|
|
|
}
|
2023-10-18 03:25:50 +00:00
|
|
|
}
|
2023-10-19 10:12:05 +00:00
|
|
|
|
|
|
|
func (s *Stream) handleMaretTradeEvent(m MarketTradeEvent) {
|
|
|
|
if m.actionType == ActionTypeSnapshot {
|
|
|
|
// we don't support snapshot event
|
|
|
|
return
|
|
|
|
}
|
|
|
|
for _, trade := range m.Events {
|
|
|
|
globalTrade, err := trade.ToGlobal(m.instId)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("failed to convert to market trade")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
s.EmitMarketTrade(globalTrade)
|
|
|
|
}
|
|
|
|
}
|
2023-10-31 13:53:13 +00:00
|
|
|
|
|
|
|
func (s *Stream) handleKLineEvent(k KLineEvent) {
|
|
|
|
if k.actionType == ActionTypeSnapshot {
|
|
|
|
// we don't support snapshot event
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
interval, found := toGlobalInterval[string(k.channel)]
|
|
|
|
if !found {
|
|
|
|
log.Errorf("unexpected interval %s on KLine subscription", k.channel)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, kline := range k.Events {
|
|
|
|
last, ok := s.lastCandle[k.CacheKey()]
|
|
|
|
if ok && kline.StartTime.Time().After(last.StartTime.Time()) {
|
|
|
|
last.Closed = true
|
|
|
|
s.EmitKLineClosed(last)
|
|
|
|
}
|
|
|
|
|
|
|
|
kLine := kline.ToGlobal(interval, k.instId)
|
|
|
|
s.EmitKLine(kLine)
|
|
|
|
s.lastCandle[k.CacheKey()] = kLine
|
|
|
|
}
|
|
|
|
}
|
2023-11-10 14:35:39 +00:00
|
|
|
|
|
|
|
func (s *Stream) handleAccountEvent(m AccountEvent) {
|
|
|
|
balanceMap := toGlobalBalanceMap(m.Balances)
|
|
|
|
if len(balanceMap) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if m.actionType == ActionTypeUpdate {
|
|
|
|
s.StandardStream.EmitBalanceUpdate(balanceMap)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
s.StandardStream.EmitBalanceSnapshot(balanceMap)
|
|
|
|
}
|
2023-11-14 03:23:30 +00:00
|
|
|
|
|
|
|
func (s *Stream) handleOrderTradeEvent(m OrderTradeEvent) {
|
|
|
|
if len(m.Orders) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, order := range m.Orders {
|
|
|
|
globalOrder, err := order.toGlobalOrder()
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("failed to convert order to global: %s", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
// The bitget support only snapshot on orders channel, so we use snapshot as update to emit data.
|
|
|
|
if m.actionType != ActionTypeSnapshot {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
s.StandardStream.EmitOrderUpdate(globalOrder)
|
|
|
|
|
|
|
|
if globalOrder.Status == types.OrderStatusPartiallyFilled {
|
|
|
|
trade, err := order.toGlobalTrade()
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("failed to convert trade to global: %s", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
s.StandardStream.EmitTradeUpdate(trade)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|