Skip to content

Commit

Permalink
refactor(portfolio): improve daily balance calculation for futures an…
Browse files Browse the repository at this point in the history
…d 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.
  • Loading branch information
saleh-mir committed Dec 19, 2024
1 parent 85d77cf commit e203383
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
20 changes: 12 additions & 8 deletions jesse/modes/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)}')

Expand Down
10 changes: 8 additions & 2 deletions jesse/strategies/Strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit e203383

Please sign in to comment.