bbgo_origin/pkg/strategy/rebalance/strategy.go

234 lines
5.7 KiB
Go
Raw Normal View History

2021-12-12 09:19:27 +00:00
package kline
import (
"context"
2021-12-21 17:50:27 +00:00
"fmt"
2021-12-12 09:19:27 +00:00
"time"
"github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
"github.com/c9s/bbgo/pkg/util"
)
const ID = "rebalance"
var log = logrus.WithField("strategy", ID)
func init() {
bbgo.RegisterStrategy(ID, &Strategy{})
}
2021-12-13 07:19:34 +00:00
func Sum(m map[string]fixedpoint.Value) fixedpoint.Value {
sum := fixedpoint.NewFromFloat(0.0)
for _, v := range m {
sum = sum.Add(v)
2021-12-12 09:19:27 +00:00
}
2021-12-13 07:19:34 +00:00
return sum
2021-12-12 09:19:27 +00:00
}
2021-12-13 07:19:34 +00:00
func Normalize(m map[string]fixedpoint.Value) map[string]fixedpoint.Value {
sum := Sum(m)
if sum.Float64() == 1.0 {
return m
2021-12-12 09:19:27 +00:00
}
2021-12-13 07:19:34 +00:00
normalized := make(map[string]fixedpoint.Value)
for k, v := range m {
normalized[k] = v.Div(sum)
}
return normalized
2021-12-12 09:19:27 +00:00
}
2021-12-13 07:19:34 +00:00
func ElementwiseProduct(m1, m2 map[string]fixedpoint.Value) map[string]fixedpoint.Value {
m := make(map[string]fixedpoint.Value)
for k, v := range m1 {
m[k] = v.Mul(m2[k])
2021-12-12 09:19:27 +00:00
}
2021-12-13 07:19:34 +00:00
return m
2021-12-12 09:19:27 +00:00
}
type Strategy struct {
Notifiability *bbgo.Notifiability
2021-12-20 15:27:03 +00:00
Interval types.Duration `json:"interval"`
BaseCurrency string `json:"baseCurrency"`
TargetWeights map[string]fixedpoint.Value `json:"targetWeights"`
Threshold fixedpoint.Value `json:"threshold"`
IgnoreLocked bool `json:"ignoreLocked"`
Verbose bool `json:"verbose"`
// max amount to buy or sell per order
MaxAmount fixedpoint.Value `json:"maxAmount"`
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 s.Interval == 0 {
return fmt.Errorf("interval shoud not be 0")
}
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())
}
}
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
}
2021-12-12 09:19:27 +00:00
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {}
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
2021-12-20 15:27:03 +00:00
s.TargetWeights = Normalize(s.TargetWeights)
2021-12-12 09:19:27 +00:00
go func() {
ticker := time.NewTicker(util.MillisecondsJitter(s.Interval.Duration(), 1000))
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
2021-12-13 07:19:34 +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) {
prices, err := s.getPrices(ctx, session)
2021-12-12 09:19:27 +00:00
if err != nil {
return
}
balances := session.Account.Balances()
2021-12-13 07:19:34 +00:00
quantities := s.getQuantities(balances)
marketValues := ElementwiseProduct(prices, quantities)
2021-12-12 09:19:27 +00:00
2021-12-13 07:19:34 +00:00
orders := s.generateSubmitOrders(prices, marketValues)
2021-12-12 09:19:27 +00:00
_, err = orderExecutor.SubmitOrders(ctx, orders...)
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
}
}
2021-12-13 07:19:34 +00:00
func (s *Strategy) getPrices(ctx context.Context, session *bbgo.ExchangeSession) (map[string]fixedpoint.Value, error) {
2021-12-12 09:19:27 +00:00
prices := make(map[string]fixedpoint.Value)
2021-12-20 15:27:03 +00:00
for currency := range s.TargetWeights {
2021-12-12 09:19:27 +00:00
if currency == s.BaseCurrency {
prices[currency] = fixedpoint.One
2021-12-12 09:19:27 +00:00
continue
}
symbol := currency + s.BaseCurrency
ticker, err := session.Exchange.QueryTicker(ctx, symbol)
if err != nil {
s.Notifiability.Notify("query ticker error: %s", err.Error())
log.WithError(err).Error("query ticker error")
return prices, err
}
prices[currency] = ticker.Last
2021-12-12 09:19:27 +00:00
}
return prices, nil
}
2021-12-13 07:19:34 +00:00
func (s *Strategy) getQuantities(balances types.BalanceMap) map[string]fixedpoint.Value {
quantities := make(map[string]fixedpoint.Value)
2021-12-20 15:27:03 +00:00
for currency := range s.TargetWeights {
2021-12-12 09:19:27 +00:00
if s.IgnoreLocked {
2021-12-13 07:19:34 +00:00
quantities[currency] = balances[currency].Total()
} else {
quantities[currency] = balances[currency].Available
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
}
2021-12-13 07:19:34 +00:00
func (s *Strategy) generateSubmitOrders(prices, marketValues map[string]fixedpoint.Value) []types.SubmitOrder {
2021-12-12 09:19:27 +00:00
var submitOrders []types.SubmitOrder
2021-12-13 07:19:34 +00:00
currentWeights := Normalize(marketValues)
totalValue := Sum(marketValues)
log.Infof("total value: %f", totalValue.Float64())
2021-12-20 15:27:03 +00:00
for currency, targetWeight := range s.TargetWeights {
2021-12-12 09:19:27 +00:00
if currency == s.BaseCurrency {
continue
}
symbol := currency + s.BaseCurrency
2021-12-20 15:27:03 +00:00
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
}
2021-12-20 15:27:03 +00:00
quantity := weightDifference.Mul(totalValue).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 {
2021-12-20 15:27:03 +00:00
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
}
2021-12-12 09:19:27 +00:00
order := types.SubmitOrder{
Symbol: symbol,
Side: side,
Type: types.OrderTypeMarket,
Quantity: quantity}
2021-12-12 09:19:27 +00:00
submitOrders = append(submitOrders, order)
}
return submitOrders
}