max: parse and convert trade update

This commit is contained in:
c9s 2020-10-19 22:23:49 +08:00
parent 822e4c2703
commit 366036a35b
2 changed files with 59 additions and 0 deletions

View File

@ -108,6 +108,8 @@ type TradeUpdate struct {
Timestamp int64 `json:"T"` Timestamp int64 `json:"T"`
OrderID uint64 `json:"oi"` OrderID uint64 `json:"oi"`
Maker bool `json:"m"`
} }
func parseTradeUpdate(v *fastjson.Value) TradeUpdate { func parseTradeUpdate(v *fastjson.Value) TradeUpdate {
@ -121,6 +123,7 @@ func parseTradeUpdate(v *fastjson.Value) TradeUpdate {
FeeCurrency: string(v.GetStringBytes("fc")), FeeCurrency: string(v.GetStringBytes("fc")),
Timestamp: v.GetInt64("T"), Timestamp: v.GetInt64("T"),
OrderID: v.GetUint64("oi"), OrderID: v.GetUint64("oi"),
Maker: v.GetBool("m"),
} }
} }

View File

@ -2,6 +2,8 @@ package max
import ( import (
"context" "context"
"strconv"
"time"
max "github.com/c9s/bbgo/pkg/exchange/max/maxapi" max "github.com/c9s/bbgo/pkg/exchange/max/maxapi"
"github.com/c9s/bbgo/pkg/types" "github.com/c9s/bbgo/pkg/types"
@ -26,6 +28,20 @@ func NewStream(key, secret string) *Stream {
logger.Infof("M: %s", message) logger.Infof("M: %s", message)
}) })
// wss.OnTradeEvent(func(e max.PublicTradeEvent) { })
wss.OnTradeUpdateEvent(func(e max.TradeUpdateEvent) {
for _, tradeUpdate := range e.Trades {
trade, err := convertWebSocketTrade(tradeUpdate)
if err != nil {
log.WithError(err).Error("websocket trade update convert error")
return
}
stream.EmitTrade(*trade)
}
})
wss.OnBookEvent(func(e max.BookEvent) { wss.OnBookEvent(func(e max.BookEvent) {
newbook, err := e.OrderBook() newbook, err := e.OrderBook()
if err != nil { if err != nil {
@ -83,3 +99,43 @@ func (s *Stream) Connect(ctx context.Context) error {
func (s *Stream) Close() error { func (s *Stream) Close() error {
return s.websocketService.Close() return s.websocketService.Close()
} }
func convertWebSocketTrade(t max.TradeUpdate) (*types.Trade, error) {
// skip trade ID that is the same. however this should not happen
var side = toGlobalSideType(t.Side)
// trade time
mts := time.Unix(0, t.Timestamp*int64(time.Millisecond))
price, err := strconv.ParseFloat(t.Price, 64)
if err != nil {
return nil, err
}
quantity, err := strconv.ParseFloat(t.Volume, 64)
if err != nil {
return nil, err
}
quoteQuantity := price * quantity
fee, err := strconv.ParseFloat(t.Fee, 64)
if err != nil {
return nil, err
}
return &types.Trade{
ID: int64(t.ID),
Price: price,
Symbol: toGlobalSymbol(t.Market),
Exchange: "max",
Quantity: quantity,
Side: side,
IsBuyer: side == "bid",
IsMaker: t.Maker,
Fee: fee,
FeeCurrency: toGlobalCurrency(t.FeeCurrency),
QuoteQuantity: quoteQuantity,
Time: mts,
}, nil
}