bbgo_origin/pkg/exchange/ftx/websocket_messages.go

469 lines
12 KiB
Go
Raw Permalink Normal View History

2021-02-27 10:41:46 +00:00
package ftx
2021-03-01 00:13:21 +00:00
import (
"encoding/json"
"fmt"
2021-03-06 11:23:44 +00:00
"hash/crc32"
2021-03-01 00:13:21 +00:00
"math"
2021-03-06 11:23:44 +00:00
"strconv"
2021-03-02 14:18:41 +00:00
"strings"
2021-03-01 00:13:21 +00:00
"time"
2021-03-02 14:18:41 +00:00
2022-03-02 06:35:35 +00:00
"github.com/c9s/bbgo/pkg/exchange/ftx/ftxapi"
2021-03-02 14:18:41 +00:00
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
2021-03-01 00:13:21 +00:00
)
2021-02-27 11:27:26 +00:00
2021-02-27 10:41:46 +00:00
type operation string
2021-03-28 08:29:36 +00:00
const ping operation = "ping"
2021-03-27 08:58:51 +00:00
const login operation = "login"
2021-02-27 10:41:46 +00:00
const subscribe operation = "subscribe"
const unsubscribe operation = "unsubscribe"
type channel string
const orderBookChannel channel = "orderbook"
const marketTradeChannel channel = "trades"
const bookTickerChannel channel = "ticker"
2021-03-27 11:02:19 +00:00
const privateOrdersChannel channel = "orders"
2021-03-28 06:42:54 +00:00
const privateTradesChannel channel = "fills"
2021-02-27 10:41:46 +00:00
var errUnsupportedConversion = fmt.Errorf("unsupported conversion")
2021-03-27 11:26:39 +00:00
2021-03-27 11:02:19 +00:00
/*
Private:
order update: `{'op': 'subscribe', 'channel': 'orders'}`
login: `{"args": { "key": "<api_key>", "sign": "<signature>", "time": <ts> }, "op": "login" }`
*/
2021-03-27 08:58:51 +00:00
type websocketRequest struct {
Operation operation `json:"op"`
// {'op': 'subscribe', 'channel': 'trades', 'market': 'BTC-PERP'}
Channel channel `json:"channel,omitempty"`
Market string `json:"market,omitempty"`
Login loginArgs `json:"args,omitempty"`
}
/*
{
"args": {
"key": "<api_key>",
"sign": "<signature>",
"time": <ts>
},
"op": "login"
}
*/
type loginArgs struct {
Key string `json:"key"`
Signature string `json:"sign"`
Time int64 `json:"time"`
2021-05-25 14:12:10 +00:00
SubAccount string `json:"subaccount,omitempty"`
2021-03-27 08:58:51 +00:00
}
2021-05-25 13:30:15 +00:00
func newLoginRequest(key, secret string, t time.Time, subaccount string) websocketRequest {
2021-03-27 08:58:51 +00:00
millis := t.UnixNano() / int64(time.Millisecond)
return websocketRequest{
Operation: login,
Login: loginArgs{
Key: key,
Signature: sign(secret, loginBody(millis)),
Time: millis,
2021-05-25 13:30:15 +00:00
SubAccount: subaccount,
2021-03-27 08:58:51 +00:00
},
}
}
func loginBody(millis int64) string {
return fmt.Sprintf("%dwebsocket_login", millis)
}
type respType string
2021-03-28 08:29:36 +00:00
const pongRespType respType = "pong"
const errRespType respType = "error"
const subscribedRespType respType = "subscribed"
const unsubscribedRespType respType = "unsubscribed"
const infoRespType respType = "info"
const partialRespType respType = "partial"
const updateRespType respType = "update"
2021-03-27 11:26:39 +00:00
type websocketResponse struct {
mandatoryFields
2021-03-27 11:26:39 +00:00
optionalFields
}
type mandatoryFields struct {
2021-03-27 11:26:39 +00:00
Channel channel `json:"channel"`
Type respType `json:"type"`
}
type optionalFields struct {
Market string `json:"market"`
// Example: {"type": "error", "code": 404, "msg": "No such market: BTCUSDT"}
Code int64 `json:"code"`
Message string `json:"msg"`
Data json.RawMessage `json:"data"`
}
type orderUpdateResponse struct {
mandatoryFields
2021-03-27 11:26:39 +00:00
2022-03-02 17:47:19 +00:00
Data ftxapi.Order `json:"data"`
2021-03-27 11:26:39 +00:00
}
type trade struct {
Price fixedpoint.Value `json:"price"`
Size fixedpoint.Value `json:"size"`
Side string `json:"side"`
Liquidation bool `json:"liquidation"`
Time time.Time `json:"time"`
}
type tradeResponse struct {
mandatoryFields
Data []trade `json:"data"`
}
func (r websocketResponse) toMarketTradeResponse() (t []types.Trade, err error) {
if r.Channel != marketTradeChannel {
return t, fmt.Errorf("type %s, channel %s: channel incorrect", r.Type, r.Channel)
}
var tds []trade
if err = json.Unmarshal(r.Data, &tds); err != nil {
return t, err
}
t = make([]types.Trade, len(tds))
for i, td := range tds {
tt := &t[i]
tt.Exchange = types.ExchangeFTX
tt.Price = td.Price
tt.Quantity = td.Size
tt.QuoteQuantity = td.Size
tt.Symbol = r.Market
tt.Side = types.SideType(TrimUpperString(string(td.Side)))
tt.IsBuyer = true
tt.IsMaker = false
tt.Time = types.Time(td.Time)
}
return t, nil
}
2021-03-27 11:26:39 +00:00
func (r websocketResponse) toOrderUpdateResponse() (orderUpdateResponse, error) {
2021-03-28 02:20:35 +00:00
if r.Channel != privateOrdersChannel {
return orderUpdateResponse{}, fmt.Errorf("type %s, channel %s: %w", r.Type, r.Channel, errUnsupportedConversion)
2021-03-27 11:26:39 +00:00
}
var o orderUpdateResponse
if err := json.Unmarshal(r.Data, &o.Data); err != nil {
return orderUpdateResponse{}, err
}
o.mandatoryFields = r.mandatoryFields
2021-03-27 11:26:39 +00:00
return o, nil
}
2021-03-28 06:42:54 +00:00
type tradeUpdateResponse struct {
mandatoryFields
2022-03-02 06:35:35 +00:00
Data ftxapi.Fill `json:"data"`
2021-03-28 06:42:54 +00:00
}
func (r websocketResponse) toTradeUpdateResponse() (tradeUpdateResponse, error) {
if r.Channel != privateTradesChannel {
return tradeUpdateResponse{}, fmt.Errorf("type %s, channel %s: %w", r.Type, r.Channel, errUnsupportedConversion)
}
var t tradeUpdateResponse
if err := json.Unmarshal(r.Data, &t.Data); err != nil {
return tradeUpdateResponse{}, err
}
t.mandatoryFields = r.mandatoryFields
return t, nil
}
/*
Private:
order: {"type": "subscribed", "channel": "orders"}
2021-02-27 11:27:26 +00:00
Public
2021-03-28 02:34:00 +00:00
orderbook: {"type": "subscribed", "channel": "orderbook", "market": "BTC/USDT"}
2021-02-27 11:27:26 +00:00
*/
type subscribedResponse struct {
mandatoryFields
2021-02-27 11:27:26 +00:00
Market string `json:"market"`
}
2021-03-28 02:20:35 +00:00
func (s subscribedResponse) String() string {
2022-04-22 16:10:27 +00:00
return fmt.Sprintf("%s channel is subscribed", strings.TrimSpace(fmt.Sprintf("%s %s", s.Market, s.Channel)))
2021-03-28 02:20:35 +00:00
}
// {"type": "subscribed", "channel": "orderbook", "market": "BTC/USDT"}
func (r websocketResponse) toSubscribedResponse() (subscribedResponse, error) {
if r.Type != subscribedRespType {
return subscribedResponse{}, fmt.Errorf("type %s, channel %s: %w", r.Type, r.Channel, errUnsupportedConversion)
}
2021-02-27 11:27:26 +00:00
return subscribedResponse{
mandatoryFields: r.mandatoryFields,
Market: r.Market,
}, nil
2021-02-27 11:27:26 +00:00
}
2021-03-28 02:34:00 +00:00
// {"type": "error", "code": 400, "msg": "Already logged in"}
type errResponse struct {
Code int64 `json:"code"`
Message string `json:"msg"`
}
func (e errResponse) String() string {
return fmt.Sprintf("%d: %s", e.Code, e.Message)
}
func (r websocketResponse) toErrResponse() errResponse {
return errResponse{
Code: r.Code,
Message: r.Message,
}
}
2022-03-02 17:47:19 +00:00
// sample :{"bid": 49194.0, "ask": 49195.0, "bidSize": 0.0775, "askSize": 0.0247, "last": 49200.0, "time": 1640171788.9339821}
func (r websocketResponse) toBookTickerResponse() (bookTickerResponse, error) {
if r.Channel != bookTickerChannel {
return bookTickerResponse{}, fmt.Errorf("type %s, channel %s: %w", r.Type, r.Channel, errUnsupportedConversion)
}
var o bookTickerResponse
if err := json.Unmarshal(r.Data, &o); err != nil {
return bookTickerResponse{}, err
}
o.mandatoryFields = r.mandatoryFields
o.Market = r.Market
o.Timestamp = nanoToTime(o.Time)
return o, nil
}
func (r websocketResponse) toPublicOrderBookResponse() (orderBookResponse, error) {
if r.Channel != orderBookChannel {
return orderBookResponse{}, fmt.Errorf("type %s, channel %s: %w", r.Type, r.Channel, errUnsupportedConversion)
2021-03-01 00:13:21 +00:00
}
var o orderBookResponse
if err := json.Unmarshal(r.Data, &o); err != nil {
2021-03-06 11:23:44 +00:00
return orderBookResponse{}, err
2021-03-01 00:13:21 +00:00
}
o.mandatoryFields = r.mandatoryFields
o.Market = r.Market
o.Timestamp = nanoToTime(o.Time)
2021-03-01 00:13:21 +00:00
return o, nil
}
func nanoToTime(input float64) time.Time {
sec, dec := math.Modf(input)
return time.Unix(int64(sec), int64(dec*1e9))
2021-02-27 11:27:26 +00:00
}
2021-03-01 00:13:21 +00:00
2021-03-06 11:23:44 +00:00
type orderBookResponse struct {
2021-03-01 00:13:21 +00:00
mandatoryFields
Market string `json:"market"`
Action string `json:"action"`
Time float64 `json:"time"`
2021-03-01 00:13:21 +00:00
Timestamp time.Time
2021-03-01 00:13:21 +00:00
2021-03-04 00:55:52 +00:00
Checksum uint32 `json:"checksum"`
2021-03-01 00:13:21 +00:00
2021-03-06 11:23:44 +00:00
// best 100 orders. Ex. {[100,1], [50, 2]}
Bids [][]json.Number `json:"bids"`
2021-03-01 00:13:21 +00:00
2021-03-06 11:23:44 +00:00
// best 100 orders. Ex. {[51, 1], [102, 3]}
Asks [][]json.Number `json:"asks"`
2021-03-01 00:13:21 +00:00
}
2021-03-02 14:18:41 +00:00
type bookTickerResponse struct {
mandatoryFields
Market string `json:"market"`
Bid fixedpoint.Value `json:"bid"`
Ask fixedpoint.Value `json:"ask"`
BidSize fixedpoint.Value `json:"bidSize"`
AskSize fixedpoint.Value `json:"askSize"`
Last fixedpoint.Value `json:"last"`
Time float64 `json:"time"`
Timestamp time.Time
}
2021-03-06 11:23:44 +00:00
// only 100 orders so we use linear search here
func (r *orderBookResponse) update(orderUpdates orderBookResponse) {
r.Checksum = orderUpdates.Checksum
r.updateBids(orderUpdates.Bids)
r.updateAsks(orderUpdates.Asks)
}
func (r *orderBookResponse) updateAsks(asks [][]json.Number) {
higherPrice := func(dst, src float64) bool {
return dst < src
}
for _, o := range asks {
if remove := o[1] == "0"; remove {
r.Asks = removePrice(r.Asks, o[0])
} else {
r.Asks = upsertPriceVolume(r.Asks, o, higherPrice)
}
}
}
func (r *orderBookResponse) updateBids(bids [][]json.Number) {
lessPrice := func(dst, src float64) bool {
return dst > src
}
for _, o := range bids {
if remove := o[1] == "0"; remove {
r.Bids = removePrice(r.Bids, o[0])
} else {
r.Bids = upsertPriceVolume(r.Bids, o, lessPrice)
}
}
}
func upsertPriceVolume(dst [][]json.Number, src []json.Number, priceComparator func(dst float64, src float64) bool) [][]json.Number {
for i, pv := range dst {
dstPrice := pv[0]
srcPrice := src[0]
// update volume
if dstPrice == srcPrice {
pv[1] = src[1]
return dst
}
// The value must be a number which is verified by json.Unmarshal, so the err
// should never happen.
dstPriceNum, err := strconv.ParseFloat(string(dstPrice), 64)
if err != nil {
logger.WithError(err).Errorf("unexpected price %s", dstPrice)
continue
}
srcPriceNum, err := strconv.ParseFloat(string(srcPrice), 64)
if err != nil {
logger.WithError(err).Errorf("unexpected price updates %s", srcPrice)
continue
}
if !priceComparator(dstPriceNum, srcPriceNum) {
return insertAt(dst, i, src)
}
}
return append(dst, src)
}
func insertAt(dst [][]json.Number, id int, pv []json.Number) (result [][]json.Number) {
result = append(result, dst[:id]...)
result = append(result, pv)
result = append(result, dst[id:]...)
return
}
func removePrice(dst [][]json.Number, price json.Number) [][]json.Number {
for i, pv := range dst {
if pv[0] == price {
return append(dst[:i], dst[i+1:]...)
}
}
return dst
}
func (r orderBookResponse) verifyChecksum() error {
if crc32Val := crc32.ChecksumIEEE([]byte(checksumString(r.Bids, r.Asks))); crc32Val != r.Checksum {
return fmt.Errorf("expected checksum %d, actual checksum %d: %w", r.Checksum, crc32Val, errUnmatchedChecksum)
}
return nil
}
// <best_bid_price>:<best_bid_size>:<best_ask_price>:<best_ask_size>...
func checksumString(bids, asks [][]json.Number) string {
sb := strings.Builder{}
appendNumber := func(pv []json.Number) {
if sb.Len() != 0 {
sb.WriteString(":")
}
sb.WriteString(string(pv[0]))
sb.WriteString(":")
sb.WriteString(string(pv[1]))
}
bidsLen := len(bids)
asksLen := len(asks)
for i := 0; i < bidsLen || i < asksLen; i++ {
if i < bidsLen {
appendNumber(bids[i])
}
if i < asksLen {
appendNumber(asks[i])
}
}
return sb.String()
}
var errUnmatchedChecksum = fmt.Errorf("unmatched checksum")
2021-05-22 03:36:58 +00:00
func toGlobalOrderBook(r orderBookResponse) (types.SliceOrderBook, error) {
bids, err := toPriceVolumeSlice(r.Bids)
if err != nil {
2021-05-22 03:36:58 +00:00
return types.SliceOrderBook{}, fmt.Errorf("can't convert bids to priceVolumeSlice: %w", err)
}
asks, err := toPriceVolumeSlice(r.Asks)
if err != nil {
2021-05-22 03:36:58 +00:00
return types.SliceOrderBook{}, fmt.Errorf("can't convert asks to priceVolumeSlice: %w", err)
}
2021-05-22 03:36:58 +00:00
return types.SliceOrderBook{
2021-03-02 14:18:41 +00:00
// ex. BTC/USDT
Symbol: toGlobalSymbol(strings.ToUpper(r.Market)),
Bids: bids,
Asks: asks,
}, nil
2021-03-02 14:18:41 +00:00
}
func toGlobalBookTicker(r bookTickerResponse) (types.BookTicker, error) {
return types.BookTicker{
// ex. BTC/USDT
Symbol: toGlobalSymbol(strings.ToUpper(r.Market)),
2022-03-02 17:47:19 +00:00
// Time: r.Timestamp,
Buy: r.Bid,
BuySize: r.BidSize,
Sell: r.Ask,
SellSize: r.AskSize,
2022-03-02 17:47:19 +00:00
// Last: r.Last,
}, nil
}
func toPriceVolumeSlice(orders [][]json.Number) (types.PriceVolumeSlice, error) {
2021-03-02 14:18:41 +00:00
var pv types.PriceVolumeSlice
for _, o := range orders {
p, err := fixedpoint.NewFromString(string(o[0]))
if err != nil {
return nil, fmt.Errorf("can't convert price %+v to fixedpoint: %w", o[0], err)
}
v, err := fixedpoint.NewFromString(string(o[1]))
if err != nil {
return nil, fmt.Errorf("can't convert volume %+v to fixedpoint: %w", o[0], err)
}
pv = append(pv, types.PriceVolume{Price: p, Volume: v})
2021-03-02 14:18:41 +00:00
}
return pv, nil
2021-03-02 14:18:41 +00:00
}