bbgo_origin/pkg/exchange/binance/depthframe.go

231 lines
5.6 KiB
Go
Raw Normal View History

package binance
import (
"context"
"sync"
2021-05-25 17:05:12 +00:00
"time"
"github.com/adshao/go-binance/v2"
2021-05-25 17:20:24 +00:00
"github.com/pkg/errors"
)
//go:generate callbackgen -type DepthFrame
type DepthFrame struct {
2021-05-25 11:13:10 +00:00
Symbol string
client *binance.Client
context context.Context
2021-05-25 11:13:10 +00:00
snapshotMutex sync.Mutex
snapshotDepth *DepthEvent
bufMutex sync.Mutex
bufEvents []DepthEvent
2021-05-25 17:20:24 +00:00
resetC chan struct{}
once sync.Once
readyCallbacks []func(snapshotDepth DepthEvent, bufEvents []DepthEvent)
pushCallbacks []func(e DepthEvent)
}
2021-01-25 06:26:22 +00:00
func (f *DepthFrame) reset() {
2021-05-25 11:13:10 +00:00
if debugBinanceDepth {
log.Infof("resetting %s depth frame", f.Symbol)
}
f.bufMutex.Lock()
f.bufEvents = nil
f.bufMutex.Unlock()
f.snapshotMutex.Lock()
f.snapshotDepth = nil
f.once = sync.Once{}
f.snapshotMutex.Unlock()
}
2021-05-25 17:20:24 +00:00
func (f *DepthFrame) emitReset() {
select {
case f.resetC <- struct{}{}:
default:
}
}
2021-05-25 11:13:10 +00:00
func (f *DepthFrame) bufferEvent(e DepthEvent) {
if debugBinanceDepth {
log.Infof("buffering %s depth event FirstUpdateID = %d, FinalUpdateID = %d", f.Symbol, e.FirstUpdateID, e.FinalUpdateID)
}
f.bufMutex.Lock()
f.bufEvents = append(f.bufEvents, e)
f.bufMutex.Unlock()
}
2021-05-25 17:20:24 +00:00
func (f *DepthFrame) loadDepthSnapshot() error {
2021-05-25 17:05:12 +00:00
if debugBinanceDepth {
log.Infof("buffering %s depth events...", f.Symbol)
}
time.Sleep(3 * time.Second)
2021-01-24 06:12:44 +00:00
if debugBinanceDepth {
log.Infof("loading %s depth from the restful api", f.Symbol)
}
depth, err := f.fetch(f.context)
if err != nil {
2021-01-24 08:54:13 +00:00
log.WithError(err).Errorf("depth api error")
2021-05-25 17:20:24 +00:00
return err
}
2021-01-25 05:53:11 +00:00
if len(depth.Asks) == 0 {
log.Errorf("depth response error: empty asks")
2021-05-25 17:20:24 +00:00
return errors.New("depth response error: empty asks")
2021-01-25 05:53:11 +00:00
}
if len(depth.Bids) == 0 {
2021-05-25 17:20:24 +00:00
return errors.New("depth response error: empty bids")
2021-01-25 05:53:11 +00:00
}
2021-05-25 11:13:10 +00:00
if debugBinanceDepth {
log.Infof("loaded %s depth, last update ID = %d", f.Symbol, depth.FinalUpdateID)
}
// filter the events by the event IDs
2021-05-25 11:13:10 +00:00
f.bufMutex.Lock()
bufEvents := f.bufEvents
f.bufEvents = nil
f.bufMutex.Unlock()
var events []DepthEvent
2021-05-25 11:13:10 +00:00
for _, e := range bufEvents {
if e.FinalUpdateID < depth.FinalUpdateID {
if debugBinanceDepth {
log.Infof("DROP %s depth event (final update id is %d older than the last update), updateID %d ~ %d (len %d)",
f.Symbol,
depth.FinalUpdateID-e.FinalUpdateID,
e.FirstUpdateID, e.FinalUpdateID, e.FinalUpdateID-e.FirstUpdateID)
}
continue
}
2021-05-25 11:13:10 +00:00
if debugBinanceDepth {
log.Infof("KEEP %s depth event, updateID %d ~ %d (len %d)",
f.Symbol,
e.FirstUpdateID, e.FinalUpdateID, e.FinalUpdateID-e.FirstUpdateID)
}
events = append(events, e)
}
// since we're buffering the update events, ideally the some of the head events
// should be older than the received depth snapshot.
// if the head event is newer than the depth we got,
// then there are something missed, we need to restart the process.
if len(events) > 0 {
2021-05-25 11:13:10 +00:00
// The first processed event should have U (final update ID) <= lastUpdateId+1 AND (first update id) >= lastUpdateId+1.
firstEvent := events[0]
2021-05-25 11:13:10 +00:00
// valid
nextID := depth.FinalUpdateID + 1
if firstEvent.FirstUpdateID > nextID || firstEvent.FinalUpdateID < nextID {
2021-05-25 17:05:12 +00:00
log.Warn("MISMATCH final update id for order book, resetting depth...")
2021-05-25 17:20:24 +00:00
return errors.New("MISMATCH final update id for order book, resetting depth...")
}
2021-05-25 11:13:10 +00:00
if debugBinanceDepth {
log.Infof("VALID first %s depth event, updateID %d ~ %d (len %d)",
f.Symbol,
firstEvent.FirstUpdateID, firstEvent.FinalUpdateID, firstEvent.FinalUpdateID-firstEvent.FirstUpdateID)
}
}
2021-05-25 11:13:10 +00:00
if debugBinanceDepth {
log.Infof("READY %s depth, %d bufferred events", f.Symbol, len(events))
}
2021-05-25 16:58:21 +00:00
f.snapshotMutex.Lock()
f.snapshotDepth = depth
f.snapshotMutex.Unlock()
f.EmitReady(*depth, events)
2021-05-25 17:20:24 +00:00
return nil
}
func (f *DepthFrame) PushEvent(e DepthEvent) {
2021-05-25 11:13:10 +00:00
f.snapshotMutex.Lock()
snapshot := f.snapshotDepth
f.snapshotMutex.Unlock()
// before the snapshot is loaded, we need to buffer the events until we loaded the snapshot.
2021-05-25 11:13:10 +00:00
if snapshot == nil {
2021-05-25 17:20:24 +00:00
select {
case <-f.resetC:
f.reset()
default:
// buffer the events until we loaded the snapshot
f.bufferEvent(e)
}
go f.once.Do(func() {
if err := f.loadDepthSnapshot(); err != nil {
log.WithError(err).Error("depth snapshot load failed, resetting..")
f.emitReset()
}
})
2021-05-25 11:13:10 +00:00
return
}
2021-05-25 11:13:10 +00:00
// drop old events
if e.FinalUpdateID <= snapshot.FinalUpdateID {
2021-05-25 13:36:14 +00:00
log.Infof("DROP %s depth update event, updateID %d ~ %d (len %d)",
f.Symbol,
e.FirstUpdateID, e.FinalUpdateID, e.FinalUpdateID-e.FirstUpdateID)
return
}
if e.FirstUpdateID > snapshot.FinalUpdateID+1 {
log.Infof("MISSING %s depth update event, resetting, updateID %d ~ %d (len %d)",
f.Symbol,
e.FirstUpdateID, e.FinalUpdateID, e.FinalUpdateID-e.FirstUpdateID)
2021-05-25 17:20:24 +00:00
f.emitReset()
2021-05-25 11:13:10 +00:00
return
}
2021-05-25 11:13:10 +00:00
f.snapshotMutex.Lock()
f.snapshotDepth.FinalUpdateID = e.FinalUpdateID
f.snapshotMutex.Unlock()
f.EmitPush(e)
}
// fetch fetches the depth and convert to the depth event so that we can reuse the event structure to convert it to the global orderbook type
func (f *DepthFrame) fetch(ctx context.Context) (*DepthEvent, error) {
if debugBinanceDepth {
log.Infof("fetching %s depth snapshot", f.Symbol)
}
response, err := f.client.NewDepthService().Symbol(f.Symbol).Do(ctx)
if err != nil {
return nil, err
}
event := DepthEvent{
2021-05-25 13:36:14 +00:00
Symbol: f.Symbol,
FirstUpdateID: 0,
FinalUpdateID: response.LastUpdateID,
}
for _, entry := range response.Bids {
event.Bids = append(event.Bids, DepthEntry{PriceLevel: entry.Price, Quantity: entry.Quantity})
}
for _, entry := range response.Asks {
event.Asks = append(event.Asks, DepthEntry{PriceLevel: entry.Price, Quantity: entry.Quantity})
}
return &event, nil
}