From 3a7b3718382f796fca03484f3b78461c931a04b5 Mon Sep 17 00:00:00 2001 From: Hermes Date: Fri, 22 May 2026 10:19:24 +0000 Subject: [PATCH] fix: portfolio simulator pnl calculation and trade status --- agents/papert.py | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/agents/papert.py b/agents/papert.py index c4e9239..4345523 100644 --- a/agents/papert.py +++ b/agents/papert.py @@ -142,8 +142,16 @@ class Portfolio: fee = gross * fee_rate net_proceeds = gross - fee amount_usdt = gross - pnl = net_proceeds - (btc_to_sell * price) # simplified - pnl_pct = (pnl / (btc_to_sell * price)) * 100 if btc_to_sell > 0 else 0 + + # Calculate average entry price from OPEN BUYs + c.execute(f"SELECT entry_price, btc_amount FROM {self.tbl_trades} WHERE action='BUY' AND result IN ('PENDING', 'OPEN')") + buy_trades = c.fetchall() + total_cost = sum(t[0] * t[1] for t in buy_trades) + total_btc = sum(t[1] for t in buy_trades) + avg_entry = total_cost / total_btc if total_btc > 0 else price + + pnl = net_proceeds - (btc_to_sell * avg_entry) + pnl_pct = (pnl / (btc_to_sell * avg_entry)) * 100 if (btc_to_sell * avg_entry) > 0 else 0 new_balance = balance + net_proceeds new_btc_held = btc_held - btc_to_sell @@ -157,7 +165,7 @@ class Portfolio: else: exit_reason = f"signal_{self.strategy}" - result_str = f"🔴 SELL ({self.strategy}) | {btc_to_sell:.6f} BTC @ ${price:,.0f} | Net: ${net_proceeds:.2f} | Fee: ${fee:.2f}" + result_str = f"🔴 SELL ({self.strategy}) | {btc_to_sell:.6f} BTC @ ${price:,.0f} | Net: ${net_proceeds:.2f} | PNL: ${pnl:.2f} | Fee: ${fee:.2f}" else: new_balance = balance new_btc_held = btc_held @@ -165,16 +173,22 @@ class Portfolio: # Record trade if it happened if action in ("BUY", "SELL") and (action == "BUY" or btc_held > 0): - is_win = pnl > 0 if action == "SELL" and btc_held > 0 else None + is_win = pnl > 0 if action == "SELL" else None + trade_result = "WIN" if is_win is True else ("LOSS" if is_win is False else "OPEN") + c.execute(f""" INSERT INTO {self.tbl_trades} (date,action,entry_price,amount_usdt,btc_amount,exit_price,pnl_usdt,pnl_pct,stop_loss,take_profit,fee_usdt,exit_reason,result,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) """, (today, action, price, amount_usdt, btc_amount, price if action == "SELL" else 0, pnl, pnl_pct, stop_loss, take_profit, - amount_usdt * fee_rate if action == "BUY" else amount_usdt * fee_rate if action == "SELL" else 0, - exit_reason, "WIN" if is_win else ("LOSS" if is_win is False else "PENDING"), + amount_usdt * fee_rate, + exit_reason, trade_result, now)) + + if action == "SELL": + # Mark previous OPEN buys as CLOSED + c.execute(f"UPDATE {self.tbl_trades} SET result='CLOSED' WHERE action='BUY' AND result IN ('PENDING', 'OPEN')") # Update daily stats c.execute(f"UPDATE {self.tbl_portfolio} SET balance=?, btc_held=?, total_trades=total_trades+1 WHERE date=?",