import sqlite3 import os import logging from datetime import datetime from typing import Optional, Dict, List logger = logging.getLogger('Database') class TradingDB: """Persistent storage for active trades and session history.""" def __init__(self, db_path: str = "trading_ops.db"): self.db_path = db_path self._init_db() def _get_connection(self): return sqlite3.connect(self.db_path) def _init_db(self): """Creates tables if they don't exist.""" with self._get_connection() as conn: cursor = conn.cursor() # Table for active positions (one per symbol) cursor.execute(''' CREATE TABLE IF NOT EXISTS active_positions ( symbol TEXT PRIMARY KEY, direction TEXT NOT NULL, entry_price REAL NOT NULL, qty INTEGER NOT NULL, sl_price REAL, tp_price REAL, sl_order_id TEXT, security_id TEXT, exchange_segment INTEGER, entry_time TEXT NOT NULL ) ''') # AUDIT FIX: Migration for existing DBs try: cursor.execute("ALTER TABLE active_positions ADD COLUMN sl_order_id TEXT") cursor.execute("ALTER TABLE active_positions ADD COLUMN security_id TEXT") cursor.execute("ALTER TABLE active_positions ADD COLUMN exchange_segment INTEGER") except sqlite3.OperationalError: pass # Columns already exist # Table for completed trade history cursor.execute(''' CREATE TABLE IF NOT EXISTS trade_history ( id INTEGER PRIMARY KEY AUTOINCREMENT, symbol TEXT NOT NULL, direction TEXT NOT NULL, entry_price REAL NOT NULL, exit_price REAL NOT NULL, pnl REAL NOT NULL, entry_time TEXT NOT NULL, exit_time TEXT NOT NULL ) ''') conn.commit() logger.info("Database initialized.") def save_position(self, symbol: str, direction: str, price: float, qty: int, sl: float = 0, tp: float = 0, sl_order_id: str = None, sec_id: str = None, segment: int = 2): """Records a new active position with broker-side order tracking.""" now = datetime.now().isoformat() with self._get_connection() as conn: cursor = conn.cursor() cursor.execute(''' INSERT OR REPLACE INTO active_positions (symbol, direction, entry_price, qty, sl_price, tp_price, sl_order_id, security_id, exchange_segment, entry_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ''', (symbol, direction, price, qty, sl, tp, sl_order_id, sec_id, segment, now)) conn.commit() logger.info(f"DB: Saved {direction} {symbol} @ {price:.2f} (SL Order: {sl_order_id})") def clear_position(self, symbol: str, exit_price: float): """Moves a position from active to history with correct rupee PnL.""" with self._get_connection() as conn: cursor = conn.cursor() # 1. Fetch data — include qty so we can compute real rupee PnL cursor.execute( "SELECT direction, entry_price, entry_time, qty FROM active_positions WHERE symbol = ?", (symbol,) ) row = cursor.fetchone() if not row: return 0.0 # No position found direction, entry_price, entry_time, qty = row # BUG FIX 4: PnL was raw index-point diff (e.g. 30 pts on NIFTY). # Actual P&L = points × lot_size × qty. # Previously ₹-572 was actually -572 points ≈ -₹28,600 on NIFTY. try: from config import SYMBOL_LOT_SIZES, BROKERAGE_PER_ORDER lot_size = SYMBOL_LOT_SIZES.get(symbol, 50) brokerage = BROKERAGE_PER_ORDER except ImportError: lot_size = 50 brokerage = 40 raw_pts = (exit_price - entry_price) if direction == "BUY" else (entry_price - exit_price) pnl = (raw_pts * (qty or 1) * lot_size) - brokerage exit_time = datetime.now().isoformat() # 2. Log to history cursor.execute(''' INSERT INTO trade_history (symbol, direction, entry_price, exit_price, pnl, entry_time, exit_time) VALUES (?, ?, ?, ?, ?, ?, ?) ''', (symbol, direction, entry_price, exit_price, pnl, entry_time, exit_time)) # 3. Delete active cursor.execute("DELETE FROM active_positions WHERE symbol = ?", (symbol,)) conn.commit() logger.info(f"DB: Closed {symbol} (PNL: {pnl:.2f}). Moved to history.") return pnl def get_all_active(self) -> List[Dict]: """Recovers state on startup.""" with self._get_connection() as conn: conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute("SELECT * FROM active_positions") rows = cursor.fetchall() return [dict(row) for row in rows]