1 Star 0 Fork 0

yuliang87 / go-binance

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
websocket_service.go 25.58 KB
一键复制 编辑 原始数据 按行查看 历史
yuliang87 提交于 2021-09-05 13:02 . 1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
package delivery
import (
"encoding/json"
"fmt"
"strings"
"time"
)
// Endpoints
const (
baseWsMainUrl = "wss://dstream.binance.com/ws"
baseWsTestnetUrl = "wss://dstream.binancefuture.com/ws"
)
var (
// WebsocketTimeout is an interval for sending ping/pong messages if WebsocketKeepalive is enabled
WebsocketTimeout = time.Second * 60
// WebsocketKeepalive enables sending ping/pong messages to check the connection stability
WebsocketKeepalive = false
// UseTestnet switch all the WS streams from production to the testnet
UseTestnet = false
)
// getWsEndpoint return the base endpoint of the WS according the UseTestnet flag
func getWsEndpoint() string {
if UseTestnet {
return baseWsTestnetUrl
}
return baseWsMainUrl
}
// WsAggTradeEvent define websocket aggTrde event.
type WsAggTradeEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
AggregateTradeID int64 `json:"a"`
Symbol string `json:"s"`
Price string `json:"p"`
Quantity string `json:"q"`
FirstTradeID int64 `json:"f"`
LastTradeID int64 `json:"l"`
TradeTime int64 `json:"T"`
Maker bool `json:"m"`
}
// WsAggTradeHandler handle websocket that push trade information that is aggregated for a single taker order.
type WsAggTradeHandler func(event *WsAggTradeEvent)
// WsAggTradeServe serve websocket that push trade information that is aggregated for a single taker order.
func WsAggTradeServe(symbol string, handler WsAggTradeHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@aggTrade", getWsEndpoint(), strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsAggTradeEvent)
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsIndexPriceEvent define websocket indexPriceUpdate event.
type WsIndexPriceEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Pair string `json:"i"`
IndexPrice string `json:"p"`
}
// WsIndexPriceHandler handle websocket that push index price for a pair.
type WsIndexPriceHandler func(event *WsIndexPriceEvent)
// WsIndexPriceServe serve websocket that pushes index price for a pair.
func WsIndexPriceServe(symbol string, handler WsIndexPriceHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@indexPrice", getWsEndpoint(), strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsIndexPriceEvent)
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsMarkPriceEvent define websocket markPriceUpdate event.
type WsMarkPriceEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Symbol string `json:"s"`
MarkPrice string `json:"p"`
EstimatedSettlePrice string `json:"P"`
FundingRate string `json:"r"`
NextFundingTime int64 `json:"T"`
}
// WsMarkPriceHandler handle websocket that pushes price and funding rate for a single symbol.
type WsMarkPriceHandler func(event *WsMarkPriceEvent)
// WsMarkPriceServe serve websocket that pushes price and funding rate for a single symbol.
func WsMarkPriceServe(symbol string, handler WsMarkPriceHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@markPrice", getWsEndpoint(), strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsMarkPriceEvent)
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsPairMarkPriceEvent defines an array of websocket markPriceUpdate events.
type WsPairMarkPriceEvent []*WsMarkPriceEvent
// WsPairMarkPriceHandler handle websocket that pushes price and funding rate for all symbol.
type WsPairMarkPriceHandler func(event WsPairMarkPriceEvent)
// WsPairMarkPriceServe serve websocket that pushes price and funding rate for all symbol.
func WsPairMarkPriceServe(handler WsPairMarkPriceHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/markPrice@arr", getWsEndpoint())
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
var event WsPairMarkPriceEvent
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsKlineEvent define websocket kline event
type WsKlineEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Symbol string `json:"s"`
Kline WsKline `json:"k"`
}
// WsKline define websocket kline
type WsKline struct {
StartTime int64 `json:"t"`
EndTime int64 `json:"T"`
Symbol string `json:"s"`
Interval string `json:"i"`
FirstTradeID int64 `json:"f"`
LastTradeID int64 `json:"L"`
Open string `json:"o"`
Close string `json:"c"`
High string `json:"h"`
Low string `json:"l"`
Volume string `json:"v"`
TradeNum int64 `json:"n"`
IsFinal bool `json:"x"`
QuoteVolume string `json:"q"`
ActiveBuyVolume string `json:"V"`
ActiveBuyQuoteVolume string `json:"Q"`
}
// WsKlineHandler handle websocket kline event
type WsKlineHandler func(event *WsKlineEvent)
// WsKlineServe serve websocket kline handler with a symbol and interval like 15m, 30s
func WsKlineServe(symbol string, interval string, handler WsKlineHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@kline_%s", getWsEndpoint(), strings.ToLower(symbol), interval)
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsKlineEvent)
err := json.Unmarshal(message, event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsContinuousKlineEvent define websocket continuous kline event
type WsContinuousKlineEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Pair string `json:"ps"`
ContractType string `json:"ct"`
Kline WsContinuousKline `json:"k"`
}
// WsContinuousKline define websocket continuous kline
type WsContinuousKline struct {
StartTime int64 `json:"t"`
EndTime int64 `json:"T"`
Interval string `json:"i"`
FirstTradeID int64 `json:"f"`
LastTradeID int64 `json:"L"`
Open string `json:"o"`
Close string `json:"c"`
High string `json:"h"`
Low string `json:"l"`
Volume string `json:"v"`
TradeNum int64 `json:"n"`
IsFinal bool `json:"x"`
QuoteVolume string `json:"q"`
ActiveBuyVolume string `json:"V"`
ActiveBuyQuoteVolume string `json:"Q"`
}
// WsContinuousKlineHandler handle websocket continuous kline event
type WsContinuousKlineHandler func(event *WsContinuousKlineEvent)
// WsContinuousKlineServe serve websocket kline handler with a pair, a contract type and interval like 15m, 30s
func WsContinuousKlineServe(pair string, contractType string, interval string, handler WsContinuousKlineHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s_%s@continuousKline_%s", getWsEndpoint(), strings.ToLower(pair), strings.ToLower(contractType), interval)
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsContinuousKlineEvent)
err := json.Unmarshal(message, event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsIndexPriceKlineEvent define websocket index price kline event
type WsIndexPriceKlineEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Pair string `json:"ps"`
Kline WsIndexPriceKline `json:"k"`
}
// WsIndexPriceKline define websocket index price kline
type WsIndexPriceKline struct {
StartTime int64 `json:"t"`
EndTime int64 `json:"T"`
Interval string `json:"i"`
LastTradeId int64 `json:"L"` // LastTradeId Ignore
Open string `json:"o"`
Close string `json:"c"`
High string `json:"h"`
Low string `json:"l"`
TradeNum int64 `json:"n"`
IsFinal bool `json:"x"`
}
// WsIndexPriceKlineHandler handle websocket index kline event
type WsIndexPriceKlineHandler func(event *WsIndexPriceKlineEvent)
// WsIndexPriceKlineServe serve websocket kline handler with a pair and interval like 15m, 30s
func WsIndexPriceKlineServe(pair string, interval string, handler WsIndexPriceKlineHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@indexPriceKline_%s", getWsEndpoint(), strings.ToLower(pair), interval)
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsIndexPriceKlineEvent)
err := json.Unmarshal(message, event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsMarkPriceKlineEvent define websocket market price kline event
type WsMarkPriceKlineEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Pair string `json:"ps"`
Kline WsMarkPriceKline `json:"k"`
}
// WsMarkPriceKline define websocket market price kline
type WsMarkPriceKline struct {
StartTime int64 `json:"t"`
EndTime int64 `json:"T"`
Symbol string `json:"s"`
Interval string `json:"i"`
LastTradeID int64 `json:"L"` // LastTradeID Ignore
Open string `json:"o"`
Close string `json:"c"`
High string `json:"h"`
Low string `json:"l"`
TradeNum int64 `json:"n"`
IsFinal bool `json:"x"`
}
// WsMarkPriceKlineHandler handle websocket market price kline event
type WsMarkPriceKlineHandler func(event *WsMarkPriceKlineEvent)
// WsMarkPriceKlineServe serve websocket kline handler with a symbol and interval like 15m, 30s
func WsMarkPriceKlineServe(symbol string, interval string, handler WsMarkPriceKlineHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@markPriceKline_%s", getWsEndpoint(), strings.ToLower(symbol), interval)
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsMarkPriceKlineEvent)
err := json.Unmarshal(message, event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsMiniMarketTickerEvent define websocket mini market ticker event.
type WsMiniMarketTickerEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Symbol string `json:"s"`
Pair string `json:"ps"`
ClosePrice string `json:"c"`
OpenPrice string `json:"o"`
HighPrice string `json:"h"`
LowPrice string `json:"l"`
Volume string `json:"v"`
QuoteVolume string `json:"q"`
}
// WsMiniMarketTickerHandler handle websocket that pushes 24hr rolling window mini-ticker statistics for a single symbol.
type WsMiniMarketTickerHandler func(event *WsMiniMarketTickerEvent)
// WsMiniMarketTickerServe serve websocket that pushes 24hr rolling window mini-ticker statistics for a single symbol.
func WsMiniMarketTickerServe(symbol string, handler WsMiniMarketTickerHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@miniTicker", getWsEndpoint(), strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsMiniMarketTickerEvent)
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsAllMiniMarketTickerEvent define an array of websocket mini market ticker events.
type WsAllMiniMarketTickerEvent []*WsMiniMarketTickerEvent
// WsAllMiniMarketTickerHandler handle websocket that pushes price and funding rate for all markets.
type WsAllMiniMarketTickerHandler func(event WsAllMiniMarketTickerEvent)
// WsAllMiniMarketTickerServe serve websocket that pushes price and funding rate for all markets.
func WsAllMiniMarketTickerServe(handler WsAllMiniMarketTickerHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/!miniTicker@arr", getWsEndpoint())
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
var event WsAllMiniMarketTickerEvent
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsMarketTickerEvent define websocket market ticker event.
type WsMarketTickerEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
Symbol string `json:"s"`
Pair string `json:"ps"`
PriceChange string `json:"p"`
PriceChangePercent string `json:"P"`
WeightedAvgPrice string `json:"w"`
ClosePrice string `json:"c"`
CloseQty string `json:"Q"`
OpenPrice string `json:"o"`
HighPrice string `json:"h"`
LowPrice string `json:"l"`
BaseVolume string `json:"v"`
QuoteVolume string `json:"q"`
OpenTime int64 `json:"O"`
CloseTime int64 `json:"C"`
FirstID int64 `json:"F"`
LastID int64 `json:"L"`
TradeCount int64 `json:"n"`
}
// WsMarketTickerHandler handle websocket that pushes 24hr rolling window mini-ticker statistics for a single symbol.
type WsMarketTickerHandler func(event *WsMarketTickerEvent)
// WsMarketTickerServe serve websocket that pushes 24hr rolling window mini-ticker statistics for a single symbol.
func WsMarketTickerServe(symbol string, handler WsMarketTickerHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@ticker", getWsEndpoint(), strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsMarketTickerEvent)
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsAllMarketTickerEvent define an array of websocket mini ticker events.
type WsAllMarketTickerEvent []*WsMarketTickerEvent
// WsAllMarketTickerHandler handle websocket that pushes price and funding rate for all markets.
type WsAllMarketTickerHandler func(event WsAllMarketTickerEvent)
// WsAllMarketTickerServe serve websocket that pushes price and funding rate for all markets.
func WsAllMarketTickerServe(handler WsAllMarketTickerHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/!ticker@arr", getWsEndpoint())
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
var event WsAllMarketTickerEvent
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsBookTickerEvent define websocket best book ticker event.
type WsBookTickerEvent struct {
Event string `json:"e"`
UpdateID int64 `json:"u"`
Symbol string `json:"s"`
Pair string `json:"ps"`
BestBidPrice string `json:"b"`
BestBidQty string `json:"B"`
BestAskPrice string `json:"a"`
BestAskQty string `json:"A"`
TransactionTime int64 `json:"T"`
Time int64 `json:"E"`
}
// WsBookTickerHandler handle websocket that pushes updates to the best bid or ask price or quantity in real-time for a specified symbol.
type WsBookTickerHandler func(event *WsBookTickerEvent)
// WsBookTickerServe serve websocket that pushes updates to the best bid or ask price or quantity in real-time for a specified symbol.
func WsBookTickerServe(symbol string, handler WsBookTickerHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@bookTicker", getWsEndpoint(), strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsBookTickerEvent)
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsAllBookTickerServe serve websocket that pushes updates to the best bid or ask price or quantity in real-time for all symbols.
func WsAllBookTickerServe(handler WsBookTickerHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/!bookTicker", getWsEndpoint())
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsBookTickerEvent)
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsLiquidationOrderEvent define websocket liquidation order event.
type WsLiquidationOrderEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
LiquidationOrder WsLiquidationOrder `json:"o"`
}
// WsLiquidationOrder define websocket liquidation order.
type WsLiquidationOrder struct {
Symbol string `json:"s"`
Pair string `json:"ps"`
Side SideType `json:"S"`
OrderType OrderType `json:"o"`
TimeInForce TimeInForceType `json:"f"`
OrigQuantity string `json:"q"`
Price string `json:"p"`
AvgPrice string `json:"ap"`
OrderStatus OrderStatusType `json:"X"`
LastFilledQty string `json:"l"`
AccumulatedFilledQty string `json:"z"`
TradeTime int64 `json:"T"`
}
// WsLiquidationOrderHandler handle websocket that pushes force liquidation order information for specific symbol.
type WsLiquidationOrderHandler func(event *WsLiquidationOrderEvent)
// WsLiquidationOrderServe serve websocket that pushes force liquidation order information for specific symbol.
func WsLiquidationOrderServe(symbol string, handler WsLiquidationOrderHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@forceOrder", getWsEndpoint(), strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsLiquidationOrderEvent)
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsAllLiquidationOrderServe serve websocket that pushes force liquidation order information for all symbols.
func WsAllLiquidationOrderServe(handler WsLiquidationOrderHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/!forceOrder@arr", getWsEndpoint())
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsLiquidationOrderEvent)
err := json.Unmarshal(message, &event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsDepthEvent define websocket depth book event
type WsDepthEvent struct {
Event string `json:"e"`
Time int64 `json:"E"`
TransactionTime int64 `json:"T"`
Symbol string `json:"s"`
Pair string `json:"ps"`
FirstUpdateID int64 `json:"U"`
LastUpdateID int64 `json:"u"`
PrevLastUpdateID int64 `json:"pu"`
Bids []Bid `json:"b"`
Asks []Ask `json:"a"`
}
// WsDepthHandler handle websocket depth event
type WsDepthHandler func(event *WsDepthEvent)
// WsPartialDepthServe serve websocket partial depth handler.
func WsPartialDepthServe(symbol string, levels int, handler WsDepthHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@depth%d", getWsEndpoint(), strings.ToLower(symbol), levels)
cfg := newWsConfig(endpoint)
return wsDepthServe(cfg, handler, errHandler)
}
// WsDiffDepthServe serve websocket diff. depth handler.
func WsDiffDepthServe(symbol string, handler WsDepthHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s@depth", getWsEndpoint(), strings.ToLower(symbol))
cfg := newWsConfig(endpoint)
return wsDepthServe(cfg, handler, errHandler)
}
func wsDepthServe(cfg *WsConfig, handler WsDepthHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
wsHandler := func(message []byte) {
j, err := newJSON(message)
if err != nil {
errHandler(err)
return
}
event := new(WsDepthEvent)
event.Event = j.Get("e").MustString()
event.Time = j.Get("E").MustInt64()
event.TransactionTime = j.Get("T").MustInt64()
event.Symbol = j.Get("s").MustString()
event.Pair = j.Get("ps").MustString()
event.FirstUpdateID = j.Get("U").MustInt64()
event.LastUpdateID = j.Get("u").MustInt64()
event.PrevLastUpdateID = j.Get("pu").MustInt64()
bidsLen := len(j.Get("b").MustArray())
event.Bids = make([]Bid, bidsLen)
for i := 0; i < bidsLen; i++ {
item := j.Get("b").GetIndex(i)
event.Bids[i] = Bid{
Price: item.GetIndex(0).MustString(),
Quantity: item.GetIndex(1).MustString(),
}
}
asksLen := len(j.Get("a").MustArray())
event.Asks = make([]Ask, asksLen)
for i := 0; i < asksLen; i++ {
item := j.Get("a").GetIndex(i)
event.Asks[i] = Ask{
Price: item.GetIndex(0).MustString(),
Quantity: item.GetIndex(1).MustString(),
}
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
// WsUserDataEvent define user data event
type WsUserDataEvent struct {
Event UserDataEventType `json:"e"`
Time int64 `json:"E"`
Alias string `json:"i"`
CrossWalletBalance string `json:"cw"`
MarginCallPositions []WsPosition `json:"p"`
TransactionTime int64 `json:"T"`
AccountUpdate WsAccountUpdate `json:"a"`
OrderTradeUpdate WsOrderTradeUpdate `json:"o"`
}
// WsAccountUpdate define account update
type WsAccountUpdate struct {
Reason UserDataEventReasonType `json:"m"`
Balances []WsBalance `json:"B"`
Positions []WsPosition `json:"P"`
}
// WsBalance define balance
type WsBalance struct {
Asset string `json:"a"`
Balance string `json:"wb"`
CrossWalletBalance string `json:"cw"`
BalanceChange string `json:"bc"`
}
// WsPosition define position
type WsPosition struct {
Symbol string `json:"s"`
Side PositionSideType `json:"ps"`
Amount string `json:"pa"`
MarginType MarginType `json:"mt"`
IsolatedWallet string `json:"iw"`
EntryPrice string `json:"ep"`
MarkPrice string `json:"mp"`
UnrealizedPnL string `json:"up"`
AccumulatedRealized string `json:"cr"`
MaintenanceMarginRequired string `json:"mm"`
}
// WsOrderTradeUpdate define order trade update
type WsOrderTradeUpdate struct {
Symbol string `json:"s"`
ClientOrderID string `json:"c"`
Side SideType `json:"S"`
Type OrderType `json:"o"`
TimeInForce TimeInForceType `json:"f"`
OriginalQty string `json:"q"`
OriginalPrice string `json:"p"`
AveragePrice string `json:"ap"`
StopPrice string `json:"sp"`
ExecutionType OrderExecutionType `json:"x"`
Status OrderStatusType `json:"X"`
ID int64 `json:"i"`
LastFilledQty string `json:"l"`
AccumulatedFilledQty string `json:"z"`
LastFilledPrice string `json:"L"`
MarginAsset string `json:"ma"`
CommissionAsset string `json:"N"`
Commission string `json:"n"`
TradeTime int64 `json:"T"`
TradeID int64 `json:"t"`
RealizedPnL string `json:"rp"`
BidsNotional string `json:"b"`
AsksNotional string `json:"a"`
IsMaker bool `json:"m"`
IsReduceOnly bool `json:"R"`
WorkingType WorkingType `json:"wt"`
OriginalType OrderType `json:"ot"`
PositionSide PositionSideType `json:"ps"`
IsClosingPosition bool `json:"cp"`
ActivationPrice string `json:"AP"`
CallbackRate string `json:"cr"`
IsProtected bool `json:"pP"`
}
// WsAccountConfigUpdate define account config update
type WsAccountConfigUpdate struct {
Symbol string `json:"s"`
Leverage int64 `json:"l"`
}
// WsUserDataHandler handle WsUserDataEvent
type WsUserDataHandler func(event *WsUserDataEvent)
// WsUserDataServe serve user data handler with listen key
func WsUserDataServe(listenKey string, handler WsUserDataHandler, errHandler ErrHandler) (doneC, stopC chan struct{}, err error) {
endpoint := fmt.Sprintf("%s/%s", getWsEndpoint(), listenKey)
cfg := newWsConfig(endpoint)
wsHandler := func(message []byte) {
event := new(WsUserDataEvent)
err := json.Unmarshal(message, event)
if err != nil {
errHandler(err)
return
}
handler(event)
}
return wsServe(cfg, wsHandler, errHandler)
}
1
https://gitee.com/yuliang_team/go-binance.git
git@gitee.com:yuliang_team/go-binance.git
yuliang_team
go-binance
go-binance
dab6f66bac3c

搜索帮助