File size: 5,945 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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import os
import json
from datetime import datetime
from config import SETTINGS_FILE

POSITIONS_FILE = 'portfolio_positions.json'

# ---------- Load/Save ----------
from modules.storage import load_json, save_json

def _load_positions():
    """Load positions from storage"""
    data = load_json(POSITIONS_FILE, default=None)
    if data is None:
        return {"batches": []}
    return data

def _save_positions(data):
    """Save positions to storage"""
    return save_json(POSITIONS_FILE, data)

# ---------- Create Batch ----------
def create_batch(batch_name, coins, take_profit_pct, stop_loss_pct):
    """
    Create a new position batch.
    
    Args:
        batch_name: Descriptive name (e.g., "Short Scan 2026-09-11")
        coins: List of dicts with {symbol, coin_id, quantity, avg_price, usdt_spent}
        take_profit_pct: Portfolio TP target (e.g., 5 for +5%)
        stop_loss_pct: Portfolio SL target (e.g., 3 for -3%)
    """
    data = _load_positions()
    
    total_cost = sum(c['usdt_spent'] for c in coins)
    
    batch = {
        "id": f"batch_{int(datetime.now().timestamp())}",
        "name": batch_name,
        "created_at": datetime.now().isoformat(),
        "take_profit_pct": take_profit_pct,
        "stop_loss_pct": stop_loss_pct,
        "total_cost": round(total_cost, 2),
        "status": "open",
        "coins": coins,
        "close_reason": None,
        "closed_at": None,
        "final_value": None,
        "final_pnl": None
    }
    
    data["batches"].append(batch)
    _save_positions(data)
    print(f"✅ Created batch: {batch_name} (${total_cost:.2f})")
    return batch

# ---------- Get Batches ----------
def get_all_batches():
    """Get all position batches"""
    return _load_positions().get("batches", [])

def get_open_batches():
    """Get only open batches"""
    return [b for b in get_all_batches() if b.get("status") == "open"]

def get_batch(batch_id):
    """Get a specific batch"""
    for b in get_all_batches():
        if b["id"] == batch_id:
            return b
    return None

# ---------- Update Batch Prices ----------
def update_batch_prices(batch_id, current_prices):
    """Update a batch with current prices and calculate P&L"""
    data = _load_positions()
    for batch in data["batches"]:
        if batch["id"] != batch_id:
            continue
        
        current_value = 0
        for coin in batch["coins"]:
            symbol = coin["symbol"]
            price = current_prices.get(symbol, coin["avg_price"])
            value = coin["quantity"] * price
            coin["current_price"] = price
            coin["current_value"] = round(value, 2)
            coin["unrealized_pnl"] = round(value - coin["usdt_spent"], 2)
            coin["pnl_pct"] = round(((value / coin["usdt_spent"]) - 1) * 100, 2) if coin["usdt_spent"] > 0 else 0
            current_value += value
        
        batch["current_value"] = round(current_value, 2)
        batch["unrealized_pnl"] = round(current_value - batch["total_cost"], 2)
        batch["pnl_pct"] = round(((current_value / batch["total_cost"]) - 1) * 100, 2) if batch["total_cost"] > 0 else 0
        batch["last_updated"] = datetime.now().isoformat()
        
        # Check TP/SL triggers
        trigger = None
        if batch["pnl_pct"] >= batch["take_profit_pct"]:
            trigger = "take_profit"
        elif batch["pnl_pct"] <= -batch["stop_loss_pct"]:
            trigger = "stop_loss"
        
        batch["pending_trigger"] = trigger
        
        _save_positions(data)
        return batch
    return None

# ---------- Trigger Check ----------
def check_triggers(current_prices):
    """Check all open batches for TP/SL triggers"""
    triggered = []
    for batch in get_open_batches():
        updated = update_batch_prices(batch["id"], current_prices)
        if updated and updated.get("pending_trigger"):
            triggered.append(updated)
    return triggered

# ---------- Close Batch ----------
def close_batch(batch_id, reason, final_value, results=None):
    """Mark a batch as closed"""
    data = _load_positions()
    for batch in data["batches"]:
        if batch["id"] != batch_id:
            continue
        batch["status"] = "closed"
        batch["close_reason"] = reason
        batch["closed_at"] = datetime.now().isoformat()
        batch["final_value"] = round(final_value, 2)
        batch["final_pnl"] = round(final_value - batch["total_cost"], 2)
        batch["final_pnl_pct"] = round(((final_value / batch["total_cost"]) - 1) * 100, 2) if batch["total_cost"] > 0 else 0
        if results:
            batch["close_results"] = results
        batch["pending_trigger"] = None
        _save_positions(data)
        print(f"✅ Closed batch {batch_id}: {reason} ({batch['final_pnl']:+.2f})")
        return batch
    return None

# ---------- Portfolio Summary ----------
def get_portfolio_summary(current_prices):
    """Get overall portfolio stats across all open batches"""
    open_batches = get_open_batches()
    
    total_cost = 0
    total_value = 0
    
    for batch in open_batches:
        updated = update_batch_prices(batch["id"], current_prices)
        if updated:
            total_cost += updated["total_cost"]
            total_value += updated["current_value"]
    
    total_pnl = total_value - total_cost
    total_pnl_pct = ((total_value / total_cost) - 1) * 100 if total_cost > 0 else 0
    
    return {
        "total_batches": len(open_batches),
        "total_cost": round(total_cost, 2),
        "total_value": round(total_value, 2),
        "total_pnl": round(total_pnl, 2),
        "total_pnl_pct": round(total_pnl_pct, 2),
        "batches": open_batches
    }

# ---------- Delete Batch ----------
def delete_batch(batch_id):
    """Remove a batch entirely"""
    data = _load_positions()
    data["batches"] = [b for b in data["batches"] if b["id"] != batch_id]
    _save_positions(data)
    return True