""" db/repository.py - DB 접근 레이어 """ import json from datetime import datetime from app.db.models import get_conn def save_trade(ticker, name, entry_time, entry_price, quantity, side, ai_boosted=False): with get_conn() as conn: conn.execute(""" INSERT INTO trades (date, ticker, name, entry_time, entry_price, quantity, side, ai_boosted) VALUES (?, ?, ?, ?, ?, ?, ?, ?) """, (datetime.now().strftime("%Y-%m-%d"), ticker, name, entry_time, entry_price, quantity, side, 1 if ai_boosted else 0)) def update_trade_exit(ticker, exit_time, exit_price, exit_reason, pnl, fee): with get_conn() as conn: conn.execute(""" UPDATE trades SET exit_time=?, exit_price=?, exit_reason=?, pnl=?, fee=? WHERE ticker=? AND exit_time IS NULL ORDER BY id DESC LIMIT 1 """, (exit_time, exit_price, exit_reason, pnl, fee, ticker)) def save_daily_summary(date, total, wins, losses, gross_pnl, fee, net_pnl, mdd, stopped): with get_conn() as conn: conn.execute(""" INSERT OR REPLACE INTO daily_summary VALUES (?,?,?,?,?,?,?,?,?) """, (date, total, wins, losses, gross_pnl, fee, net_pnl, mdd, stopped)) def save_ai_context(ctx: dict, tokens_used: int = 0, success: bool = True): with get_conn() as conn: conn.execute(""" INSERT OR REPLACE INTO ai_context_log (date, generated_at, trade_allowed, market_sentiment, sentiment_score, risk_level, hot_sectors, avoid_sectors, boosted_tickers, blacklist_tickers, position_size_mult, reason, claude_tokens_used, api_call_success) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) """, ( ctx.get("date"), ctx.get("generated_at"), 1 if ctx.get("trade_allowed") else 0, ctx.get("market_sentiment"), ctx.get("sentiment_score"), ctx.get("risk_level"), json.dumps(ctx.get("hot_sectors", []), ensure_ascii=False), json.dumps(ctx.get("avoid_sectors", []), ensure_ascii=False), json.dumps(ctx.get("boosted_tickers", []), ensure_ascii=False), json.dumps(ctx.get("blacklist_tickers", []), ensure_ascii=False), ctx.get("position_size_multiplier", 1.0), ctx.get("reason", ""), tokens_used, 1 if success else 0, )) def get_today_trades(date: str = None): date = date or datetime.now().strftime("%Y-%m-%d") with get_conn() as conn: rows = conn.execute( "SELECT * FROM trades WHERE date=?", (date,) ).fetchall() return rows def get_open_positions(): with get_conn() as conn: rows = conn.execute( "SELECT * FROM positions" ).fetchall() return rows