Skip to content

Commit

Permalink
binance: Desync books on disconnect.
Browse files Browse the repository at this point in the history
  • Loading branch information
JoeGruffins committed Sep 25, 2024
1 parent ab9457b commit adef014
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions client/mm/libxc/binance.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ type binanceOrderBook struct {
baseConversionFactor uint64
quoteConversionFactor uint64
log dex.Logger

connectedChan chan bool
}

func newBinanceOrderBook(
Expand All @@ -86,6 +88,7 @@ func newBinanceOrderBook(
quoteConversionFactor: quoteConversionFactor,
log: log,
getSnapshot: getSnapshot,
connectedChan: make(chan bool),
}
}

Expand Down Expand Up @@ -288,6 +291,13 @@ func (b *binanceOrderBook) Connect(ctx context.Context) (*sync.WaitGroup, error
if retry != nil { // don't hammer
continue
}
case connected := <-b.connectedChan:
if !connected {
b.log.Debugf("Unsyncing %s orderbook due to disconnect.", b.mktID, retryFrequency)
desync()
retry = nil
continue
}
case <-ctx.Done():
return
}
Expand All @@ -296,7 +306,7 @@ func (b *binanceOrderBook) Connect(ctx context.Context) (*sync.WaitGroup, error
b.log.Infof("Synced %s orderbook", b.mktID)
retry = nil
} else {
b.log.Infof("Failed to sync %s orderbook. Trying again in %s", b.mktID, retryFrequency)
b.log.Infof("Failed to sync %s orderbook. Trying again in %s", b.mktID, retryFrequency)
desync() // Clears the syncCache
retry = time.After(retryFrequency)
}
Expand Down Expand Up @@ -1745,6 +1755,19 @@ func (bnc *binance) connectToMarketDataStream(ctx context.Context, baseID, quote
newConnection := func() (comms.WsConn, *dex.ConnectionMaster, error) {
addr := fmt.Sprintf("%s/stream?streams=%s", bnc.wsURL, strings.Join(bnc.streams(), "/"))
// Need to send key but not signature
connectEventFunc := func(cs comms.ConnectionStatus) {
if cs != comms.Disconnected && cs != comms.Connected {
return
}
// If disconnected, set all books to unsynced so bots
// will not place new orders.
connected := cs == comms.Connected
bnc.booksMtx.RLock()
defer bnc.booksMtx.RLock()
for _, b := range bnc.books {
b.connectedChan <- connected
}
}
conn, err := comms.NewWsConn(&comms.WsCfg{
URL: addr,
// Binance Docs: The websocket server will send a ping frame every 3
Expand All @@ -1759,7 +1782,7 @@ func (bnc *binance) connectToMarketDataStream(ctx context.Context, baseID, quote
default:
}
},
ConnectEventFunc: func(cs comms.ConnectionStatus) {},
ConnectEventFunc: connectEventFunc,
Logger: bnc.log.SubLogger("BNCBOOK"),
RawHandler: bnc.handleMarketDataNote,
})
Expand Down

0 comments on commit adef014

Please sign in to comment.