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"
|
2022-04-07 08:00:30 +00:00
|
|
|
"math"
|
|
|
|
"sort"
|
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
|
|
|
|
|
2022-03-23 15:52:59 +00:00
|
|
|
Interval types.Interval `json:"interval"`
|
2021-12-20 15:27:03 +00:00
|
|
|
BaseCurrency string `json:"baseCurrency"`
|
|
|
|
TargetWeights map[string]fixedpoint.Value `json:"targetWeights"`
|
|
|
|
Threshold fixedpoint.Value `json:"threshold"`
|
|
|
|
Verbose bool `json:"verbose"`
|
2022-03-23 15:52:59 +00:00
|
|
|
DryRun bool `json:"dryRun"`
|
2021-12-20 15:27:03 +00:00
|
|
|
// max amount to buy or sell per order
|
|
|
|
MaxAmount fixedpoint.Value `json:"maxAmount"`
|
2022-04-07 08:00:30 +00:00
|
|
|
|
|
|
|
currencies []string
|
2022-05-26 07:57:38 +00:00
|
|
|
|
2022-06-15 15:34:57 +00:00
|
|
|
activeOrderBook *bbgo.ActiveOrderBook
|
2022-04-07 08:00:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) Initialize() error {
|
|
|
|
for currency := range s.TargetWeights {
|
|
|
|
s.currencies = append(s.currencies, currency)
|
|
|
|
}
|
|
|
|
|
|
|
|
sort.Strings(s.currencies)
|
|
|
|
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")
|
|
|
|
}
|
|
|
|
|
|
|
|
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-06-15 13:34:42 +00:00
|
|
|
for _, symbol := range s.symbols() {
|
2022-05-19 01:48:36 +00:00
|
|
|
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
|
|
|
|
|
|
|
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
|
2022-06-15 15:34:57 +00:00
|
|
|
s.activeOrderBook = bbgo.NewActiveOrderBook("")
|
|
|
|
s.activeOrderBook.BindStream(session.UserDataStream)
|
2022-05-26 07:57:38 +00:00
|
|
|
|
2022-03-23 15:52:59 +00:00
|
|
|
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
|
2022-05-26 07:57:38 +00:00
|
|
|
if kline.Symbol != s.currencies[0]+s.BaseCurrency {
|
|
|
|
return
|
|
|
|
}
|
2022-03-23 15:52:59 +00:00
|
|
|
s.rebalance(ctx, orderExecutor, session)
|
|
|
|
})
|
2021-12-12 09:19:27 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-12-13 07:19:34 +00:00
|
|
|
func (s *Strategy) rebalance(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) {
|
2022-06-15 15:34:57 +00:00
|
|
|
err := orderExecutor.CancelOrders(ctx, s.activeOrderBook.Orders()...)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("failed to cancel orders")
|
|
|
|
return
|
2022-05-26 07:57:38 +00:00
|
|
|
}
|
|
|
|
|
2022-06-15 13:34:42 +00:00
|
|
|
prices, err := s.prices(ctx, session)
|
2021-12-12 09:19:27 +00:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-06-15 15:07:27 +00:00
|
|
|
marketValues := prices.Mul(s.quantities(session))
|
2021-12-12 09:19:27 +00:00
|
|
|
|
2021-12-13 07:19:34 +00:00
|
|
|
orders := s.generateSubmitOrders(prices, marketValues)
|
2022-03-23 15:52:59 +00:00
|
|
|
for _, order := range orders {
|
|
|
|
log.Infof("generated submit order: %s", order.String())
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.DryRun {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-05-26 07:57:38 +00:00
|
|
|
createdOrders, err := orderExecutor.SubmitOrders(ctx, orders...)
|
2021-12-12 09:19:27 +00:00
|
|
|
if err != nil {
|
2021-12-21 17:41:48 +00:00
|
|
|
log.WithError(err).Error("submit order error")
|
2021-12-12 09:19:27 +00:00
|
|
|
return
|
|
|
|
}
|
2022-05-26 07:57:38 +00:00
|
|
|
|
2022-06-15 15:34:57 +00:00
|
|
|
s.activeOrderBook.Add(createdOrders...)
|
2021-12-12 09:19:27 +00:00
|
|
|
}
|
|
|
|
|
2022-06-15 13:34:42 +00:00
|
|
|
func (s *Strategy) prices(ctx context.Context, session *bbgo.ExchangeSession) (prices types.Float64Slice, err error) {
|
2022-06-15 15:07:27 +00:00
|
|
|
tickers, err := session.Exchange.QueryTickers(ctx, s.symbols()...)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-04-07 08:00:30 +00:00
|
|
|
for _, currency := range s.currencies {
|
2021-12-12 09:19:27 +00:00
|
|
|
if currency == s.BaseCurrency {
|
2022-04-07 08:00:30 +00:00
|
|
|
prices = append(prices, 1.0)
|
2021-12-12 09:19:27 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
symbol := currency + s.BaseCurrency
|
2022-06-15 15:07:27 +00:00
|
|
|
prices = append(prices, tickers[symbol].Last.Float64())
|
2021-12-12 09:19:27 +00:00
|
|
|
}
|
|
|
|
return prices, nil
|
|
|
|
}
|
|
|
|
|
2022-06-15 15:07:27 +00:00
|
|
|
func (s *Strategy) quantities(session *bbgo.ExchangeSession) (quantities types.Float64Slice) {
|
|
|
|
balances := session.GetAccount().Balances()
|
2022-04-07 08:00:30 +00:00
|
|
|
for _, currency := range s.currencies {
|
2022-06-15 15:07:27 +00:00
|
|
|
quantities = append(quantities, balances[currency].Total().Float64())
|
2021-12-12 09:19:27 +00:00
|
|
|
}
|
2021-12-13 07:19:34 +00:00
|
|
|
return quantities
|
2021-12-12 09:19:27 +00:00
|
|
|
}
|
|
|
|
|
2022-04-07 08:00:30 +00:00
|
|
|
func (s *Strategy) generateSubmitOrders(prices, marketValues types.Float64Slice) (submitOrders []types.SubmitOrder) {
|
|
|
|
currentWeights := marketValues.Normalize()
|
2021-12-13 07:19:34 +00:00
|
|
|
|
2022-04-07 08:00:30 +00:00
|
|
|
for i, currency := range s.currencies {
|
2021-12-12 09:19:27 +00:00
|
|
|
if currency == s.BaseCurrency {
|
|
|
|
continue
|
|
|
|
}
|
2022-04-07 08:00:30 +00:00
|
|
|
|
2021-12-12 09:19:27 +00:00
|
|
|
symbol := currency + s.BaseCurrency
|
2022-04-07 08:00:30 +00:00
|
|
|
currentWeight := currentWeights[i]
|
|
|
|
currentPrice := prices[i]
|
|
|
|
targetWeight := s.TargetWeights[currency].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
|
|
|
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-04-07 08:00:30 +00:00
|
|
|
weightDifference := targetWeight - currentWeight
|
|
|
|
if math.Abs(weightDifference) < s.Threshold.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
|
|
|
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 15:07:27 +00:00
|
|
|
quantity := fixedpoint.NewFromFloat((weightDifference * marketValues.Sum()) / 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-04-07 08:00:30 +00:00
|
|
|
quantity = bbgo.AdjustQuantityByMaxAmount(quantity, fixedpoint.NewFromFloat(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-04-07 08:00:30 +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: fixedpoint.NewFromFloat(currentPrice),
|
|
|
|
}
|
2021-12-12 09:19:27 +00:00
|
|
|
|
|
|
|
submitOrders = append(submitOrders, order)
|
|
|
|
}
|
|
|
|
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-04-07 08:00:30 +00:00
|
|
|
for _, currency := range s.currencies {
|
2022-03-23 15:52:59 +00:00
|
|
|
if currency == s.BaseCurrency {
|
|
|
|
continue
|
|
|
|
}
|
2022-04-07 08:00:30 +00:00
|
|
|
symbols = append(symbols, currency+s.BaseCurrency)
|
2022-03-23 15:52:59 +00:00
|
|
|
}
|
|
|
|
return symbols
|
|
|
|
}
|