File size: 4,562 Bytes
5f20dc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
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
    }