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
|
|
|
|
|
2022-06-16 08:30:55 +00:00
|
|
|
Interval types.Interval `json:"interval"`
|
2022-10-13 10:16:11 +00:00
|
|
|
QuoteCurrency string `json:"quoteCurrency"`
|
2022-06-16 08:30:55 +00:00
|
|
|
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"`
|
2022-06-16 08:30:55 +00:00
|
|
|
DryRun bool `json:"dryRun"`
|
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
|
2022-04-07 08:00:30 +00:00
|
|
|
}
|
|
|
|
|
2023-03-06 12:33:14 +00:00
|
|
|
func (s *Strategy) Defaults() error {
|
|
|
|
if s.OrderType == "" {
|
|
|
|
s.OrderType = types.OrderTypeLimitMaker
|
|
|
|
}
|
2023-03-06 13:37:03 +00:00
|
|
|
return nil
|
2023-03-06 12:33:14 +00:00
|
|
|
}
|
|
|
|
|
2022-04-07 08:00:30 +00:00
|
|
|
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")
|
|
|
|
}
|
|
|
|
|
2022-06-15 18:52:52 +00:00
|
|
|
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())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if s.Threshold.Sign() < 0 {
|
2021-12-21 17:50:27 +00:00
|
|
|
return fmt.Errorf("threshold should not less than 0")
|
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
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-12 15:48:26 +00:00
|
|
|
s.PositionMap = NewPositionMap(markets)
|
2023-03-08 13:54:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if s.ProfitStatsMap == nil {
|
2023-03-12 15:48:26 +00:00
|
|
|
s.ProfitStatsMap = NewProfitStatsMap(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)
|
|
|
|
|
|
|
|
s.session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
|
|
|
|
s.rebalance(ctx)
|
2022-03-23 15:52:59 +00:00
|
|
|
})
|
2022-06-15 18:52:52 +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) {
|
2022-06-15 18:52:52 +00:00
|
|
|
// 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 {
|
2022-06-15 18:52:52 +00:00
|
|
|
log.WithError(err).Errorf("failed to cancel orders")
|
2021-12-12 09:19:27 +00:00
|
|
|
}
|
|
|
|
|
2023-03-08 13:54:36 +00:00
|
|
|
submitOrders := s.generateSubmitOrders(ctx)
|
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
|
|
|
|
}
|
|
|
|
|
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-08 13:54:36 +00:00
|
|
|
func (s *Strategy) prices(ctx context.Context) types.ValueMap {
|
2022-06-16 08:30:55 +00:00
|
|
|
m := make(types.ValueMap)
|
2022-06-15 18:52:52 +00:00
|
|
|
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
|
|
|
|
}
|
2022-06-15 18:52:52 +00:00
|
|
|
|
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 {
|
|
|
|
log.WithError(err).Error("failed to query tickers")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
m[currency] = ticker.Last
|
|
|
|
}
|
2022-06-15 18:52:52 +00:00
|
|
|
return m
|
2021-12-12 09:19:27 +00:00
|
|
|
}
|
|
|
|
|
2023-03-08 13:54:36 +00:00
|
|
|
func (s *Strategy) quantities() types.ValueMap {
|
2022-06-16 08:30:55 +00:00
|
|
|
m := make(types.ValueMap)
|
2022-06-15 18:52:52 +00:00
|
|
|
|
2023-03-08 13:54:36 +00:00
|
|
|
balances := s.session.GetAccount().Balances()
|
2022-06-15 18:52:52 +00:00
|
|
|
for currency := range s.TargetWeights {
|
|
|
|
m[currency] = balances[currency].Total()
|
2021-12-12 09:19:27 +00:00
|
|
|
}
|
2022-06-15 18:52:52 +00:00
|
|
|
|
|
|
|
return m
|
2021-12-12 09:19:27 +00:00
|
|
|
}
|
|
|
|
|
2023-03-08 13:54:36 +00:00
|
|
|
func (s *Strategy) generateSubmitOrders(ctx context.Context) (submitOrders []types.SubmitOrder) {
|
|
|
|
prices := s.prices(ctx)
|
|
|
|
marketValues := prices.Mul(s.quantities())
|
2022-04-07 08:00:30 +00:00
|
|
|
currentWeights := marketValues.Normalize()
|
2021-12-13 07:19:34 +00:00
|
|
|
|
2022-06-15 18:52:52 +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-04-07 08:00:30 +00:00
|
|
|
|
2022-10-13 10:16:11 +00:00
|
|
|
symbol := currency + s.QuoteCurrency
|
2022-06-15 18:52:52 +00:00
|
|
|
currentWeight := currentWeights[currency]
|
|
|
|
currentPrice := prices[currency]
|
2022-04-07 08:00:30 +00:00
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
log.Infof("%s price: %v, current weight: %v, target weight: %v",
|
2021-12-21 17:41:48 +00:00
|
|
|
symbol,
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
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
|
2022-06-15 18:52:52 +00:00
|
|
|
weightDifference := targetWeight.Sub(currentWeight)
|
|
|
|
if weightDifference.Abs().Compare(s.Threshold) < 0 {
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
log.Infof("%s weight distance |%v - %v| = |%v| less than the threshold: %v",
|
2021-12-21 18:04:44 +00:00
|
|
|
symbol,
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
currentWeight,
|
|
|
|
targetWeight,
|
|
|
|
weightDifference,
|
|
|
|
s.Threshold)
|
2021-12-12 09:19:27 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2022-06-15 18:52:52 +00:00
|
|
|
quantity := weightDifference.Mul(marketValues.Sum()).Div(currentPrice)
|
2021-12-12 09:19:27 +00:00
|
|
|
|
|
|
|
side := types.SideTypeBuy
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
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
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if s.MaxAmount.Sign() > 0 {
|
2022-06-15 18:52:52 +00:00
|
|
|
quantity = bbgo.AdjustQuantityByMaxAmount(quantity, currentPrice, s.MaxAmount)
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
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(),
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
currentPrice,
|
|
|
|
s.MaxAmount)
|
2021-12-20 15:27:03 +00:00
|
|
|
}
|
2022-06-15 18:52:52 +00:00
|
|
|
|
2022-04-07 08:00:30 +00:00
|
|
|
log.Debugf("symbol: %v, quantity: %v", symbol, quantity)
|
2022-06-15 18:52:52 +00:00
|
|
|
|
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,
|
2022-06-15 18:52:52 +00:00
|
|
|
Price: currentPrice,
|
2022-05-26 07:57:38 +00:00
|
|
|
}
|
2021-12-12 09:19:27 +00:00
|
|
|
|
|
|
|
submitOrders = append(submitOrders, order)
|
|
|
|
}
|
2022-06-15 18:52:52 +00:00
|
|
|
|
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) {
|
2022-06-15 18:52:52 +00:00
|
|
|
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
|
|
|
|
}
|