Merge pull request #387 from narumiruna/narumi/rebalance/validate

strategy: rebalance: validate parameters
This commit is contained in:
Yo-An Lin 2021-12-22 10:52:37 +08:00 committed by GitHub
commit b2ffcb7993
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 3 deletions

View File

@ -13,9 +13,9 @@ exchangeStrategies:
targetWeights:
BTC: 40%
ETH: 20%
MAX: 20%
USDT: 10%
TWD: 10%
MAX: 10%
USDT: 15%
TWD: 15%
threshold: 2%
# max amount to buy or sell per order
maxAmount: 10_000

View File

@ -2,6 +2,7 @@ package kline
import (
"context"
"fmt"
"time"
"github.com/sirupsen/logrus"
@ -67,6 +68,32 @@ func (s *Strategy) ID() string {
return ID
}
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 < 0 {
return fmt.Errorf("threshold should not less than 0")
}
if s.MaxAmount < 0 {
return fmt.Errorf("maxAmount shoud not less than 0")
}
return nil
}
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {}
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
@ -103,6 +130,7 @@ func (s *Strategy) rebalance(ctx context.Context, orderExecutor bbgo.OrderExecut
orders := s.generateSubmitOrders(prices, marketValues)
_, err = orderExecutor.SubmitOrders(ctx, orders...)
if err != nil {
log.WithError(err).Error("submit order error")
return
}
}
@ -156,11 +184,22 @@ func (s *Strategy) generateSubmitOrders(prices, marketValues map[string]fixedpoi
symbol := currency + s.BaseCurrency
currentWeight := currentWeights[currency]
currentPrice := prices[currency]
log.Infof("%s price: %f, current weight: %f, target weight: %f",
symbol,
currentPrice.Float64(),
currentWeight.Float64(),
targetWeight.Float64())
// 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() < s.Threshold {
log.Infof("%s weight distance |%f - %f| = |%f| less than the threshold: %f",
symbol,
currentWeight.Float64(),
targetWeight.Float64(),
weightDifference.Float64(),
s.Threshold.Float64())
continue
}