DB삭제 되는부분 처리
This commit is contained in:
174
CLAUDE.md
174
CLAUDE.md
@@ -1,135 +1,135 @@
|
|||||||
# Auto Stock Trading System — Claude Context Guide
|
# 자동 주식 매매 시스템 — Claude 컨텍스트 가이드
|
||||||
|
|
||||||
> **Core Directive**: This document defines the strategies, rules, and architecture for the system. All code modifications and analysis must strictly adhere to these guidelines.
|
> **핵심 지침 (Core Directive)**: 이 문서는 시스템의 전략, 규칙 및 아키텍처를 정의합니다. 모든 코드 수정 및 분석은 이 가이드라인을 엄격하게 준수해야 합니다.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Project Overview
|
## 1. 프로젝트 개요
|
||||||
|
|
||||||
### 1.1 Tech Stack
|
### 1.1 기술 스택
|
||||||
- **Backend**: Python 3.11, FastAPI, SQLAlchemy (Async), PostgreSQL, Redis
|
- **백엔드**: Python 3.11, FastAPI, SQLAlchemy (Async), PostgreSQL, Redis
|
||||||
- **Frontend**: React, TypeScript, Vite, Recharts
|
- **프론트엔드**: React, TypeScript, Vite, Recharts
|
||||||
- **Infrastructure**: Docker Compose, Nginx
|
- **인프라**: Docker Compose, Nginx
|
||||||
- **AI Layer**: Claude 3.5 Sonnet / Gemini 2.0 Flash (Switch via `.env`)
|
- **AI 계층**: Claude 3.5 Sonnet / Gemini 2.0 Flash (`.env`에서 전환)
|
||||||
- **Integration**: KIS REST/WebSocket API, MCP Server (stdio)
|
- **연동 (Integration)**: 한국투자증권(KIS) REST/WebSocket API, MCP Server (stdio)
|
||||||
|
|
||||||
### 1.2 Environment (`.env`)
|
### 1.2 환경 변수 (`.env`)
|
||||||
- **AI_PROVIDER**: `gemini` or `claude`
|
- **AI_PROVIDER**: `gemini` 또는 `claude`
|
||||||
- **KIS_MODE**: `virtual` or `real`
|
- **KIS_MODE**: `virtual` (모의투자) 또는 `real` (실전투자)
|
||||||
- **TOKEN_SAVE_MODE**: `true` (Compresses JSON, limits chart data to 30 days)
|
- **TOKEN_SAVE_MODE**: `true` (JSON을 압축하고, 차트 데이터를 30일치로 제한함)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Directory Structure
|
## 2. 디렉토리 구조
|
||||||
|
|
||||||
### 2.1 Backend (`backend/app/`)
|
### 2.1 백엔드 (`backend/app/`)
|
||||||
- **API**: `api/endpoints/` (Market data, Portfolio, Trades)
|
- **API**: `api/endpoints/` (시장 데이터, 포트폴리오, 매매)
|
||||||
- **Core**: `market_data.py`, `portfolio.py`, `trades.py`
|
- **코어 (Core)**: `market_data.py`, `portfolio.py`, `trades.py`
|
||||||
|
|
||||||
### 2.2 Services (`backend/app/services/`)
|
### 2.2 서비스 (`backend/app/services/`)
|
||||||
- **Strategies**: `mean_reversion_strategy.py` (v2), `short_term_strategy.py`, `kosdaq_scanner.py`
|
- **전략 (Strategies)**: `mean_reversion_strategy.py` (v2), `short_term_strategy.py`, `kosdaq_scanner.py`
|
||||||
- **Analysis**: `feature_engineering.py`, `ml_ensemble.py`, `tensorflow_predictor.py`
|
- **분석 (Analysis)**: `feature_engineering.py`, `ml_ensemble.py`, `tensorflow_predictor.py`
|
||||||
- **Risk & Utils**: `risk_management.py`, `loss_tracker.py`, `mdd_manager.py`
|
- **리스크 및 유틸 (Risk & Utils)**: `risk_management.py`, `loss_tracker.py`, `mdd_manager.py`
|
||||||
- **Architecture**: `db_worker.py` (Async DB Writer)
|
- **아키텍처 (Architecture)**: `db_worker.py` (비동기 DB 처리 워커)
|
||||||
|
|
||||||
### 2.3 MCP (`mcp-server/`)
|
### 2.3 MCP (`mcp-server/`)
|
||||||
- `stdio_server.py`, `auto_trade_claude.py`, `trade_monitor.py`
|
- `stdio_server.py`, `auto_trade_claude.py`, `trade_monitor.py`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Architecture Principles (Critical)
|
## 3. 아키텍처 원칙 (필수 준수 사항)
|
||||||
|
|
||||||
### 3.1 Separation of Concerns
|
### 3.1 관심사 분리 (Separation of Concerns)
|
||||||
- **Real-time Layer**: Handles API callbacks, Websocket broadcasts, and memory caching. **Zero DB I/O allowed.**
|
- **실시간 계층 (Real-time Layer)**: API 콜백, 웹소켓 브로드캐스트 및 메모리 캐싱을 처리합니다. **DB I/O(데이터베이스 입출력)는 절대 허용되지 않습니다.**
|
||||||
- **Persistence Layer**: Handles DB INSERT/UPDATE operations via background workers.
|
- **영속성 계층 (Persistence Layer)**: 백그라운드 워커를 통해 DB INSERT/UPDATE 작업을 처리합니다.
|
||||||
|
|
||||||
### 3.2 Async DB Worker Rule
|
### 3.2 비동기 DB 워커 규칙
|
||||||
- **Direct DB Access Ban**: Never call `AsyncSessionLocal()` or `commit()` inside API callbacks or real-time schedulers.
|
- **직접적인 DB 접근 금지**: API 콜백이나 실시간 스케줄러 내부에서 `AsyncSessionLocal()` 또는 `commit()`을 절대 호출하지 마십시오.
|
||||||
- **Queue Usage**: All data persistence (Trade history, Analysis results) must be sent to `db_task_queue` in `db_worker.py`.
|
- **큐(Queue) 사용**: 모든 데이터 저장(매매 내역, 분석 결과 등)은 `db_worker.py`의 `db_task_queue`로 보내야 합니다.
|
||||||
- **Worker**: The background worker processes the queue and handles safe DB transactions sequentially.
|
- **워커 (Worker)**: 백그라운드 워커가 큐를 처리하고 안전한 DB 트랜잭션을 순차적으로 수행합니다.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Coding Guidelines
|
## 4. 코딩 가이드라인
|
||||||
|
|
||||||
### 4.1 Stability
|
### 4.1 안정성
|
||||||
- **No Breaking Changes**: Never alter existing function/class signatures.
|
- **기존 코드 파괴 금지 (No Breaking Changes)**: 기존 함수나 클래스의 시그니처를 절대 변경하지 마십시오.
|
||||||
- **Versioning**: Use `_v2`, `_v3` suffixes for new strategy implementations.
|
- **버전 관리**: 새로운 전략 구현 시 `_v2`, `_v3` 등의 접미사를 사용하십시오.
|
||||||
|
|
||||||
### 4.2 Optimization
|
### 4.2 최적화
|
||||||
- **JSON Handling**: Always use `core.json_helpers._dumps()` instead of `json.dumps`.
|
- **JSON 처리**: `json.dumps` 대신 항상 `core.json_helpers._dumps()`를 사용하십시오.
|
||||||
- **Prompt Engineering**: Minimize tokens, use compact formats.
|
- **프롬프트 엔지니어링**: 토큰 사용을 최소화하고 컴팩트한 포맷을 사용하십시오.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. Risk Management Rules
|
## 5. 리스크 관리 규칙
|
||||||
|
|
||||||
### 5.1 Position Sizing
|
### 5.1 포지션 사이징 (Position Sizing)
|
||||||
- **Max Allocation**: 3-4% of total capital per stock.
|
- **최대 비중**: 종목당 총 자본의 3~4%.
|
||||||
- **Max Count**: 20-25 stocks max.
|
- **최대 보유 종목 수**: 20~25개 종목.
|
||||||
- **Leverage**: Max 20% of total capital for Inverse/Leveraged ETFs.
|
- **레버리지**: 인버스/레버리지 ETF의 경우 총 자본의 최대 20%로 제한.
|
||||||
|
|
||||||
### 5.2 Stop Loss (SL) & Take Profit (TP)
|
### 5.2 손절(SL) 및 익절(TP)
|
||||||
- **SL Base**: -6% (Stable), -10% (Volatile).
|
- **기본 손절 (SL Base)**: -6% (안정적 종목), -10% (변동성 종목).
|
||||||
- **SL ATR**: `Entry Price - (2.5 * ATR)`. (Priority over base SL)
|
- **ATR 손절**: `진입가 - (2.5 * ATR)`. (기본 손절보다 우선 적용)
|
||||||
- **TP**: Sell 50% at +2R profit.
|
- **익절 (TP)**: +2R 수익(리스크 대비 2배 수익) 도달 시 50% 분할 매도.
|
||||||
- **Trailing Stop**: `High - (1.5 * ATR)` for remaining 50%.
|
- **트레일링 스탑 (Trailing Stop)**: 나머지 50% 물량에 대해 `고점 - (1.5 * ATR)` 적용.
|
||||||
|
|
||||||
### 5.3 MDD Control
|
### 5.3 MDD(최대 낙폭) 관리
|
||||||
- **MDD -10%**: Stop new entries. Reduce position sizes by 30%. **Stop Short-term Strategy.**
|
- **MDD -10%**: 신규 진입을 중단합니다. 포지션 규모를 30% 축소합니다. **단기 매매 전략(Short-term Strategy)을 중단합니다.**
|
||||||
- **MDD -20%**: Force reduce all positions by 50%. Liquidate leveraged assets first.
|
- **MDD -20%**: 모든 포지션을 강제로 50% 축소합니다. 레버리지 자산부터 우선 청산합니다.
|
||||||
|
|
||||||
### 5.4 Filters
|
### 5.4 필터 (Filters)
|
||||||
- **Price**: > 5,000 KRW (Korea), > $4 (US). (Exceptions: ETFs, REITs)
|
- **가격**: 5,000원 초과 (국내), $4 초과 (미국). (예외: ETF, 리츠)
|
||||||
- **Correlation**: Max 3 stocks per sector. Reject entry if correlation > 0.7 with portfolio.
|
- **상관관계 (Correlation)**: 섹터당 최대 3종목. 기존 포트폴리오와의 상관계수가 0.7을 초과하면 진입을 거부합니다.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 6. Strategy A: RSI + Bollinger Mean Reversion v2
|
## 6. 전략 A: RSI + 볼린저 밴드 평균 회귀 v2
|
||||||
|
|
||||||
### 6.1 Market Regime (Daily)
|
### 6.1 시장 국면 (일봉 기준)
|
||||||
- **BULL**: KOSPI200 > MA200 AND MA200 Slope > 0.
|
- **상승장 (BULL)**: 코스피200 > 200일 이동평균선(MA200) AND MA200 기울기 > 0.
|
||||||
- **BEAR**: KOSPI200 < MA200 AND MA200 Slope < 0.
|
- **하락장 (BEAR)**: 코스피200 < 200일 이동평균선(MA200) AND MA200 기울기 < 0.
|
||||||
- **SIDEWAYS**: ADX < 20 OR Slope ≈ 0. **(Ignore all signals)**
|
- **횡보장 (SIDEWAYS)**: ADX < 20 OR 기울기 ≈ 0. **(이 국면에서는 모든 진입 신호를 무시합니다)**
|
||||||
|
|
||||||
### 6.2 Entry Conditions
|
### 6.2 진입 조건
|
||||||
- **Bull Market**: RSI(14) < 25, Price within BB Lower (-3% to +1.5%), Vol > 20MA.
|
- **상승장**: RSI(14) < 25, 가격이 볼린저 밴드(BB) 하단 부근 (-3% ~ +1.5%), 거래량 > 20일 평균 거래량(20MA).
|
||||||
- **Bear Market**: RSI(14) < 30, Price < BB Lower, Vol > 1.5x 20MA, Reversal candle required.
|
- **하락장**: RSI(14) < 30, 가격 < 볼린저 밴드 하단, 거래량 > 1.5배 * 20MA, 반전 캔들(Reversal candle) 필수.
|
||||||
- **Pre-emptive**: Daily RSI < 40 AND 60m RSI < 30 AND Breakout MA5.
|
- **선제 진입 (Pre-emptive)**: 일봉 RSI < 40 AND 60분봉 RSI < 30 AND 5일 이동평균선(MA5) 상향 돌파.
|
||||||
|
|
||||||
### 6.3 Exit Conditions
|
### 6.3 청산 조건
|
||||||
- **Partial**: RSI > 50 OR Price > BB Mid OR Profit > 2*ATR.
|
- **부분 매도**: RSI > 50 OR 가격 > 볼린저 밴드 중앙선 OR 수익 > 2*ATR.
|
||||||
- **Full**: RSI > 65 OR Price > BB Upper (99%) OR Trailing Stop.
|
- **전량 매도**: RSI > 65 OR 가격 > 볼린저 밴드 상단 (99%) OR 트레일링 스탑 도달.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 7. Strategy B: Aggressive Growth
|
## 7. 전략 B: 공격적 성장 (Aggressive Growth)
|
||||||
|
|
||||||
### 7.1 Kosdaq Scanner (Swing)
|
### 7.1 코스닥 스캐너 (스윙 매매)
|
||||||
- **Scope**: All Kosdaq (~1600).
|
- **대상 (Scope)**: 코스닥 전 종목 (약 1,600개).
|
||||||
- **Filter**: Price > 5,000 KRW, Top 20% Volume.
|
- **필터 (Filter)**: 가격 > 5,000원, 거래량 상위 20%.
|
||||||
- **Score**: `0.5*RSI + 0.3*BB + 0.2*Vol`. Pick Top 20.
|
- **점수 (Score)**: `0.5*RSI + 0.3*BB + 0.2*Vol`. 상위 20개 종목 선정.
|
||||||
- **Allocation**: 25% of Capital.
|
- **자산 배분 (Allocation)**: 전체 자본의 25%.
|
||||||
|
|
||||||
### 7.2 Short-term Strategy (15m)
|
### 7.2 단기 전략 (15분봉)
|
||||||
- **Target**: Stocks with Daily RSI < 40.
|
- **타겟 (Target)**: 일봉 RSI < 40 인 종목.
|
||||||
- **Entry**: 15m RSI < 30, Price near BB Lower, MA5 Breakout, Vol > 1.3x.
|
- **진입 (Entry)**: 15분봉 RSI < 30, 가격이 볼린저 밴드 하단 부근, 5MA 상향 돌파, 거래량 > 1.3배 증가.
|
||||||
- **Exit**: 15m RSI > 55 OR Profit > 1.5 * ATR(15m).
|
- **청산 (Exit)**: 15분봉 RSI > 55 OR 수익 > 1.5 * ATR(15분봉).
|
||||||
- **Allocation**: Max 25% of Capital. **Disable if MDD < -10%.**
|
- **자산 배분 (Allocation)**: 전체 자본의 최대 25%. **MDD가 -10% 미만이면 비활성화합니다.**
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 8. Instructions for Claude
|
## 8. Claude에 대한 지침
|
||||||
|
|
||||||
### 8.1 Critical Checkpoints
|
### 8.1 주요 점검 사항 (Critical Checkpoints)
|
||||||
1. **Architecture**: Ensure all DB writes use `db_worker.py`.
|
1. **아키텍처**: 모든 DB 쓰기 작업이 `db_worker.py`를 사용하는지 확인하십시오.
|
||||||
2. **Safety**: Always apply Risk Rules (Section 5) to every trade.
|
2. **안전성 (Safety)**: 모든 매매에 리스크 규칙(섹션 5)을 항상 적용하십시오.
|
||||||
3. **Regime**: Do NOT suggest entries in SIDEWAYS regime.
|
3. **시장 국면 (Regime)**: 횡보장(SIDEWAYS) 국면에서는 진입을 제안하지 마십시오.
|
||||||
4. **Testing**: No real trading without Backtest + Walk-forward validation.
|
4. **테스트**: 백테스트 및 전진 분석(Walk-forward validation) 없이는 실전 투자를 하지 마십시오.
|
||||||
|
|
||||||
### 8.2 Response Format
|
### 8.2 응답 형식 (Response Format)
|
||||||
- Use `_dumps()` for JSON.
|
- JSON 출력 시 `_dumps()`를 사용하십시오.
|
||||||
- Create new files for new features.
|
- 새로운 기능 개발 시 새 파일을 생성하십시오.
|
||||||
- Do not modify existing signatures.
|
- 기존 시그니처를 수정하지 마십시오.
|
||||||
|
|
||||||
*Last updated: 2026-02-24*
|
*마지막 업데이트: 2026-02-24*
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ echo -e "${GREEN}✓ Docker 확인 완료${NC}"
|
|||||||
|
|
||||||
# 기존 컨테이너 중지 및 제거
|
# 기존 컨테이너 중지 및 제거
|
||||||
echo -e "${YELLOW}기존 컨테이너 중지 중...${NC}"
|
echo -e "${YELLOW}기존 컨테이너 중지 중...${NC}"
|
||||||
docker-compose down -v 2>/dev/null || docker compose down -v 2>/dev/null || true
|
docker-compose down 2>/dev/null || docker compose down 2>/dev/null || true
|
||||||
|
|
||||||
# Docker 이미지 빌드
|
# Docker 이미지 빌드
|
||||||
echo -e "${YELLOW}Docker 이미지 빌드 중...${NC}"
|
echo -e "${YELLOW}Docker 이미지 빌드 중...${NC}"
|
||||||
|
|||||||
Reference in New Issue
Block a user