#!/bin/bash # 장중 매매 모니터링 스크립트 # 사용법: bash backend/monitor_trading.sh echo "══════════════════════════════════════════════════════" echo " Auto-Stock 장중 모니터링 ($(date '+%Y-%m-%d %H:%M:%S'))" echo "══════════════════════════════════════════════════════" # 1. 적응형 모드 echo "" echo "▶ 적응형 전략 모드" API_KEY=$(docker exec autostock-backend python3 -c "from app.core.config import settings; print(settings.SECRET_KEY)" 2>/dev/null) curl -s http://127.0.0.1:8000/api/v1/adaptive-strategy/status \ -H "X-API-Key: $API_KEY" 2>/dev/null | python3 -c " import json, sys d = json.load(sys.stdin) c = d.get('condition', {}) p = d.get('params', {}) print(f' 모드: {d.get(\"trading_mode\", \"?\")}'.upper()) print(f' ATR: {c.get(\"atr_percentile\", 0):.0f}% | 5일: {c.get(\"recent_5d_return\", 0):+.2f}%') print(f' 스윙: RSI<{p.get(\"rsi_entry\",0)} 포지션{p.get(\"position_size\",0)*100:.0f}%') print(f' 데이트레이딩: {\"ON\" if p.get(\"daytrading_enabled\") else \"OFF\"}') " 2>/dev/null # 2. 오늘 매매 echo "" echo "▶ 오늘 매매" docker exec autostock-backend python3 -c " import asyncio from datetime import datetime, timedelta async def run(): from app.core.database import AsyncSessionLocal from app.models.models import TradeHistory from sqlalchemy import select async with AsyncSessionLocal() as db: today = datetime.utcnow().replace(hour=0, minute=0, second=0) result = await db.execute( select(TradeHistory).where(TradeHistory.created_at >= today).order_by(TradeHistory.created_at.desc()) ) trades = result.scalars().all() buys = [t for t in trades if t.order_type == 'BUY' and t.status == 'COMPLETED'] sells = [t for t in trades if t.order_type == 'SELL' and t.status == 'COMPLETED'] pnl = sum(float(t.net_profit_loss or 0) for t in sells) wins = sum(1 for t in sells if float(t.net_profit_loss or 0) > 0) losses = sum(1 for t in sells if float(t.net_profit_loss or 0) <= 0) print(f' 매수 {len(buys)}건 | 매도 {len(sells)}건 | 손익 {pnl:+,.0f}원 ({wins}승 {losses}패)') print() for t in trades[:10]: kst = t.created_at + timedelta(hours=9) if t.created_at else None time_str = kst.strftime('%H:%M') if kst else '??:??' pnl_str = f'{float(t.net_profit_loss or 0):>+8,.0f}원' if t.order_type == 'SELL' else ' ' flag = '🟢' if t.order_type == 'BUY' else ('✅' if float(t.net_profit_loss or 0) > 0 else '❌') status = '' if t.status == 'COMPLETED' else f' [{t.status}]' print(f' {flag} {time_str} {t.order_type:4s} {(t.stock_name or t.stock_code):10s} {t.order_quantity:3d}주 {pnl_str}{status}') asyncio.run(run()) " 2>/dev/null # 3. 포트폴리오 echo "" echo "▶ 포트폴리오" docker exec autostock-backend python3 -c " import asyncio async def run(): from app.core.database import AsyncSessionLocal from app.models.models import Portfolio from sqlalchemy import select async with AsyncSessionLocal() as db: pf = await db.execute(select(Portfolio).where(Portfolio.quantity > 0)) holdings = pf.scalars().all() total_val = sum(float(h.current_price or 0) * h.quantity for h in holdings) total_pnl = sum(float(h.profit_loss or 0) for h in holdings) print(f' 보유 {len(holdings)}종목 | 평가 {total_val:,.0f}원 | 손익 {total_pnl:+,.0f}원') for h in sorted(holdings, key=lambda x: float(x.profit_loss_rate or 0), reverse=True): rate = float(h.profit_loss_rate or 0) flag = '🟢' if rate > 0 else '🔴' if rate < -2 else '🟡' print(f' {flag} {(h.stock_name or h.stock_code):10s} {h.quantity:3d}주 {float(h.current_price or 0):>10,.0f}원 ({rate:>+.2f}%)') asyncio.run(run()) " 2>/dev/null # 4. 최근 에러 echo "" echo "▶ 최근 경고/에러" docker logs autostock-backend --since 5m 2>&1 | grep -iE "ERROR|WARNING|❌|⚠️" | grep -v "sklearn\|LGBMClassifier\|feature names" | tail -5 echo "" echo "══════════════════════════════════════════════════════"