Files
auto-stock/backend/monitor_trading.sh
shuim de7921d270 fix: CRITICAL/HIGH 버그 30건 수정 + 전체 코드 주석 추가 + 중복 정리
## CRITICAL 수정 (20건)
- day_trading: global 선언 누락, loss_tracker 연동, ban 체크 추가
- trade_executor: BUY 체결가 order_price로 수정, remaining_pct 누적 계산
- risk_validator: get_current_price dict 파싱, MAX_POSITION_SIZE 동기화, DB 세션 누수
- risk_management/recommendations: date.today() → KST 변환
- mdd_manager: Lock 밖 executed_key 참조 수정
- correlation_filter: output → output2 키 수정
- portfolio: 해외 종목 USD/KRW 환율 적용 분리
- Sharpe Ratio 거래빈도 기반 연간화
- telegram_notifier: send_message() 공개 래퍼 추가
- position_manager: 앱 재시작 시 DB 포지션 복원
- swing exit_service: remaining_pct 조건 범위 수정
- run_backtest: original_qty 기반 remaining_pct 계산
- us_market_schedule: 2027년 미국 공휴일 추가
- Login.tsx: res.ok 검증 추가
- mean_reversion_strategy: RSI 로그 하드코딩 수정

## HIGH 수정 (10건)
- db_worker: DLQ 파일 백업 메커니즘 추가
- korea_investment_api: 만료 토큰 임의 연장 제거
- market_data: chart_cache 최대 100개 + TTL 만료
- main.py: rate_limit_store 1시간 미접근 IP 정리
- recommendations: fire-and-forget try/except 추가
- swing/scheduler: DB 세션 3개 분리
- Dashboard: wsMessages 전체 순회
- Layout: /health 엔드포인트 + 30초 폴링
- ml_ensemble: POST /train require_api_key 추가
- day_trading: record_trade_result_safe() 전환

## 코드 정리
- 프론트엔드: isUsStock, formatTime 공통 유틸 추출
- 백엔드: dead code 제거, 중복 import 통합
- MCP: JSON 파싱 헬퍼 추출 (~60줄 감소)
- 전체 ~100개 파일 한국어 주석 추가
- 테스트 13건 코드 기준 수정 (468 passed)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 16:05:41 +09:00

93 lines
4.4 KiB
Bash
Executable File

#!/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 "══════════════════════════════════════════════════════"