rebalance: manage active order book without specifying symbol

This commit is contained in:
なるみ 2022-06-15 23:34:57 +08:00
parent a4814951d4
commit 87adf694b1

View File

@ -35,7 +35,7 @@ type Strategy struct {
currencies []string currencies []string
activeOrderBooks map[string]*bbgo.ActiveOrderBook activeOrderBook *bbgo.ActiveOrderBook
} }
func (s *Strategy) Initialize() error { func (s *Strategy) Initialize() error {
@ -80,12 +80,8 @@ func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
} }
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error { func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
s.activeOrderBooks = make(map[string]*bbgo.ActiveOrderBook) s.activeOrderBook = bbgo.NewActiveOrderBook("")
for _, symbol := range s.symbols() { s.activeOrderBook.BindStream(session.UserDataStream)
activeOrderBook := bbgo.NewActiveOrderBook(symbol)
activeOrderBook.BindStream(session.UserDataStream)
s.activeOrderBooks[symbol] = activeOrderBook
}
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) { session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
if kline.Symbol != s.currencies[0]+s.BaseCurrency { if kline.Symbol != s.currencies[0]+s.BaseCurrency {
@ -97,12 +93,10 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
} }
func (s *Strategy) rebalance(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) { func (s *Strategy) rebalance(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) {
for symbol, book := range s.activeOrderBooks { err := orderExecutor.CancelOrders(ctx, s.activeOrderBook.Orders()...)
err := orderExecutor.CancelOrders(ctx, book.Orders()...) if err != nil {
if err != nil { log.WithError(err).Error("failed to cancel orders")
log.WithError(err).Errorf("failed to cancel %s orders", symbol) return
return
}
} }
prices, err := s.prices(ctx, session) prices, err := s.prices(ctx, session)
@ -127,9 +121,7 @@ func (s *Strategy) rebalance(ctx context.Context, orderExecutor bbgo.OrderExecut
return return
} }
for _, createdOrder := range createdOrders { s.activeOrderBook.Add(createdOrders...)
s.activeOrderBooks[createdOrder.Symbol].Add(createdOrder)
}
} }
func (s *Strategy) prices(ctx context.Context, session *bbgo.ExchangeSession) (prices types.Float64Slice, err error) { func (s *Strategy) prices(ctx context.Context, session *bbgo.ExchangeSession) (prices types.Float64Slice, err error) {