From f864974efee093a67331d1532bb2e71420791e72 Mon Sep 17 00:00:00 2001 From: c9s Date: Sun, 1 Sep 2024 00:58:50 +0800 Subject: [PATCH] xmaker: improve hedge account credit calculation --- pkg/strategy/xmaker/strategy.go | 49 ++++++++++++++++++++++++--------- 1 file changed, 36 insertions(+), 13 deletions(-) diff --git a/pkg/strategy/xmaker/strategy.go b/pkg/strategy/xmaker/strategy.go index dfd23a0..ae5be1a 100644 --- a/pkg/strategy/xmaker/strategy.go +++ b/pkg/strategy/xmaker/strategy.go @@ -503,6 +503,10 @@ func (s *Strategy) updateQuote(ctx context.Context) { !hedgeAccount.MarginLevel.IsZero() { if hedgeAccount.MarginLevel.Compare(s.MinMarginLevel) < 0 { + s.logger.Infof("hedge account margin level %s is less then the min margin level %s, calculating the borrowed positions", + hedgeAccount.MarginLevel.String(), + s.MinMarginLevel.String()) + if quote, ok := hedgeAccount.Balance(s.sourceMarket.QuoteCurrency); ok { quoteDebt := quote.Debt() if quoteDebt.Sign() > 0 { @@ -517,22 +521,41 @@ func (s *Strategy) updateQuote(ctx context.Context) { } } } else { - // credit buffer - creditBufferRatio := fixedpoint.NewFromFloat(1.2) - if quote, ok := hedgeAccount.Balance(s.sourceMarket.QuoteCurrency); ok { - netQuote := quote.Net() - if netQuote.Sign() > 0 { - hedgeQuota.QuoteAsset.Add(netQuote.Mul(creditBufferRatio)) - } - } + s.logger.Infof("hedge account margin level %s is greater than the min margin level %s, calculating the net value", + hedgeAccount.MarginLevel.String(), + s.MinMarginLevel.String()) - if base, ok := hedgeAccount.Balance(s.sourceMarket.BaseCurrency); ok { - netBase := base.Net() - if netBase.Sign() > 0 { - hedgeQuota.BaseAsset.Add(netBase.Mul(creditBufferRatio)) + netValueInUsd, calcErr := s.accountValueCalculator.NetValue(ctx) + if calcErr != nil { + s.logger.WithError(calcErr).Errorf("unable to calculate the net value") + } else { + // calculate credit buffer + s.logger.Infof("hedge account net value in usd: %f", netValueInUsd.Float64()) + + if quote, ok := hedgeAccount.Balance(s.sourceMarket.QuoteCurrency); ok { + debt := quote.Debt() + quota := netValueInUsd.Sub(debt) + + s.logger.Infof("hedge account quote balance: %s, debt: %s, quota: %s", + quote.String(), + debt.String(), + quota.String()) + + hedgeQuota.QuoteAsset.Add(quota) + } + + if base, ok := hedgeAccount.Balance(s.sourceMarket.BaseCurrency); ok { + debt := base.Debt() + quota := netValueInUsd.Div(bestAsk.Price).Sub(debt) + + s.logger.Infof("hedge account base balance: %s, debt: %s, quota: %s", + base.String(), + debt.String(), + quota.String()) + + hedgeQuota.BaseAsset.Add(quota) } } - // netValueInUsd, err := s.accountValueCalculator.NetValue(ctx) } } else {