#!/usr/bin/env python3 """화요일 장중 상태: DB 수집 + 전략별 매매 스냅샷.""" import sys from datetime import datetime sys.path.insert(0, "/home/hoon/kis_bot") from database import TradeDB TODAY = "2026-08-18" SINCE = f"{TODAY} 09:00:00" def cols(db, table): return [dict(r)["Field"] for r in db.conn.execute(f"SHOW COLUMNS FROM {table}").fetchall()] def main(): db = TradeDB() try: print(f"=== 화요일 상태 스냅샷 ({datetime.now():%Y-%m-%d %H:%M:%S}) ===\n") # --- ws_ticks --- wt_cols = cols(db, "ws_ticks") print(f"ws_ticks cols: {wt_cols[:8]}...") rows = db.conn.execute( """ SELECT source, COUNT(*) n, MIN(tick_time) tmin, MAX(tick_time) tmax, COUNT(DISTINCT code) codes FROM ws_ticks WHERE tick_time >= %s GROUP BY source ORDER BY n DESC """, (SINCE,), ).fetchall() print("\n--- ws_ticks 오늘 09:00~ (source별) ---") if not rows: print("(없음)") else: for r in rows: d = dict(r) print( f" {d['source']:12s} rows={d['n']:>8,} codes={d['codes']:>4} " f"{d['tmin']} ~ {d['tmax']}" ) rows5 = db.conn.execute( """ SELECT source, code, COUNT(*) n FROM ws_ticks WHERE tick_time >= %s GROUP BY source, code ORDER BY n DESC LIMIT 10 """, (SINCE,), ).fetchall() print("\n--- ws_ticks 종목 TOP10 ---") for r in rows5: d = dict(r) print(f" {d['source']:12s} {d['code']} {d['n']:,}") # --- ws_orderbook --- if "ws_orderbook" in [t for t in ["ws_orderbook"]]: ob_cols = cols(db, "ws_orderbook") print(f"\nws_orderbook cols sample: {ob_cols[:10]}") rows = db.conn.execute( """ SELECT source, COUNT(*) n, MIN(snap_time) tmin, MAX(snap_time) tmax, COUNT(DISTINCT code) codes FROM ws_orderbook WHERE snap_time >= %s GROUP BY source ORDER BY n DESC """, (SINCE,), ).fetchall() print("\n--- ws_orderbook 오늘 09:00~ ---") if not rows: print("(없음)") else: for r in rows: d = dict(r) print( f" {d['source']:16s} rows={d['n']:>7,} codes={d['codes']:>4} " f"{d['tmin']} ~ {d['tmax']}" ) # --- history --- if "target_candidates_history" in ["target_candidates_history"]: hcols = cols(db, "target_candidates_history") print(f"\ntarget_candidates_history event_time type: ", end="") for c in hcols: if c == "event_time": print("found") rows = db.conn.execute( """ SELECT strategy_id, COUNT(*) n, MIN(event_time) tmin, MAX(event_time) tmax FROM target_candidates_history WHERE event_time >= %s GROUP BY strategy_id ORDER BY n DESC """, (SINCE,), ).fetchall() print("\n--- target_candidates_history 오늘 ---") for r in rows: d = dict(r) print( f" {d['strategy_id']:12s} rows={d['n']:>5} " f"{d['tmin']} ~ {d['tmax']}" ) # --- ls_ws_candles if exists --- try: ccols = cols(db, "ls_ws_candles") rows = db.conn.execute( """ SELECT COUNT(*) n, COUNT(DISTINCT code) codes, MIN(candle_time) tmin, MAX(candle_time) tmax FROM ls_ws_candles WHERE candle_time >= %s """, (SINCE,), ).fetchone() d = dict(rows) print(f"\n--- ls_ws_candles 오늘: rows={d['n']:,} codes={d['codes']} {d['tmin']} ~ {d['tmax']} ---") except Exception as e: print(f"\n--- ls_ws_candles: skip ({e}) ---") # --- active_trades / trades today --- for tbl in ("active_trades", "trade_history"): try: tcols = cols(db, tbl) sid_col = "strategy_id" if "strategy_id" in tcols else None if not sid_col: continue time_col = None for cand in ("buy_time", "created_at", "updated_at", "entry_time"): if cand in tcols: time_col = cand break if tbl == "active_trades": rows = db.conn.execute( f"SELECT strategy_id, code, buy_price, buy_time, qty FROM {tbl} ORDER BY buy_time DESC" ).fetchall() print(f"\n--- {tbl} (현재 보유) ---") if not rows: print(" (없음)") for r in rows: d = dict(r) print( f" {d.get('strategy_id','?'):12s} {d.get('code','?')} " f"qty={d.get('qty')} buy={d.get('buy_price')} @ {d.get('buy_time')}" ) elif time_col: rows = db.conn.execute( f""" SELECT strategy_id, COUNT(*) n FROM {tbl} WHERE {time_col} >= %s GROUP BY strategy_id ORDER BY n DESC """, (SINCE,), ).fetchall() print(f"\n--- {tbl} 오늘 매매건 ({time_col}) ---") if not rows: print(" (없음)") for r in rows: d = dict(r) print(f" {d['strategy_id']:12s} n={d['n']}") except Exception as e: print(f"\n--- {tbl}: skip ({e}) ---") # recent orders if table exists for tbl in ("orders", "order_log"): try: ocols = cols(db, tbl) if "strategy_id" not in ocols: continue tcol = "order_time" if "order_time" in ocols else "created_at" rows = db.conn.execute( f""" SELECT strategy_id, side, code, status, {tcol} FROM {tbl} WHERE {tcol} >= %s ORDER BY {tcol} DESC LIMIT 30 """, (SINCE,), ).fetchall() print(f"\n--- {tbl} 최근 30건 ---") for r in rows: d = dict(r) print( f" {d.get('strategy_id','?'):10s} {d.get('side','?'):4s} " f"{d.get('code','?')} {d.get('status','?')} @ {d.get(tcol)}" ) break except Exception: pass finally: db.close() if __name__ == "__main__": main()