From b564e69f825f867fedf7246577eb01fee32e443d Mon Sep 17 00:00:00 2001 From: Andy Cheng Date: Fri, 5 Aug 2022 15:59:20 +0800 Subject: [PATCH] strategy/supertrend: add CalculateQuoteQuantity() --- pkg/risk/account_value.go | 28 ++++++++++++++++++++++++++++ pkg/strategy/supertrend/strategy.go | 4 ---- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/pkg/risk/account_value.go b/pkg/risk/account_value.go index 22a485a82..519d122da 100644 --- a/pkg/risk/account_value.go +++ b/pkg/risk/account_value.go @@ -12,6 +12,8 @@ import ( "github.com/c9s/bbgo/pkg/types" ) +var log = logrus.WithField("risk", "AccountValueCalculator") + var one = fixedpoint.One var maxLeverage = fixedpoint.NewFromInt(10) @@ -268,3 +270,29 @@ func CalculateBaseQuantity(session *bbgo.ExchangeSession, market types.Market, p return quantity, fmt.Errorf("quantity is zero, can not submit sell order, please check your settings") } + +func CalculateQuoteQuantity(session *bbgo.ExchangeSession, ctx context.Context, quoteCurrency string, leverage fixedpoint.Value) (fixedpoint.Value, error) { + // default leverage guard + if leverage.IsZero() { + leverage = fixedpoint.NewFromInt(3) + } + + quoteBalance, _ := session.Account.Balance(quoteCurrency) + accountValue := NewAccountValueCalculator(session, quoteCurrency) + + usingLeverage := session.Margin || session.IsolatedMargin || session.Futures || session.IsolatedFutures + if !usingLeverage { + // For spot, we simply return the quote balance + return quoteBalance.Available, nil + } + + // using leverage -- starts from here + availableQuote, err := accountValue.AvailableQuote(ctx) + if err != nil { + log.WithError(err).Errorf("can not update available quote") + return fixedpoint.Zero, err + } + logrus.Infof("calculating available leveraged quote quantity: account available quote = %+v", availableQuote) + + return availableQuote, nil +} diff --git a/pkg/strategy/supertrend/strategy.go b/pkg/strategy/supertrend/strategy.go index b6580a8fd..d876c7e45 100644 --- a/pkg/strategy/supertrend/strategy.go +++ b/pkg/strategy/supertrend/strategy.go @@ -119,10 +119,6 @@ func (s *Strategy) Validate() error { return errors.New("interval is required") } - if s.Leverage <= 0.0 { - return errors.New("leverage is required") - } - return nil }