bbgo_origin/pkg/strategy/rebalance/strategy.go

337 lines
8.5 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
"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{})
}
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-03-08 13:54:36 +00:00
Environment *bbgo.Environment
Interval types.Interval `json:"interval"`
2022-10-13 10:16:11 +00:00
QuoteCurrency string `json:"quoteCurrency"`
TargetWeights types.ValueMap `json:"targetWeights"`
Threshold fixedpoint.Value `json:"threshold"`
2023-03-02 07:56:25 +00:00
MaxAmount fixedpoint.Value `json:"maxAmount"` // max amount to buy or sell per order
OrderType types.OrderType `json:"orderType"`
DryRun bool `json:"dryRun"`
2023-03-13 14:43:42 +00:00
OnStart bool `json:"onStart"` // rebalance on start
2022-06-15 16:20:53 +00:00
2023-03-12 15:48:26 +00:00
PositionMap PositionMap `persistence:"positionMap"`
ProfitStatsMap ProfitStatsMap `persistence:"profitStatsMap"`
2023-03-08 13:54:36 +00:00
session *bbgo.ExchangeSession
2023-03-12 15:48:26 +00:00
orderExecutorMap GeneralOrderExecutorMap
2023-03-08 13:54:36 +00:00
activeOrderBook *bbgo.ActiveOrderBook
}
func (s *Strategy) Defaults() error {
if s.OrderType == "" {
s.OrderType = types.OrderTypeLimitMaker
}
return nil
}
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) {
2022-10-28 07:15:55 +00:00
for _, symbol := range s.symbols() {
session.Subscribe(types.KLineChannel, symbol, types.SubscribeOptions{Interval: s.Interval})
}
2022-03-23 15:52:59 +00:00
}
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 {
s.session = session
2022-05-26 07:57:38 +00:00
2023-03-08 13:54:36 +00:00
markets, err := s.markets()
if err != nil {
return err
}
if s.PositionMap == nil {
2023-03-14 06:37:54 +00:00
s.PositionMap = make(PositionMap)
2023-03-08 13:54:36 +00:00
}
s.PositionMap.CreatePositions(markets)
2023-03-08 13:54:36 +00:00
if s.ProfitStatsMap == nil {
2023-03-14 06:37:54 +00:00
s.ProfitStatsMap = make(ProfitStatsMap)
2022-06-15 19:24:39 +00:00
}
s.ProfitStatsMap.CreateProfitStats(markets)
2022-06-15 19:24:39 +00:00
2023-03-12 15:48:26 +00:00
s.orderExecutorMap = NewGeneralOrderExecutorMap(session, s.PositionMap)
s.orderExecutorMap.BindEnvironment(s.Environment)
s.orderExecutorMap.BindProfitStats(s.ProfitStatsMap)
s.orderExecutorMap.Bind()
s.orderExecutorMap.Sync(ctx, s)
2023-03-08 13:54:36 +00:00
s.activeOrderBook = bbgo.NewActiveOrderBook("")
s.activeOrderBook.BindStream(s.session.UserDataStream)
2023-03-13 14:43:42 +00:00
session.UserDataStream.OnStart(func() {
if s.OnStart {
s.rebalance(ctx)
}
})
2023-03-08 13:54:36 +00:00
s.session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
s.rebalance(ctx)
2022-03-23 15:52:59 +00:00
})
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()
_ = s.orderExecutorMap.GracefulCancel(ctx)
})
2023-03-08 13:54:36 +00:00
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-03-08 13:54:36 +00:00
if err := s.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
}
2023-03-13 08:46:18 +00:00
submitOrders, err := s.generateSubmitOrders(ctx)
if err != nil {
log.WithError(err).Error("failed to generate submit orders")
return
}
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 {
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-03-12 15:48:26 +00:00
createdOrders, err := s.orderExecutorMap.SubmitOrders(ctx, submitOrders...)
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-03-13 08:46:18 +00:00
func (s *Strategy) prices(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-03-08 13:54:36 +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-03-13 15:30:33 +00:00
m[currency] = ticker.Buy.Add(ticker.Sell).Div(fixedpoint.NewFromFloat(2.0))
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-03-13 08:46:18 +00:00
func (s *Strategy) balances() (types.BalanceMap, error) {
m := make(types.BalanceMap)
2023-03-08 13:54:36 +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-03-13 08:46:18 +00:00
func (s *Strategy) generateSubmitOrders(ctx context.Context) (submitOrders []types.SubmitOrder, err error) {
prices, err := s.prices(ctx)
if err != nil {
return nil, err
}
balances, err := s.balances()
if err != nil {
return nil, err
}
marketValues := prices.Mul(balanceToTotal(balances))
currentWeights := marketValues.Normalize()
2021-12-13 07:19:34 +00:00
for currency, targetWeight := range s.TargetWeights {
2022-10-13 10:16:11 +00:00
if currency == s.QuoteCurrency {
2021-12-12 09:19:27 +00:00
continue
}
2022-10-13 10:16:11 +00:00
symbol := currency + s.QuoteCurrency
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
2023-03-13 08:46:18 +00:00
maxAmount := s.adjustMaxAmountByBalance(side, currency, currentPrice, balances)
if maxAmount.Sign() > 0 {
quantity = bbgo.AdjustQuantityByMaxAmount(quantity, currentPrice, 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,
2023-03-02 07:56:25 +00:00
Type: s.OrderType,
2022-05-26 07:57:38 +00:00
Quantity: quantity,
Price: currentPrice,
2022-05-26 07:57:38 +00:00
}
2021-12-12 09:19:27 +00:00
2023-03-13 10:24:46 +00:00
if ok := s.checkMinimalOrderQuantity(order); ok {
submitOrders = append(submitOrders, order)
}
2021-12-12 09:19:27 +00:00
}
2023-03-13 08:46:18 +00:00
return submitOrders, err
2021-12-12 09:19:27 +00:00
}
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-10-13 10:16:11 +00:00
if currency == s.QuoteCurrency {
2022-03-23 15:52:59 +00:00
continue
}
2022-10-13 10:16:11 +00:00
symbols = append(symbols, currency+s.QuoteCurrency)
2022-03-23 15:52:59 +00:00
}
return symbols
}
2023-03-08 13:54:36 +00:00
func (s *Strategy) markets() ([]types.Market, error) {
markets := []types.Market{}
for _, symbol := range s.symbols() {
market, ok := s.session.Market(symbol)
if !ok {
return nil, fmt.Errorf("market %s not found", symbol)
}
markets = append(markets, market)
}
return markets, nil
}
2023-03-13 08:46:18 +00:00
func (s *Strategy) adjustMaxAmountByBalance(side types.SideType, currency string, currentPrice fixedpoint.Value, balances types.BalanceMap) fixedpoint.Value {
var maxAmount fixedpoint.Value
switch side {
case types.SideTypeBuy:
maxAmount = balances[s.QuoteCurrency].Available
case types.SideTypeSell:
maxAmount = balances[currency].Available.Mul(currentPrice)
default:
log.Errorf("unknown side type: %s", side)
return fixedpoint.Zero
}
if s.MaxAmount.Sign() > 0 {
maxAmount = fixedpoint.Min(s.MaxAmount, maxAmount)
}
return maxAmount
}
func (s *Strategy) checkMinimalOrderQuantity(order types.SubmitOrder) bool {
if order.Quantity.Compare(order.Market.MinQuantity) < 0 {
log.Infof("order quantity is too small: %f < %f", order.Quantity.Float64(), order.Market.MinQuantity.Float64())
return false
}
if order.Quantity.Mul(order.Price).Compare(order.Market.MinNotional) < 0 {
log.Infof("order min notional is too small: %f < %f", order.Quantity.Mul(order.Price).Float64(), order.Market.MinNotional.Float64())
return false
}
return true
}
func balanceToTotal(balances types.BalanceMap) types.ValueMap {
m := make(types.ValueMap)
for _, b := range balances {
m[b.Currency] = b.Total()
}
return m
}