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