import os import csv from datetime import datetime from config import JOURNAL_FILE # ---------- Initialize Journal ---------- def init_journal(): """Create the journal CSV if it doesn't exist""" if not os.path.isfile(JOURNAL_FILE): with open(JOURNAL_FILE, 'w', newline='') as f: writer = csv.writer(f) writer.writerow([ 'symbol', 'entry_price', 'exit_price', 'quantity', 'entry_date', 'exit_date', 'pnl', 'status' ]) print(f"✅ Created journal at {JOURNAL_FILE}") # ---------- Get Journal Path ---------- def get_journal_path(): """Get the journal file path (initializing if needed)""" if not os.path.isfile(JOURNAL_FILE): init_journal() return JOURNAL_FILE # ---------- Add Trade Entry ---------- def add_trade(symbol, entry_price, quantity, status="OPEN"): """Add a new trade entry to the journal""" init_journal() try: with open(JOURNAL_FILE, 'a', newline='') as f: writer = csv.writer(f) writer.writerow([ symbol, entry_price, "", quantity, datetime.now().isoformat(), "", "", status ]) print(f"✅ Added trade: {symbol} @ {entry_price} x {quantity}") return True except Exception as e: print(f"❌ Failed to add trade: {e}") return False # ---------- Close Trade Entry ---------- def close_trade(symbol, exit_price): """Close an open trade by updating exit price and calculating PnL""" init_journal() try: rows = [] closed = False with open(JOURNAL_FILE, 'r') as f: reader = csv.DictReader(f) for row in reader: if row['symbol'] == symbol and row['status'] == 'OPEN' and not closed: try: entry = float(row['entry_price']) qty = float(row['quantity']) pnl = (float(exit_price) - entry) * qty row['exit_price'] = exit_price row['exit_date'] = datetime.now().isoformat() row['pnl'] = round(pnl, 4) row['status'] = 'CLOSED' closed = True except (ValueError, TypeError) as e: print(f"⚠️ Error processing row: {e}") rows.append(row) if closed: with open(JOURNAL_FILE, 'w', newline='') as f: writer = csv.DictWriter(f, fieldnames=[ 'symbol', 'entry_price', 'exit_price', 'quantity', 'entry_date', 'exit_date', 'pnl', 'status' ]) writer.writeheader() writer.writerows(rows) print(f"✅ Closed trade: {symbol} @ {exit_price}") return True else: print(f"⚠️ No open trade found for {symbol}") return False except Exception as e: print(f"❌ Failed to close trade: {e}") return False # ---------- Read All Trades ---------- def get_all_trades(): """Read all trades from the journal""" init_journal() try: with open(JOURNAL_FILE, 'r') as f: reader = csv.DictReader(f) return list(reader) except Exception as e: print(f"❌ Failed to read journal: {e}") return [] # ---------- Get Open Trades ---------- def get_open_trades(): """Get only open trades""" return [t for t in get_all_trades() if t.get('status') == 'OPEN'] # ---------- Get Journal Stats ---------- def get_journal_stats(): """Calculate statistics from the journal""" trades = get_all_trades() closed = [t for t in trades if t.get('status') == 'CLOSED'] total_pnl = 0 wins = 0 losses = 0 for t in closed: try: pnl = float(t.get('pnl', 0)) total_pnl += pnl if pnl > 0: wins += 1 elif pnl < 0: losses += 1 except (ValueError, TypeError): pass return { "total_trades": len(trades), "open_trades": len(get_open_trades()), "closed_trades": len(closed), "total_pnl": round(total_pnl, 4), "wins": wins, "losses": losses, "win_rate": round((wins / len(closed)) * 100, 2) if closed else 0 }