bbgo_origin/pkg/strategy/rebalance/strategy.go

223 lines
5.5 KiB
Go
Raw Normal View History

2022-03-29 13:51:50 +00:00
package rebalance
2021-12-12 09:19:27 +00:00
import (
"context"
2021-12-21 17:50:27 +00:00
"fmt"
2021-12-12 09:19:27 +00:00
"github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
)
const ID = "rebalance"
var log = logrus.WithField("strategy", ID)
func init() {
bbgo.RegisterStrategy(ID, &Strategy{})
}
type Strategy struct {
Notifiability *bbgo.Notifiability
Interval types.Interval `json:"interval"`
BaseCurrency string `json:"baseCurrency"`
TargetWeights types.ValueMap `json:"targetWeights"`
Threshold fixedpoint.Value `json:"threshold"`
DryRun bool `json:"dryRun"`
2022-06-15 19:24:39 +00:00
// max amount to buy or sell per order
MaxAmount fixedpoint.Value `json:"maxAmount"`
2022-06-15 16:20:53 +00:00
activeOrderBook *bbgo.ActiveOrderBook
}
func (s *Strategy) Initialize() error {
return nil
2021-12-12 09:19:27 +00:00
}
func (s *Strategy) ID() string {
return ID
}
2021-12-21 17:50:27 +00:00
func (s *Strategy) Validate() error {
if len(s.TargetWeights) == 0 {
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")
}
2021-12-21 17:50:27 +00:00
for currency, weight := range s.TargetWeights {
if weight.Float64() < 0 {
return fmt.Errorf("%s weight: %f should not less than 0", currency, weight.Float64())
}
}
if s.Threshold.Sign() < 0 {
2021-12-21 17:50:27 +00:00
return fmt.Errorf("threshold should not less than 0")
}
if s.MaxAmount.Sign() < 0 {
2021-12-21 17:50:27 +00:00
return fmt.Errorf("maxAmount shoud not less than 0")
}
return nil
}
2022-03-23 15:52:59 +00:00
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
session.Subscribe(types.KLineChannel, s.symbols()[0], types.SubscribeOptions{Interval: s.Interval})
2022-03-23 15:52:59 +00:00
}
2021-12-12 09:19:27 +00:00
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
s.activeOrderBook = bbgo.NewActiveOrderBook("")
s.activeOrderBook.BindStream(session.UserDataStream)
2022-05-26 07:57:38 +00:00
2022-06-15 19:24:39 +00:00
markets := session.Markets()
for _, symbol := range s.symbols() {
if _, ok := markets[symbol]; !ok {
return fmt.Errorf("exchange: %s does not supoort matket: %s", session.Exchange.Name(), symbol)
}
}
2022-03-23 15:52:59 +00:00
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
s.rebalance(ctx, orderExecutor, session)
})
2021-12-12 09:19:27 +00:00
return nil
}
2022-06-15 17:46:33 +00:00
2021-12-13 07:19:34 +00:00
func (s *Strategy) rebalance(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) {
// cancel active orders before rebalance
if err := session.Exchange.CancelOrders(ctx, s.activeOrderBook.Orders()...); err != nil {
log.WithError(err).Errorf("failed to cancel orders")
2021-12-12 09:19:27 +00:00
}
submitOrders := s.generateSubmitOrders(ctx, session)
2022-06-15 15:35:40 +00:00
for _, order := range submitOrders {
2022-03-23 15:52:59 +00:00
log.Infof("generated submit order: %s", order.String())
}
if s.DryRun {
return
}
2022-06-15 15:35:40 +00:00
createdOrders, err := orderExecutor.SubmitOrders(ctx, submitOrders...)
2021-12-12 09:19:27 +00:00
if err != nil {
2022-06-15 16:20:53 +00:00
log.WithError(err).Error("failed to submit orders")
2021-12-12 09:19:27 +00:00
return
}
2022-05-26 07:57:38 +00:00
s.activeOrderBook.Add(createdOrders...)
2021-12-12 09:19:27 +00:00
}
func (s *Strategy) prices(ctx context.Context, session *bbgo.ExchangeSession) types.ValueMap {
m := make(types.ValueMap)
tickers, err := session.Exchange.QueryTickers(ctx, s.symbols()...)
if err != nil {
log.WithError(err).Error("failed to query tickers")
return nil
}
for currency := range s.TargetWeights {
2021-12-12 09:19:27 +00:00
if currency == s.BaseCurrency {
m[s.BaseCurrency] = fixedpoint.One
2021-12-12 09:19:27 +00:00
continue
}
m[currency] = tickers[currency+s.BaseCurrency].Last
2021-12-12 09:19:27 +00:00
}
return m
2021-12-12 09:19:27 +00:00
}
func (s *Strategy) quantities(session *bbgo.ExchangeSession) types.ValueMap {
m := make(types.ValueMap)
balances := session.GetAccount().Balances()
for currency := range s.TargetWeights {
m[currency] = balances[currency].Total()
2021-12-12 09:19:27 +00:00
}
return m
2021-12-12 09:19:27 +00:00
}
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()
2021-12-13 07:19:34 +00:00
for currency, targetWeight := range s.TargetWeights {
2021-12-12 09:19:27 +00:00
if currency == s.BaseCurrency {
continue
}
2021-12-12 09:19:27 +00:00
symbol := currency + s.BaseCurrency
currentWeight := currentWeights[currency]
currentPrice := prices[currency]
log.Infof("%s price: %v, current weight: %v, target weight: %v",
2021-12-21 17:41:48 +00:00
symbol,
currentPrice,
currentWeight,
targetWeight)
2021-12-12 09:19:27 +00:00
2021-12-20 15:27:03 +00:00
// 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.Sub(currentWeight)
if weightDifference.Abs().Compare(s.Threshold) < 0 {
log.Infof("%s weight distance |%v - %v| = |%v| less than the threshold: %v",
2021-12-21 18:04:44 +00:00
symbol,
currentWeight,
targetWeight,
weightDifference,
s.Threshold)
2021-12-12 09:19:27 +00:00
continue
}
quantity := weightDifference.Mul(marketValues.Sum()).Div(currentPrice)
2021-12-12 09:19:27 +00:00
side := types.SideTypeBuy
if quantity.Sign() < 0 {
2021-12-12 09:19:27 +00:00
side = types.SideTypeSell
quantity = quantity.Abs()
}
2021-12-13 07:19:34 +00:00
if s.MaxAmount.Sign() > 0 {
quantity = bbgo.AdjustQuantityByMaxAmount(quantity, currentPrice, s.MaxAmount)
log.Infof("adjust the quantity %v (%s %s @ %v) by max amount %v",
quantity,
2021-12-20 15:27:03 +00:00
symbol,
side.String(),
currentPrice,
s.MaxAmount)
2021-12-20 15:27:03 +00:00
}
log.Debugf("symbol: %v, quantity: %v", symbol, quantity)
2021-12-12 09:19:27 +00:00
order := types.SubmitOrder{
Symbol: symbol,
Side: side,
2022-05-26 07:57:38 +00:00
Type: types.OrderTypeLimit,
Quantity: quantity,
Price: currentPrice,
2022-05-26 07:57:38 +00:00
}
2021-12-12 09:19:27 +00:00
submitOrders = append(submitOrders, order)
}
2021-12-12 09:19:27 +00:00
return submitOrders
}
2022-03-23 15:52:59 +00:00
2022-06-15 13:34:42 +00:00
func (s *Strategy) symbols() (symbols []string) {
for currency := range s.TargetWeights {
2022-03-23 15:52:59 +00:00
if currency == s.BaseCurrency {
continue
}
symbols = append(symbols, currency+s.BaseCurrency)
2022-03-23 15:52:59 +00:00
}
return symbols
}