rebalance: replace Float64Slice by ValueMap

This commit is contained in:
なるみ 2022-06-16 02:52:52 +08:00
parent 0a602bc259
commit 3d0ad010eb

View File

@ -3,8 +3,6 @@ package rebalance
import (
"context"
"fmt"
"math"
"sort"
"github.com/sirupsen/logrus"
@ -24,33 +22,18 @@ func init() {
type Strategy struct {
Notifiability *bbgo.Notifiability
Interval types.Interval `json:"interval"`
BaseCurrency string `json:"baseCurrency"`
TargetWeights map[string]fixedpoint.Value `json:"targetWeights"`
Threshold fixedpoint.Value `json:"threshold"`
Verbose bool `json:"verbose"`
DryRun bool `json:"dryRun"`
// max amount to buy or sell per order
MaxAmount fixedpoint.Value `json:"maxAmount"`
// sorted currencies
currencies []string
// symbol for subscribing kline
symbol string
Interval types.Interval `json:"interval"`
BaseCurrency string `json:"baseCurrency"`
TargetWeights fixedpoint.ValueMap `json:"targetWeights"`
Threshold fixedpoint.Value `json:"threshold"`
Verbose bool `json:"verbose"`
DryRun bool `json:"dryRun"`
MaxAmount fixedpoint.Value `json:"maxAmount"` // max amount to buy or sell per order
activeOrderBook *bbgo.ActiveOrderBook
}
func (s *Strategy) Initialize() error {
for currency := range s.TargetWeights {
s.currencies = append(s.currencies, currency)
}
sort.Strings(s.currencies)
s.symbol = s.currencies[0] + s.BaseCurrency
return nil
}
@ -63,6 +46,10 @@ func (s *Strategy) Validate() error {
return fmt.Errorf("targetWeights should not be empty")
}
if !s.TargetWeights.Sum().Eq(fixedpoint.One) {
return fmt.Errorf("the sum of targetWeights should be 1")
}
for currency, weight := range s.TargetWeights {
if weight.Float64() < 0 {
return fmt.Errorf("%s weight: %f should not less than 0", currency, weight.Float64())
@ -81,7 +68,7 @@ func (s *Strategy) Validate() error {
}
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
session.Subscribe(types.KLineChannel, s.symbol, types.SubscribeOptions{Interval: s.Interval})
session.Subscribe(types.KLineChannel, s.symbols()[0], types.SubscribeOptions{Interval: s.Interval})
}
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
@ -89,25 +76,18 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
s.activeOrderBook.BindStream(session.UserDataStream)
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
// cancel active orders before rebalance
if err := session.Exchange.CancelOrders(ctx, s.activeOrderBook.Orders()...); err != nil {
log.WithError(err).Errorf("failed to cancel orders")
}
s.rebalance(ctx, orderExecutor, session)
})
return nil
}
func (s *Strategy) rebalance(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) {
prices, err := s.prices(ctx, session)
if err != nil {
return
// cancel active orders before rebalance
if err := session.Exchange.CancelOrders(ctx, s.activeOrderBook.Orders()...); err != nil {
log.WithError(err).Errorf("failed to cancel orders")
}
marketValues := prices.Mul(s.quantities(session))
submitOrders := s.generateSubmitOrders(prices, marketValues)
submitOrders := s.generateSubmitOrders(ctx, session)
for _, order := range submitOrders {
log.Infof("generated submit order: %s", order.String())
}
@ -125,44 +105,50 @@ func (s *Strategy) rebalance(ctx context.Context, orderExecutor bbgo.OrderExecut
s.activeOrderBook.Add(createdOrders...)
}
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) fixedpoint.ValueMap {
m := make(fixedpoint.ValueMap)
tickers, err := session.Exchange.QueryTickers(ctx, s.symbols()...)
if err != nil {
return nil, err
log.WithError(err).Error("failed to query tickers")
return nil
}
for _, currency := range s.currencies {
for currency := range s.TargetWeights {
if currency == s.BaseCurrency {
prices = append(prices, 1.0)
m[s.BaseCurrency] = fixedpoint.One
continue
}
symbol := currency + s.BaseCurrency
prices = append(prices, tickers[symbol].Last.Float64())
m[currency] = tickers[currency+s.BaseCurrency].Last
}
return prices, nil
return m
}
func (s *Strategy) quantities(session *bbgo.ExchangeSession) (quantities types.Float64Slice) {
func (s *Strategy) quantities(session *bbgo.ExchangeSession) fixedpoint.ValueMap {
m := make(fixedpoint.ValueMap)
balances := session.GetAccount().Balances()
for _, currency := range s.currencies {
quantities = append(quantities, balances[currency].Total().Float64())
for currency := range s.TargetWeights {
m[currency] = balances[currency].Total()
}
return quantities
return m
}
func (s *Strategy) generateSubmitOrders(prices, marketValues types.Float64Slice) (submitOrders []types.SubmitOrder) {
func (s *Strategy) generateSubmitOrders(ctx context.Context, session *bbgo.ExchangeSession) (submitOrders []types.SubmitOrder) {
prices := s.prices(ctx, session)
marketValues := prices.Mul(s.quantities(session))
currentWeights := marketValues.Normalize()
for i, currency := range s.currencies {
for currency, targetWeight := range s.TargetWeights {
if currency == s.BaseCurrency {
continue
}
symbol := currency + s.BaseCurrency
currentWeight := currentWeights[i]
currentPrice := prices[i]
targetWeight := s.TargetWeights[currency].Float64()
currentWeight := currentWeights[currency]
currentPrice := prices[currency]
log.Infof("%s price: %v, current weight: %v, target weight: %v",
symbol,
@ -172,8 +158,8 @@ func (s *Strategy) generateSubmitOrders(prices, marketValues types.Float64Slice)
// calculate the difference between current weight and target weight
// if the difference is less than threshold, then we will not create the order
weightDifference := targetWeight - currentWeight
if math.Abs(weightDifference) < s.Threshold.Float64() {
weightDifference := targetWeight.Sub(currentWeight)
if weightDifference.Abs().Compare(s.Threshold) < 0 {
log.Infof("%s weight distance |%v - %v| = |%v| less than the threshold: %v",
symbol,
currentWeight,
@ -183,7 +169,7 @@ func (s *Strategy) generateSubmitOrders(prices, marketValues types.Float64Slice)
continue
}
quantity := fixedpoint.NewFromFloat((weightDifference * marketValues.Sum()) / currentPrice)
quantity := weightDifference.Mul(marketValues.Sum()).Div(currentPrice)
side := types.SideTypeBuy
if quantity.Sign() < 0 {
@ -192,7 +178,7 @@ func (s *Strategy) generateSubmitOrders(prices, marketValues types.Float64Slice)
}
if s.MaxAmount.Sign() > 0 {
quantity = bbgo.AdjustQuantityByMaxAmount(quantity, fixedpoint.NewFromFloat(currentPrice), s.MaxAmount)
quantity = bbgo.AdjustQuantityByMaxAmount(quantity, currentPrice, s.MaxAmount)
log.Infof("adjust the quantity %v (%s %s @ %v) by max amount %v",
quantity,
symbol,
@ -200,22 +186,25 @@ func (s *Strategy) generateSubmitOrders(prices, marketValues types.Float64Slice)
currentPrice,
s.MaxAmount)
}
log.Debugf("symbol: %v, quantity: %v", symbol, quantity)
order := types.SubmitOrder{
Symbol: symbol,
Side: side,
Type: types.OrderTypeLimit,
Quantity: quantity,
Price: fixedpoint.NewFromFloat(currentPrice),
Price: currentPrice,
}
submitOrders = append(submitOrders, order)
}
return submitOrders
}
func (s *Strategy) symbols() (symbols []string) {
for _, currency := range s.currencies {
for currency := range s.TargetWeights {
if currency == s.BaseCurrency {
continue
}