From 097836d1930822a59abe990ea91e8f3dcde65b46 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 10 Dec 2024 20:49:43 +0100 Subject: [PATCH] feat: improve logic for liquidation price calc --- freqtrade/leverage/liquidation_price.py | 7 +++++-- freqtrade/wallets.py | 14 ++++++++++++++ tests/leverage/test_update_liquidation_price.py | 2 +- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/freqtrade/leverage/liquidation_price.py b/freqtrade/leverage/liquidation_price.py index aed8c9160..4b49e4551 100644 --- a/freqtrade/leverage/liquidation_price.py +++ b/freqtrade/leverage/liquidation_price.py @@ -27,9 +27,12 @@ def update_liquidation_prices( total_wallet_stake = 0.0 if dry_run: # Parameters only needed for cross margin - total_wallet_stake = wallets.get_total(stake_currency) + total_wallet_stake = wallets.get_collateral() - logger.info("Updating liquidation price for all open trades.") + logger.info( + "Updating liquidation price for all open trades. " + f"Collateral {total_wallet_stake} {stake_currency}." + ) open_trades = Trade.get_open_trades() for t in open_trades: # TODO: This should be done in a batch update diff --git a/freqtrade/wallets.py b/freqtrade/wallets.py index 4dcdb4ee4..5a239dadd 100644 --- a/freqtrade/wallets.py +++ b/freqtrade/wallets.py @@ -73,6 +73,18 @@ class Wallets: else: return 0 + def get_collateral(self) -> float: + """ + Get total collateral for liquidation price calculation. + """ + if self._config.get("margin_mode") == "cross": + # free includes all balances and, combined with position collateral, + # is used as "wallet balance". + return self.get_free(self._stake_currency) + sum( + pos.collateral for pos in self._positions.values() + ) + return self.get_total(self._stake_currency) + def get_owned(self, pair: str, base_currency: str) -> float: """ Get currently owned value. @@ -139,6 +151,8 @@ class Wallets: cross_margin = 0.0 if self._config.get("margin_mode") == "cross": # In cross-margin mode, the total balance is used as collateral. + # This is moved as "free" into the stake currency balance. + # strongly tied to the get_collateral() implementation. for curr, bal in self._start_cap.items(): if curr == self._stake_currency: continue diff --git a/tests/leverage/test_update_liquidation_price.py b/tests/leverage/test_update_liquidation_price.py index 1b25babd0..68c35509f 100644 --- a/tests/leverage/test_update_liquidation_price.py +++ b/tests/leverage/test_update_liquidation_price.py @@ -29,7 +29,7 @@ def test_update_liquidation_prices(mocker, margin_mode, dry_run): assert trade_mock.set_liquidation_price.call_count == 1 - assert wallets.get_total.call_count == ( + assert wallets.get_collateral.call_count == ( 0 if margin_mode == MarginMode.ISOLATED or not dry_run else 1 )