diff --git a/src/pages/journal/trading_journal_page.py b/src/pages/journal/trading_journal_page.py index e003ec0..fa67603 100644 --- a/src/pages/journal/trading_journal_page.py +++ b/src/pages/journal/trading_journal_page.py @@ -87,29 +87,34 @@ def plot_trade_history(trades): cumulative_pnl = 0 for trade in trades: - # Only include trades with both entry and exit prices (closed trades) - if (not trade.get('exit_price') or not trade.get('entry_price') or - not isinstance(trade['exit_price'], (int, float)) or - not isinstance(trade['entry_price'], (int, float))): - continue - try: - # Convert prices to float if they're strings and are numeric - exit_price = float(trade['exit_price']) - entry_price = float(trade['entry_price']) - shares = float(trade['shares']) - - # Calculate realized P/L for this trade - trade_pnl = (exit_price - entry_price) * shares - cumulative_pnl += trade_pnl - - # Use exit_date for realized P/L - if trade.get('exit_date'): - dates.append(trade['exit_date']) - pnl.append(cumulative_pnl) + # For sell orders + if trade.get('direction') == 'sell' or trade.get('exit_price'): + price = float(trade.get('exit_price') or trade.get('entry_price')) + date = trade.get('exit_date') or trade.get('entry_date') + shares = float(trade['shares']) - except (ValueError, TypeError): - # Skip trades where conversion to float fails + # Find matching buy order to calculate P/L + position_id = trade['position_id'] + buy_trades = [t for t in trades + if t['position_id'] == position_id and + (t.get('direction', '').lower() != 'sell' and not t.get('exit_price'))] + + if buy_trades: + # Use average entry price from buy trades + total_cost = sum(float(t['entry_price']) * float(t['shares']) for t in buy_trades) + total_shares = sum(float(t['shares']) for t in buy_trades) + avg_entry_price = total_cost / total_shares if total_shares > 0 else 0 + + # Calculate P/L + trade_pnl = (price - avg_entry_price) * shares + cumulative_pnl += trade_pnl + + dates.append(date) + pnl.append(cumulative_pnl) + + except (ValueError, TypeError) as e: + print(f"Error processing trade for P/L chart: {e}") continue if not dates: