bbgo_origin/pkg/exchange/okex/stream.go

273 lines
6.5 KiB
Go
Raw Normal View History

2021-05-26 17:07:25 +00:00
package okex
import (
"context"
"fmt"
"golang.org/x/time/rate"
"strconv"
2021-05-26 17:07:25 +00:00
"time"
"github.com/c9s/bbgo/pkg/exchange/okex/okexapi"
"github.com/c9s/bbgo/pkg/types"
)
var (
tradeLogLimiter = rate.NewLimiter(rate.Every(time.Minute), 1)
)
2021-05-27 06:42:14 +00:00
type WebsocketOp struct {
Op WsEventType `json:"op"`
2021-05-27 06:42:14 +00:00
Args interface{} `json:"args"`
}
type WebsocketLogin struct {
Key string `json:"apiKey"`
Passphrase string `json:"passphrase"`
Timestamp string `json:"timestamp"`
Sign string `json:"sign"`
}
2021-05-26 17:07:25 +00:00
//go:generate callbackgen -type Stream -interface
type Stream struct {
types.StandardStream
2022-01-01 18:37:33 +00:00
client *okexapi.RestClient
2021-05-26 17:07:25 +00:00
// public callbacks
2024-01-02 15:18:57 +00:00
kLineEventCallbacks []func(candle KLineEvent)
bookEventCallbacks []func(book BookEvent)
2022-01-01 18:37:33 +00:00
accountEventCallbacks []func(account okexapi.Account)
orderDetailsEventCallbacks []func(orderDetails []okexapi.OrderDetails)
marketTradeEventCallbacks []func(tradeDetail []MarketTradeEvent)
2021-05-26 17:07:25 +00:00
}
func NewStream(client *okexapi.RestClient) *Stream {
stream := &Stream{
2022-01-01 18:37:33 +00:00
client: client,
StandardStream: types.NewStandardStream(),
2021-05-26 17:07:25 +00:00
}
2021-05-27 06:42:14 +00:00
2022-01-01 18:37:33 +00:00
stream.SetParser(parseWebSocketEvent)
stream.SetDispatcher(stream.dispatchEvent)
stream.SetEndpointCreator(stream.createEndpoint)
2021-05-27 10:43:42 +00:00
2024-01-02 15:18:57 +00:00
stream.OnKLineEvent(stream.handleKLineEvent)
2022-01-01 18:37:33 +00:00
stream.OnBookEvent(stream.handleBookEvent)
stream.OnAccountEvent(stream.handleAccountEvent)
stream.OnMarketTradeEvent(stream.handleMarketTradeEvent)
2022-01-01 18:37:33 +00:00
stream.OnOrderDetailsEvent(stream.handleOrderDetailsEvent)
stream.OnConnect(stream.handleConnect)
2024-01-09 02:57:33 +00:00
stream.OnAuth(stream.handleAuth)
2022-01-01 18:37:33 +00:00
return stream
}
2021-05-27 10:43:42 +00:00
func (s *Stream) syncSubscriptions(opType WsEventType) error {
if opType != WsEventTypeUnsubscribe && opType != WsEventTypeSubscribe {
return fmt.Errorf("unexpected subscription type: %v", opType)
}
logger := log.WithField("opType", opType)
var topics []WebsocketSubscription
for _, subscription := range s.Subscriptions {
topic, err := convertSubscription(subscription)
if err != nil {
logger.WithError(err).Errorf("convert error, subscription: %+v", subscription)
return err
}
topics = append(topics, topic)
}
logger.Infof("%s channels: %+v", opType, topics)
if err := s.Conn.WriteJSON(WebsocketOp{
Op: opType,
Args: topics,
}); 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(WsEventTypeUnsubscribe)
s.Resubscribe(func(old []types.Subscription) (new []types.Subscription, err error) {
// clear the subscriptions
return []types.Subscription{}, nil
})
}
2022-01-01 18:37:33 +00:00
func (s *Stream) handleConnect() {
if s.PublicOnly {
var subs []WebsocketSubscription
for _, subscription := range s.Subscriptions {
sub, err := convertSubscription(subscription)
if err != nil {
log.WithError(err).Errorf("subscription convert error")
continue
}
2022-01-01 18:37:33 +00:00
subs = append(subs, sub)
}
if len(subs) == 0 {
return
}
2022-01-01 18:37:33 +00:00
log.Infof("subscribing channels: %+v", subs)
err := s.Conn.WriteJSON(WebsocketOp{
Op: "subscribe",
Args: subs,
})
if err != nil {
2022-01-01 18:37:33 +00:00
log.WithError(err).Error("subscribe error")
}
} else {
// login as private channel
// sign example:
// sign=CryptoJS.enc.Base64.Stringify(CryptoJS.HmacSHA256(timestamp +'GET'+'/users/self/verify', secretKey))
msTimestamp := strconv.FormatFloat(float64(time.Now().UnixNano())/float64(time.Second), 'f', -1, 64)
payload := msTimestamp + "GET" + "/users/self/verify"
sign := okexapi.Sign(payload, s.client.Secret)
op := WebsocketOp{
Op: "login",
Args: []WebsocketLogin{
{
Key: s.client.Key,
Passphrase: s.client.Passphrase,
Timestamp: msTimestamp,
Sign: sign,
},
},
}
2022-01-01 18:37:33 +00:00
log.Infof("sending okex login request")
err := s.Conn.WriteJSON(op)
if err != nil {
2022-01-01 18:37:33 +00:00
log.WithError(err).Errorf("can not send login message")
}
2022-01-01 18:37:33 +00:00
}
}
2024-01-09 02:57:33 +00:00
func (s *Stream) handleAuth() {
var subs = []WebsocketSubscription{
{Channel: ChannelAccount},
{Channel: "orders", InstrumentType: string(okexapi.InstrumentTypeSpot)},
}
2021-05-27 06:42:14 +00:00
2024-01-09 02:57:33 +00:00
log.Infof("subscribing private channels: %+v", subs)
err := s.Conn.WriteJSON(WebsocketOp{
Op: "subscribe",
Args: subs,
})
if err != nil {
log.WithError(err).Error("private channel subscribe error")
2022-01-01 18:37:33 +00:00
}
2021-05-26 17:07:25 +00:00
}
2022-01-01 18:37:33 +00:00
func (s *Stream) handleOrderDetailsEvent(orderDetails []okexapi.OrderDetails) {
detailTrades, detailOrders := segmentOrderDetails(orderDetails)
2021-05-26 17:07:25 +00:00
2022-01-01 18:37:33 +00:00
trades, err := toGlobalTrades(detailTrades)
2021-05-26 17:07:25 +00:00
if err != nil {
2022-01-01 18:37:33 +00:00
log.WithError(err).Errorf("error converting order details into trades")
} else {
for _, trade := range trades {
s.EmitTradeUpdate(trade)
}
2021-05-26 17:07:25 +00:00
}
2022-01-01 18:37:33 +00:00
orders, err := toGlobalOrders(detailOrders)
if err != nil {
log.WithError(err).Errorf("error converting order details into orders")
} else {
for _, order := range orders {
s.EmitOrderUpdate(order)
}
}
}
2021-05-26 17:07:25 +00:00
2022-01-01 18:37:33 +00:00
func (s *Stream) handleAccountEvent(account okexapi.Account) {
balances := toGlobalBalance(&account)
2024-01-09 02:57:33 +00:00
s.EmitBalanceUpdate(balances)
2021-05-26 17:07:25 +00:00
}
2022-01-01 18:37:33 +00:00
func (s *Stream) handleBookEvent(data BookEvent) {
book := data.Book()
switch data.Action {
2024-01-02 15:18:57 +00:00
case ActionTypeSnapshot:
2022-01-01 18:37:33 +00:00
s.EmitBookSnapshot(book)
2024-01-02 15:18:57 +00:00
case ActionTypeUpdate:
2022-01-01 18:37:33 +00:00
s.EmitBookUpdate(book)
}
}
2021-05-26 17:07:25 +00:00
func (s *Stream) handleMarketTradeEvent(data []MarketTradeEvent) {
for _, event := range data {
trade, err := event.toGlobalTrade()
if err != nil {
if tradeLogLimiter.Allow() {
log.WithError(err).Error("failed to convert to market trade")
}
continue
}
s.EmitMarketTrade(trade)
}
}
2024-01-02 15:18:57 +00:00
func (s *Stream) handleKLineEvent(k KLineEvent) {
for _, event := range k.Events {
kline := event.ToGlobal(types.Interval(k.Interval), k.Symbol)
if kline.Closed {
s.EmitKLineClosed(kline)
} else {
s.EmitKLine(kline)
}
2021-05-26 17:07:25 +00:00
}
}
2022-01-01 18:37:33 +00:00
func (s *Stream) createEndpoint(ctx context.Context) (string, error) {
2021-05-27 07:16:01 +00:00
var url string
2021-12-23 06:14:48 +00:00
if s.PublicOnly {
2021-05-27 07:16:01 +00:00
url = okexapi.PublicWebSocketURL
} else {
url = okexapi.PrivateWebSocketURL
}
2022-01-01 18:37:33 +00:00
return url, nil
2021-05-26 17:07:25 +00:00
}
2022-01-01 18:37:33 +00:00
func (s *Stream) dispatchEvent(e interface{}) {
switch et := e.(type) {
case *WebSocketEvent:
2024-01-09 02:57:33 +00:00
if err := et.IsValid(); err != nil {
log.Errorf("invalid event: %v", err)
2024-01-09 03:58:43 +00:00
return
2024-01-09 02:57:33 +00:00
}
if et.IsAuthenticated() {
s.EmitAuth()
}
2022-01-01 18:37:33 +00:00
case *BookEvent:
// there's "books" for 400 depth and books5 for 5 depth
2024-01-02 15:18:57 +00:00
if et.channel != ChannelBook5 {
2022-01-01 18:37:33 +00:00
s.EmitBookEvent(*et)
2021-05-26 17:07:25 +00:00
}
2022-01-01 18:37:33 +00:00
s.EmitBookTickerUpdate(et.BookTicker())
2024-01-02 15:18:57 +00:00
case *KLineEvent:
s.EmitKLineEvent(*et)
2021-05-26 17:07:25 +00:00
2022-01-01 18:37:33 +00:00
case *okexapi.Account:
s.EmitAccountEvent(*et)
2021-05-26 17:07:25 +00:00
2022-01-01 18:37:33 +00:00
case []okexapi.OrderDetails:
s.EmitOrderDetailsEvent(et)
2021-05-26 17:07:25 +00:00
case []MarketTradeEvent:
s.EmitMarketTradeEvent(et)
2021-05-26 17:07:25 +00:00
}
}