From e203383085aa09b0311de37aab8ac6327515263d Mon Sep 17 00:00:00 2001 From: Saleh Mir Date: Thu, 19 Dec 2024 19:07:50 +0330 Subject: [PATCH] refactor(portfolio): improve daily balance calculation for futures and spot trading - Updated the save_daily_portfolio_balance function to streamline balance calculations for futures and spot trading. - For futures, wallet balance and PNLs are now summed correctly, while for spot trading, the portfolio value is retrieved from the first available strategy. - Enhanced clarity and maintainability of the code by restructuring balance accumulation logic. - Added handling for active entry orders in the Strategy class to ensure accurate total position values during spot trading. --- jesse/modes/utils.py | 20 ++++++++++++-------- jesse/strategies/Strategy.py | 10 ++++++++-- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/jesse/modes/utils.py b/jesse/modes/utils.py index 152fa3d14..9c87c4772 100644 --- a/jesse/modes/utils.py +++ b/jesse/modes/utils.py @@ -26,18 +26,22 @@ def save_daily_portfolio_balance(is_initial=False) -> None: e, = store.exchanges.storage.values() except ValueError: raise ValueError('Multiple exchange support is not supported at the moment') + if e.type == 'futures': - total_balances += e.assets[jh.app_currency()] - - for key, pos in store.positions.storage.items(): - if pos.exchange_type == 'futures' and pos.is_open: - total_balances += pos.pnl - elif pos.exchange_type == 'spot': - total_balances += pos.strategy.portfolio_value + # For futures, add wallet balance and sum of all PNLs + total_balances = e.assets[jh.app_currency()] + for key, pos in store.positions.storage.items(): + if pos.is_open: + total_balances += pos.pnl + else: + # For spot, just get portfolio_value from any strategy (they all share the same wallet) + # Get the first strategy we can find + for key, pos in store.positions.storage.items(): + total_balances = pos.strategy.portfolio_value + break store.app.daily_balance.append(total_balances) - # TEMP: disable storing in database for now if not jh.is_livetrading(): logger.info(f'Saved daily portfolio balance: {round(total_balances, 2)}') diff --git a/jesse/strategies/Strategy.py b/jesse/strategies/Strategy.py index be7b8cc40..4ee7ca6e6 100644 --- a/jesse/strategies/Strategy.py +++ b/jesse/strategies/Strategy.py @@ -1339,12 +1339,18 @@ def portfolio_value(self) -> float: # in spot mode, self.balance does not include open order's value, so: if self.is_spot_trading: + # Add value of active entry orders + entry_orders_value = 0 for o in self.entry_orders: if o.is_active: - total_position_values += o.value + entry_orders_value += o.value + # Add value of all positions + positions_value = 0 for key, p in self.all_positions.items(): - total_position_values += p.value + positions_value += p.value + + total_position_values = entry_orders_value + positions_value # in futures mode, it's simpler: elif self.is_futures_trading: