From 319e8d746fd8c6b99c90f79eb31afa88ac2355d2 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sat, 31 Aug 2024 16:46:39 +0200 Subject: [PATCH] feat: use proper trade objects for liquidation calc --- freqtrade/exchange/binance.py | 12 ++++++------ tests/exchange/test_binance.py | 14 +++++++++++++- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/freqtrade/exchange/binance.py b/freqtrade/exchange/binance.py index 3ef6be74c..a837068d1 100644 --- a/freqtrade/exchange/binance.py +++ b/freqtrade/exchange/binance.py @@ -212,20 +212,20 @@ class Binance(Exchange): if self.margin_mode == MarginMode.CROSS: mm_ex_1: float = 0.0 upnl_ex_1: float = 0.0 - pairs = [trade["pair"] for trade in open_trades] + pairs = [trade.pair for trade in open_trades] funding_rates = self.fetch_funding_rates(pairs) for trade in open_trades: - if trade["pair"] == pair: + if trade.pair == pair: # Only "other" trades are considered continue - mark_price = funding_rates[trade["pair"]]["markPrice"] + mark_price = funding_rates[trade.pair]["markPrice"] mm_ratio1, maint_amnt1 = self.get_maintenance_ratio_and_amt( - trade["pair"], trade["stake_amount"] + trade.pair, trade.stake_amount ) - maint_margin = trade["amount"] * mark_price * mm_ratio1 - maint_amnt1 + maint_margin = trade.amount * mark_price * mm_ratio1 - maint_amnt1 mm_ex_1 += maint_margin - upnl_ex_1 += trade["amount"] * mark_price - trade["amount"] * trade["open_rate"] + upnl_ex_1 += trade.amount * mark_price - trade.amount * trade.open_rate cross_vars = upnl_ex_1 - mm_ex_1 side_1 = -1 if is_short else 1 diff --git a/tests/exchange/test_binance.py b/tests/exchange/test_binance.py index 63c7dfa00..956f0b850 100644 --- a/tests/exchange/test_binance.py +++ b/tests/exchange/test_binance.py @@ -7,6 +7,7 @@ import pytest from freqtrade.enums import CandleType, MarginMode, TradingMode from freqtrade.exceptions import DependencyException, InvalidOrderException, OperationalException +from freqtrade.persistence.trade_model import Trade from tests.conftest import EXMS, get_mock_coro, get_patched_exchange, log_has_re from tests.exchange.test_exchange import ccxt_exceptionhandlers @@ -313,6 +314,17 @@ def test_liquidation_price_binance( exchange.get_maintenance_ratio_and_amt = get_maint_ratio exchange.fetch_funding_rates = fetch_funding_rates + open_trade_objects = [ + Trade( + pair=t["pair"], + open_rate=t["open_rate"], + amount=t["amount"], + stake_amount=t["stake_amount"], + fee_open=0, + ) + for t in open_trades + ] + assert ( pytest.approx( round( @@ -324,7 +336,7 @@ def test_liquidation_price_binance( amount=amount, stake_amount=open_rate * amount, leverage=5, - open_trades=open_trades, + open_trades=open_trade_objects, ), 2, )