135 lines
4.9 KiB
Markdown
135 lines
4.9 KiB
Markdown
# Auto Stock Trading System — Claude Context Guide
|
|
|
|
> **Core Directive**: This document defines the strategies, rules, and architecture for the system. All code modifications and analysis must strictly adhere to these guidelines.
|
|
|
|
---
|
|
|
|
## 1. Project Overview
|
|
|
|
### 1.1 Tech Stack
|
|
- **Backend**: Python 3.11, FastAPI, SQLAlchemy (Async), PostgreSQL, Redis
|
|
- **Frontend**: React, TypeScript, Vite, Recharts
|
|
- **Infrastructure**: Docker Compose, Nginx
|
|
- **AI Layer**: Claude 3.5 Sonnet / Gemini 2.0 Flash (Switch via `.env`)
|
|
- **Integration**: KIS REST/WebSocket API, MCP Server (stdio)
|
|
|
|
### 1.2 Environment (`.env`)
|
|
- **AI_PROVIDER**: `gemini` or `claude`
|
|
- **KIS_MODE**: `virtual` or `real`
|
|
- **TOKEN_SAVE_MODE**: `true` (Compresses JSON, limits chart data to 30 days)
|
|
|
|
---
|
|
|
|
## 2. Directory Structure
|
|
|
|
### 2.1 Backend (`backend/app/`)
|
|
- **API**: `api/endpoints/` (Market data, Portfolio, Trades)
|
|
- **Core**: `market_data.py`, `portfolio.py`, `trades.py`
|
|
|
|
### 2.2 Services (`backend/app/services/`)
|
|
- **Strategies**: `mean_reversion_strategy.py` (v2), `short_term_strategy.py`, `kosdaq_scanner.py`
|
|
- **Analysis**: `feature_engineering.py`, `ml_ensemble.py`, `tensorflow_predictor.py`
|
|
- **Risk & Utils**: `risk_management.py`, `loss_tracker.py`, `mdd_manager.py`
|
|
- **Architecture**: `db_worker.py` (Async DB Writer)
|
|
|
|
### 2.3 MCP (`mcp-server/`)
|
|
- `stdio_server.py`, `auto_trade_claude.py`, `trade_monitor.py`
|
|
|
|
---
|
|
|
|
## 3. Architecture Principles (Critical)
|
|
|
|
### 3.1 Separation of Concerns
|
|
- **Real-time Layer**: Handles API callbacks, Websocket broadcasts, and memory caching. **Zero DB I/O allowed.**
|
|
- **Persistence Layer**: Handles DB INSERT/UPDATE operations via background workers.
|
|
|
|
### 3.2 Async DB Worker Rule
|
|
- **Direct DB Access Ban**: Never call `AsyncSessionLocal()` or `commit()` inside API callbacks or real-time schedulers.
|
|
- **Queue Usage**: All data persistence (Trade history, Analysis results) must be sent to `db_task_queue` in `db_worker.py`.
|
|
- **Worker**: The background worker processes the queue and handles safe DB transactions sequentially.
|
|
|
|
---
|
|
|
|
## 4. Coding Guidelines
|
|
|
|
### 4.1 Stability
|
|
- **No Breaking Changes**: Never alter existing function/class signatures.
|
|
- **Versioning**: Use `_v2`, `_v3` suffixes for new strategy implementations.
|
|
|
|
### 4.2 Optimization
|
|
- **JSON Handling**: Always use `core.json_helpers._dumps()` instead of `json.dumps`.
|
|
- **Prompt Engineering**: Minimize tokens, use compact formats.
|
|
|
|
---
|
|
|
|
## 5. Risk Management Rules
|
|
|
|
### 5.1 Position Sizing
|
|
- **Max Allocation**: 3-4% of total capital per stock.
|
|
- **Max Count**: 20-25 stocks max.
|
|
- **Leverage**: Max 20% of total capital for Inverse/Leveraged ETFs.
|
|
|
|
### 5.2 Stop Loss (SL) & Take Profit (TP)
|
|
- **SL Base**: -6% (Stable), -10% (Volatile).
|
|
- **SL ATR**: `Entry Price - (2.5 * ATR)`. (Priority over base SL)
|
|
- **TP**: Sell 50% at +2R profit.
|
|
- **Trailing Stop**: `High - (1.5 * ATR)` for remaining 50%.
|
|
|
|
### 5.3 MDD Control
|
|
- **MDD -10%**: Stop new entries. Reduce position sizes by 30%. **Stop Short-term Strategy.**
|
|
- **MDD -20%**: Force reduce all positions by 50%. Liquidate leveraged assets first.
|
|
|
|
### 5.4 Filters
|
|
- **Price**: > 5,000 KRW (Korea), > $4 (US). (Exceptions: ETFs, REITs)
|
|
- **Correlation**: Max 3 stocks per sector. Reject entry if correlation > 0.7 with portfolio.
|
|
|
|
---
|
|
|
|
## 6. Strategy A: RSI + Bollinger Mean Reversion v2
|
|
|
|
### 6.1 Market Regime (Daily)
|
|
- **BULL**: KOSPI200 > MA200 AND MA200 Slope > 0.
|
|
- **BEAR**: KOSPI200 < MA200 AND MA200 Slope < 0.
|
|
- **SIDEWAYS**: ADX < 20 OR Slope ≈ 0. **(Ignore all signals)**
|
|
|
|
### 6.2 Entry Conditions
|
|
- **Bull Market**: RSI(14) < 25, Price within BB Lower (-3% to +1.5%), Vol > 20MA.
|
|
- **Bear Market**: RSI(14) < 30, Price < BB Lower, Vol > 1.5x 20MA, Reversal candle required.
|
|
- **Pre-emptive**: Daily RSI < 40 AND 60m RSI < 30 AND Breakout MA5.
|
|
|
|
### 6.3 Exit Conditions
|
|
- **Partial**: RSI > 50 OR Price > BB Mid OR Profit > 2*ATR.
|
|
- **Full**: RSI > 65 OR Price > BB Upper (99%) OR Trailing Stop.
|
|
|
|
---
|
|
|
|
## 7. Strategy B: Aggressive Growth
|
|
|
|
### 7.1 Kosdaq Scanner (Swing)
|
|
- **Scope**: All Kosdaq (~1600).
|
|
- **Filter**: Price > 5,000 KRW, Top 20% Volume.
|
|
- **Score**: `0.5*RSI + 0.3*BB + 0.2*Vol`. Pick Top 20.
|
|
- **Allocation**: 25% of Capital.
|
|
|
|
### 7.2 Short-term Strategy (15m)
|
|
- **Target**: Stocks with Daily RSI < 40.
|
|
- **Entry**: 15m RSI < 30, Price near BB Lower, MA5 Breakout, Vol > 1.3x.
|
|
- **Exit**: 15m RSI > 55 OR Profit > 1.5 * ATR(15m).
|
|
- **Allocation**: Max 25% of Capital. **Disable if MDD < -10%.**
|
|
|
|
---
|
|
|
|
## 8. Instructions for Claude
|
|
|
|
### 8.1 Critical Checkpoints
|
|
1. **Architecture**: Ensure all DB writes use `db_worker.py`.
|
|
2. **Safety**: Always apply Risk Rules (Section 5) to every trade.
|
|
3. **Regime**: Do NOT suggest entries in SIDEWAYS regime.
|
|
4. **Testing**: No real trading without Backtest + Walk-forward validation.
|
|
|
|
### 8.2 Response Format
|
|
- Use `_dumps()` for JSON.
|
|
- Create new files for new features.
|
|
- Do not modify existing signatures.
|
|
|
|
*Last updated: 2026-02-24* |