bbgo_origin/pkg/exchange/ftx/stream_message_handler.go

76 lines
1.8 KiB
Go
Raw Normal View History

2021-02-27 11:27:44 +00:00
package ftx
import (
"encoding/json"
2021-03-02 14:18:41 +00:00
log "github.com/sirupsen/logrus"
2021-02-27 11:27:44 +00:00
"github.com/c9s/bbgo/pkg/types"
)
type messageHandler struct {
2021-03-02 14:18:41 +00:00
*types.StandardStream
2021-02-27 11:27:44 +00:00
}
2021-03-06 11:23:44 +00:00
func (h *messageHandler) handleMessage(message []byte) {
2021-02-27 11:27:44 +00:00
var r rawResponse
if err := json.Unmarshal(message, &r); err != nil {
logger.WithError(err).Errorf("failed to unmarshal resp: %s", string(message))
return
}
switch r.Type {
case subscribedRespType:
h.handleSubscribedMessage(r)
2021-03-04 00:55:52 +00:00
case partialRespType, updateRespType:
h.handleMarketData(r)
2021-02-27 11:27:44 +00:00
default:
logger.Errorf("unsupported message type: %+v", r.Type)
}
}
// {"type": "subscribed", "channel": "orderbook", "market": "BTC/USDT"}
func (h messageHandler) handleSubscribedMessage(response rawResponse) {
2021-02-28 13:48:50 +00:00
r := response.toSubscribedResp()
logger.Infof("%s %s is subscribed", r.Market, r.Channel)
2021-02-27 11:27:44 +00:00
}
2021-03-02 14:18:41 +00:00
2021-03-04 00:55:52 +00:00
func (h *messageHandler) handleMarketData(response rawResponse) {
2021-03-06 11:23:44 +00:00
r, err := response.toOrderBookResponse()
2021-03-02 14:18:41 +00:00
if err != nil {
log.WithError(err).Errorf("failed to convert the partial response to data response")
2021-03-02 14:18:41 +00:00
return
}
2021-03-04 00:55:52 +00:00
switch r.Channel {
case orderbook:
h.handleOrderBook(r)
default:
log.Errorf("unsupported market data channel %s", r.Channel)
return
}
}
2021-03-06 11:23:44 +00:00
func (h *messageHandler) handleOrderBook(r orderBookResponse) {
globalOrderBook, err := toGlobalOrderBook(r)
if err != nil {
log.WithError(err).Errorf("failed to generate orderbook snapshot")
return
}
2021-03-04 00:55:52 +00:00
switch r.Type {
case partialRespType:
2021-03-06 11:23:44 +00:00
if err := r.verifyChecksum(); err != nil {
log.WithError(err).Errorf("invalid orderbook snapshot")
return
}
h.EmitBookSnapshot(globalOrderBook)
2021-03-04 00:55:52 +00:00
case updateRespType:
2021-03-06 11:23:44 +00:00
// emit updates, not the whole orderbook
h.EmitBookUpdate(globalOrderBook)
2021-03-04 00:55:52 +00:00
default:
log.Errorf("unsupported order book data type %s", r.Type)
return
}
2021-03-02 14:18:41 +00:00
}