bbgo_origin/pkg/strategy/rebalance/strategy.go

293 lines
7.0 KiB
Go
Raw Permalink 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"
2023-03-12 15:48:26 +00:00
"sync"
2021-12-12 09:19:27 +00:00
2023-10-31 05:53:12 +00:00
"github.com/robfig/cron/v3"
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)
2023-10-31 05:53:12 +00:00
var two = fixedpoint.NewFromFloat(2.0)
2021-12-12 09:19:27 +00:00
func init() {
bbgo.RegisterStrategy(ID, &Strategy{})
}
2023-03-12 15:48:26 +00:00
func instanceID(symbol string) string {
return fmt.Sprintf("%s:%s", ID, symbol)
}
2021-12-12 09:19:27 +00:00
type Strategy struct {
2023-10-31 05:53:12 +00:00
*MultiMarketStrategy
2023-03-08 13:54:36 +00:00
Environment *bbgo.Environment
2023-10-31 05:53:12 +00:00
CronExpression string `json:"cronExpression"`
QuoteCurrency string `json:"quoteCurrency"`
TargetWeights types.ValueMap `json:"targetWeights"`
Threshold fixedpoint.Value `json:"threshold"`
MaxAmount fixedpoint.Value `json:"maxAmount"` // max amount to buy or sell per order
OrderType types.OrderType `json:"orderType"`
DryRun bool `json:"dryRun"`
OnStart bool `json:"onStart"` // rebalance on start
symbols []string
markets map[string]types.Market
activeOrderBook *bbgo.ActiveOrderBook
cron *cron.Cron
}
func (s *Strategy) Defaults() error {
if s.OrderType == "" {
s.OrderType = types.OrderTypeLimitMaker
}
return nil
}
func (s *Strategy) Initialize() error {
2023-12-20 12:21:34 +00:00
if s.MultiMarketStrategy == nil {
s.MultiMarketStrategy = &MultiMarketStrategy{}
}
2023-10-31 05:53:12 +00:00
for currency := range s.TargetWeights {
if currency == s.QuoteCurrency {
continue
}
s.symbols = append(s.symbols, currency+s.QuoteCurrency)
}
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
}
2023-10-31 05:53:12 +00:00
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {}
2021-12-12 09:19:27 +00:00
2023-03-08 13:54:36 +00:00
func (s *Strategy) Run(ctx context.Context, _ bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
2023-10-31 05:53:12 +00:00
s.markets = make(map[string]types.Market)
for _, symbol := range s.symbols {
2023-11-03 07:07:24 +00:00
market, ok := session.Market(symbol)
2023-10-31 05:53:12 +00:00
if !ok {
return fmt.Errorf("market %s not found", symbol)
}
s.markets[symbol] = market
2022-06-15 19:24:39 +00:00
}
2023-10-31 05:53:12 +00:00
s.MultiMarketStrategy.Initialize(ctx, s.Environment, session, s.markets, ID)
2023-03-08 13:54:36 +00:00
s.activeOrderBook = bbgo.NewActiveOrderBook("")
2023-11-03 07:07:24 +00:00
s.activeOrderBook.BindStream(session.UserDataStream)
2023-12-20 12:35:43 +00:00
s.activeOrderBook.OnFilled(func(order types.Order) {
s.rebalance(ctx)
})
2023-03-08 13:54:36 +00:00
2023-03-13 14:43:42 +00:00
session.UserDataStream.OnStart(func() {
if s.OnStart {
s.rebalance(ctx)
}
})
2023-03-12 15:48:26 +00:00
// the shutdown handler, you can cancel all orders
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
2023-10-31 05:53:12 +00:00
_ = s.OrderExecutorMap.GracefulCancel(ctx)
2023-03-12 15:48:26 +00:00
})
2023-03-08 13:54:36 +00:00
2023-10-31 05:53:12 +00:00
s.cron = cron.New()
s.cron.AddFunc(s.CronExpression, func() {
s.rebalance(ctx)
})
s.cron.Start()
2023-03-12 15:48:26 +00:00
return nil
2023-03-08 13:54:36 +00:00
}
func (s *Strategy) rebalance(ctx context.Context) {
// cancel active orders before rebalance
2023-12-20 12:26:34 +00:00
if err := s.activeOrderBook.GracefulCancel(ctx, s.Session.Exchange); err != nil {
log.WithError(err).Errorf("failed to cancel orders")
2021-12-12 09:19:27 +00:00
}
2023-10-31 05:53:12 +00:00
order, err := s.generateOrder(ctx)
2023-03-13 08:46:18 +00:00
if err != nil {
2023-10-31 05:53:12 +00:00
log.WithError(err).Error("failed to generate order")
2023-03-13 08:46:18 +00:00
return
}
2023-10-31 05:53:12 +00:00
if order == nil {
log.Info("no order generated")
return
2022-03-23 15:52:59 +00:00
}
2023-10-31 05:53:12 +00:00
log.Infof("generated order: %s", order.String())
2022-03-23 15:52:59 +00:00
if s.DryRun {
2023-03-13 08:58:19 +00:00
log.Infof("dry run, not submitting orders")
2022-03-23 15:52:59 +00:00
return
}
2023-10-31 05:53:12 +00:00
createdOrders, err := s.OrderExecutorMap.SubmitOrders(ctx, *order)
2023-03-12 15:48:26 +00:00
if err != nil {
log.WithError(err).Error("failed to submit orders")
return
2021-12-12 09:19:27 +00:00
}
2023-03-12 15:48:26 +00:00
s.activeOrderBook.Add(createdOrders...)
2021-12-12 09:19:27 +00:00
}
2023-10-31 05:53:12 +00:00
func (s *Strategy) queryMidPrices(ctx context.Context) (types.ValueMap, error) {
m := make(types.ValueMap)
for currency := range s.TargetWeights {
2022-10-13 10:16:11 +00:00
if currency == s.QuoteCurrency {
m[s.QuoteCurrency] = fixedpoint.One
2021-12-12 09:19:27 +00:00
continue
}
2023-11-03 07:07:24 +00:00
ticker, err := s.Session.Exchange.QueryTicker(ctx, currency+s.QuoteCurrency)
2022-10-28 07:15:55 +00:00
if err != nil {
2023-03-13 08:46:18 +00:00
return nil, err
2022-10-28 07:15:55 +00:00
}
2023-10-31 05:53:12 +00:00
m[currency] = ticker.Buy.Add(ticker.Sell).Div(two)
2022-10-28 07:15:55 +00:00
}
2023-03-13 08:46:18 +00:00
return m, nil
2021-12-12 09:19:27 +00:00
}
2023-10-31 05:53:12 +00:00
func (s *Strategy) selectBalances() (types.BalanceMap, error) {
2023-03-13 08:46:18 +00:00
m := make(types.BalanceMap)
2023-11-03 07:07:24 +00:00
balances := s.Session.GetAccount().Balances()
for currency := range s.TargetWeights {
2023-03-13 08:46:18 +00:00
balance, ok := balances[currency]
if !ok {
return nil, fmt.Errorf("no balance for %s", currency)
}
m[currency] = balance
2021-12-12 09:19:27 +00:00
}
2023-03-13 08:46:18 +00:00
return m, nil
2021-12-12 09:19:27 +00:00
}
2023-10-31 05:53:12 +00:00
func (s *Strategy) generateOrder(ctx context.Context) (*types.SubmitOrder, error) {
prices, err := s.queryMidPrices(ctx)
2023-03-13 08:46:18 +00:00
if err != nil {
return nil, err
}
2023-10-31 05:53:12 +00:00
balances, err := s.selectBalances()
2023-03-13 08:46:18 +00:00
if err != nil {
return nil, err
}
2021-12-13 07:19:34 +00:00
2023-10-31 05:53:12 +00:00
values := prices.Mul(toValueMap(balances))
weights := values.Normalize()
2023-10-31 05:53:12 +00:00
for symbol, market := range s.markets {
target := s.TargetWeights[market.BaseCurrency]
weight := weights[market.BaseCurrency]
midPrice := prices[market.BaseCurrency]
2023-10-31 05:53:12 +00:00
log.Infof("%s mid price: %s", symbol, midPrice.String())
log.Infof("%s weight: %.2f%%, target: %.2f%%", market.BaseCurrency, weight.Float64()*100, target.Float64()*100)
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
2023-10-31 05:53:12 +00:00
diff := target.Sub(weight)
if diff.Abs().Compare(s.Threshold) < 0 {
log.Infof("%s weight is close to target, skip", market.BaseCurrency)
2021-12-12 09:19:27 +00:00
continue
}
2023-10-31 05:53:12 +00:00
quantity := diff.Mul(values.Sum()).Div(midPrice)
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
2023-11-03 07:07:24 +00:00
ticker, err := s.Session.Exchange.QueryTicker(ctx, symbol)
if err != nil {
return nil, err
2022-05-26 07:57:38 +00:00
}
2021-12-12 09:19:27 +00:00
2023-11-03 07:07:24 +00:00
var price fixedpoint.Value
2023-10-31 05:53:12 +00:00
if side == types.SideTypeBuy {
2023-11-03 07:07:24 +00:00
price = ticker.Buy
quantity = fixedpoint.Min(quantity, balances[s.QuoteCurrency].Available.Div(ticker.Sell))
2023-10-31 05:53:12 +00:00
} else if side == types.SideTypeSell {
2023-11-03 07:07:24 +00:00
price = ticker.Sell
2023-10-31 05:53:12 +00:00
quantity = fixedpoint.Min(quantity, balances[market.BaseCurrency].Available)
2023-03-13 10:24:46 +00:00
}
2022-03-23 15:52:59 +00:00
2023-11-03 07:07:24 +00:00
if s.MaxAmount.Float64() > 0 {
quantity = bbgo.AdjustQuantityByMaxAmount(quantity, price, s.MaxAmount)
log.Infof("adjusted quantity %s (%s %s @ %s) by max amount %s",
quantity.String(),
symbol,
side.String(),
price.String(),
s.MaxAmount.String())
}
if market.IsDustQuantity(quantity, price) {
2023-10-31 05:53:12 +00:00
log.Infof("quantity %s (%s %s @ %s) is dust quantity, skip",
quantity.String(),
symbol,
side.String(),
2023-11-03 07:07:24 +00:00
price.String())
2022-03-23 15:52:59 +00:00
continue
}
2023-03-13 08:46:18 +00:00
2023-10-31 05:53:12 +00:00
return &types.SubmitOrder{
Symbol: symbol,
Side: side,
Type: s.OrderType,
Quantity: quantity,
2023-11-03 07:07:24 +00:00
Price: price,
2023-10-31 05:53:12 +00:00
}, nil
2023-03-13 08:46:18 +00:00
}
2023-10-31 05:53:12 +00:00
return nil, nil
2023-03-13 08:46:18 +00:00
}
2023-10-31 05:53:12 +00:00
func toValueMap(balances types.BalanceMap) types.ValueMap {
2023-03-13 08:46:18 +00:00
m := make(types.ValueMap)
for _, b := range balances {
2023-10-31 05:53:12 +00:00
// m[b.Currency] = b.Net()
m[b.Currency] = b.Available
2023-03-13 08:46:18 +00:00
}
return m
}