Compare commits
15 Commits
feature/is
...
d105a3ff5e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d105a3ff5e | ||
| 0424c78f6c | |||
|
|
3fdb7a29d4 | ||
| 31b4d0bf1e | |||
|
|
e2275a23b1 | ||
| 7522bb7e66 | |||
|
|
63fa6841a2 | ||
| ece3c5597b | |||
|
|
63f4e49d88 | ||
|
|
e0a6b307a2 | ||
| 75320eb587 | |||
|
|
afb31b7f4b | ||
| a429a9f4da | |||
|
|
d9763def85 | ||
| ab7f0444b2 |
22
CLAUDE.md
22
CLAUDE.md
@@ -15,6 +15,9 @@ pytest -v --cov=src
|
|||||||
|
|
||||||
# Run (paper trading)
|
# Run (paper trading)
|
||||||
python -m src.main --mode=paper
|
python -m src.main --mode=paper
|
||||||
|
|
||||||
|
# Run with dashboard
|
||||||
|
python -m src.main --mode=paper --dashboard
|
||||||
```
|
```
|
||||||
|
|
||||||
## Telegram Notifications (Optional)
|
## Telegram Notifications (Optional)
|
||||||
@@ -43,6 +46,10 @@ Get real-time alerts for trades, circuit breakers, and system events via Telegra
|
|||||||
- ℹ️ Market open/close notifications
|
- ℹ️ Market open/close notifications
|
||||||
- 📝 System startup/shutdown status
|
- 📝 System startup/shutdown status
|
||||||
|
|
||||||
|
### Interactive Commands
|
||||||
|
|
||||||
|
With `TELEGRAM_COMMANDS_ENABLED=true` (default), the bot supports 9 bidirectional commands: `/help`, `/status`, `/positions`, `/report`, `/scenarios`, `/review`, `/dashboard`, `/stop`, `/resume`.
|
||||||
|
|
||||||
**Fail-safe**: Notifications never crash the trading system. Missing credentials or API errors are logged but trading continues normally.
|
**Fail-safe**: Notifications never crash the trading system. Missing credentials or API errors are logged but trading continues normally.
|
||||||
|
|
||||||
## Smart Volatility Scanner (Optional)
|
## Smart Volatility Scanner (Optional)
|
||||||
@@ -109,17 +116,23 @@ User requirements and feedback are tracked in [docs/requirements-log.md](docs/re
|
|||||||
```
|
```
|
||||||
src/
|
src/
|
||||||
├── analysis/ # Technical analysis (RSI, volatility, smart scanner)
|
├── analysis/ # Technical analysis (RSI, volatility, smart scanner)
|
||||||
|
├── backup/ # Disaster recovery (scheduler, cloud storage, health)
|
||||||
|
├── brain/ # Gemini AI decision engine (prompt optimizer, context selector)
|
||||||
├── broker/ # KIS API client (domestic + overseas)
|
├── broker/ # KIS API client (domestic + overseas)
|
||||||
├── brain/ # Gemini AI decision engine
|
├── context/ # L1-L7 hierarchical memory system
|
||||||
├── core/ # Risk manager (READ-ONLY)
|
├── core/ # Risk manager (READ-ONLY)
|
||||||
├── evolution/ # Self-improvement optimizer
|
├── dashboard/ # FastAPI read-only monitoring (8 API endpoints)
|
||||||
|
├── data/ # External data integration (news, market data, calendar)
|
||||||
|
├── evolution/ # Self-improvement (optimizer, daily review, scorecard)
|
||||||
|
├── logging/ # Decision logger (audit trail)
|
||||||
├── markets/ # Market schedules and timezone handling
|
├── markets/ # Market schedules and timezone handling
|
||||||
├── notifications/ # Telegram real-time alerts
|
├── notifications/ # Telegram alerts + bidirectional commands (9 commands)
|
||||||
|
├── strategy/ # Pre-market planner, scenario engine, playbook store
|
||||||
├── db.py # SQLite trade logging
|
├── db.py # SQLite trade logging
|
||||||
├── main.py # Trading loop orchestrator
|
├── main.py # Trading loop orchestrator
|
||||||
└── config.py # Settings (from .env)
|
└── config.py # Settings (from .env)
|
||||||
|
|
||||||
tests/ # 343 tests across 14 files
|
tests/ # 551 tests across 25 files
|
||||||
docs/ # Extended documentation
|
docs/ # Extended documentation
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -131,6 +144,7 @@ ruff check src/ tests/ # Lint
|
|||||||
mypy src/ --strict # Type check
|
mypy src/ --strict # Type check
|
||||||
|
|
||||||
python -m src.main --mode=paper # Paper trading
|
python -m src.main --mode=paper # Paper trading
|
||||||
|
python -m src.main --mode=paper --dashboard # With dashboard
|
||||||
python -m src.main --mode=live # Live trading (⚠️ real money)
|
python -m src.main --mode=live # Live trading (⚠️ real money)
|
||||||
|
|
||||||
# Gitea workflow (requires tea CLI)
|
# Gitea workflow (requires tea CLI)
|
||||||
|
|||||||
@@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
Self-evolving AI trading agent for global stock markets via KIS (Korea Investment & Securities) API. The main loop in `src/main.py` orchestrates four components across multiple markets with two trading modes: daily (batch API calls) or realtime (per-stock decisions).
|
Self-evolving AI trading agent for global stock markets via KIS (Korea Investment & Securities) API. The main loop in `src/main.py` orchestrates components across multiple markets with two trading modes: daily (batch API calls) or realtime (per-stock decisions).
|
||||||
|
|
||||||
|
**v2 Proactive Playbook Architecture**: The system uses a "plan once, execute locally" approach. Pre-market, the AI generates a playbook of scenarios (one Gemini API call per market per day). During trading hours, a local scenario engine matches live market data against these pre-computed scenarios — no additional AI calls needed. This dramatically reduces API costs and latency.
|
||||||
|
|
||||||
## Trading Modes
|
## Trading Modes
|
||||||
|
|
||||||
@@ -46,9 +48,11 @@ High-frequency trading with individual stock analysis:
|
|||||||
**KISBroker** (`kis_api.py`) — Async KIS API client for domestic Korean market
|
**KISBroker** (`kis_api.py`) — Async KIS API client for domestic Korean market
|
||||||
|
|
||||||
- Automatic OAuth token refresh (valid for 24 hours)
|
- Automatic OAuth token refresh (valid for 24 hours)
|
||||||
- Leaky-bucket rate limiter (10 requests per second)
|
- Leaky-bucket rate limiter (configurable RPS, default 2.0)
|
||||||
- POST body hash-key signing for order authentication
|
- POST body hash-key signing for order authentication
|
||||||
- Custom SSL context with disabled hostname verification for VTS (virtual trading) endpoint due to known certificate mismatch
|
- Custom SSL context with disabled hostname verification for VTS (virtual trading) endpoint due to known certificate mismatch
|
||||||
|
- `fetch_market_rankings()` — Fetch volume surge rankings from KIS API
|
||||||
|
- `get_daily_prices()` — Fetch OHLCV history for technical analysis
|
||||||
|
|
||||||
**OverseasBroker** (`overseas.py`) — KIS overseas stock API wrapper
|
**OverseasBroker** (`overseas.py`) — KIS overseas stock API wrapper
|
||||||
|
|
||||||
@@ -63,10 +67,7 @@ High-frequency trading with individual stock analysis:
|
|||||||
- `is_market_open()` checks weekends, trading hours, lunch breaks
|
- `is_market_open()` checks weekends, trading hours, lunch breaks
|
||||||
- `get_open_markets()` returns currently active markets
|
- `get_open_markets()` returns currently active markets
|
||||||
- `get_next_market_open()` finds next market to open and when
|
- `get_next_market_open()` finds next market to open and when
|
||||||
|
- 10 global markets defined (KR, US_NASDAQ, US_NYSE, US_AMEX, JP, HK, CN_SHA, CN_SZA, VN_HNX, VN_HSX)
|
||||||
**New API Methods** (added in v0.9.0):
|
|
||||||
- `fetch_market_rankings()` — Fetch volume surge rankings from KIS API
|
|
||||||
- `get_daily_prices()` — Fetch OHLCV history for technical analysis
|
|
||||||
|
|
||||||
### 2. Analysis (`src/analysis/`)
|
### 2. Analysis (`src/analysis/`)
|
||||||
|
|
||||||
@@ -91,14 +92,9 @@ High-frequency trading with individual stock analysis:
|
|||||||
- **Fallback**: Uses static watchlist if ranking API unavailable
|
- **Fallback**: Uses static watchlist if ranking API unavailable
|
||||||
- **Realtime mode only**: Daily mode uses batch processing for API efficiency
|
- **Realtime mode only**: Daily mode uses batch processing for API efficiency
|
||||||
|
|
||||||
**Benefits:**
|
### 3. Brain (`src/brain/`)
|
||||||
- Reduces Gemini API calls from 20-30 stocks to 1-3 qualified candidates
|
|
||||||
- Fast Python-based filtering before expensive AI judgment
|
|
||||||
- Logs selection context (RSI, volume_ratio, signal, score) for Evolution system
|
|
||||||
|
|
||||||
### 3. Brain (`src/brain/gemini_client.py`)
|
**GeminiClient** (`gemini_client.py`) — AI decision engine powered by Google Gemini
|
||||||
|
|
||||||
**GeminiClient** — AI decision engine powered by Google Gemini
|
|
||||||
|
|
||||||
- Constructs structured prompts from market data
|
- Constructs structured prompts from market data
|
||||||
- Parses JSON responses into `TradeDecision` objects (`action`, `confidence`, `rationale`)
|
- Parses JSON responses into `TradeDecision` objects (`action`, `confidence`, `rationale`)
|
||||||
@@ -106,11 +102,20 @@ High-frequency trading with individual stock analysis:
|
|||||||
- Falls back to safe HOLD on any parse/API error
|
- Falls back to safe HOLD on any parse/API error
|
||||||
- Handles markdown-wrapped JSON, malformed responses, invalid actions
|
- Handles markdown-wrapped JSON, malformed responses, invalid actions
|
||||||
|
|
||||||
|
**PromptOptimizer** (`prompt_optimizer.py`) — Token efficiency optimization
|
||||||
|
|
||||||
|
- Reduces prompt size while preserving decision quality
|
||||||
|
- Caches optimized prompts
|
||||||
|
|
||||||
|
**ContextSelector** (`context_selector.py`) — Relevant context selection for prompts
|
||||||
|
|
||||||
|
- Selects appropriate context layers for current market conditions
|
||||||
|
|
||||||
### 4. Risk Manager (`src/core/risk_manager.py`)
|
### 4. Risk Manager (`src/core/risk_manager.py`)
|
||||||
|
|
||||||
**RiskManager** — Safety circuit breaker and order validation
|
**RiskManager** — Safety circuit breaker and order validation
|
||||||
|
|
||||||
⚠️ **READ-ONLY by policy** (see [`docs/agents.md`](./agents.md))
|
> **READ-ONLY by policy** (see [`docs/agents.md`](./agents.md))
|
||||||
|
|
||||||
- **Circuit Breaker**: Halts all trading via `SystemExit` when daily P&L drops below -3.0%
|
- **Circuit Breaker**: Halts all trading via `SystemExit` when daily P&L drops below -3.0%
|
||||||
- Threshold may only be made stricter, never relaxed
|
- Threshold may only be made stricter, never relaxed
|
||||||
@@ -118,7 +123,79 @@ High-frequency trading with individual stock analysis:
|
|||||||
- **Fat-Finger Protection**: Rejects orders exceeding 30% of available cash
|
- **Fat-Finger Protection**: Rejects orders exceeding 30% of available cash
|
||||||
- Must always be enforced, cannot be disabled
|
- Must always be enforced, cannot be disabled
|
||||||
|
|
||||||
### 5. Notifications (`src/notifications/telegram_client.py`)
|
### 5. Strategy (`src/strategy/`)
|
||||||
|
|
||||||
|
**Pre-Market Planner** (`pre_market_planner.py`) — AI playbook generation
|
||||||
|
|
||||||
|
- Runs before market open (configurable `PRE_MARKET_MINUTES`, default 30)
|
||||||
|
- Generates scenario-based playbooks via single Gemini API call per market
|
||||||
|
- Handles timeout (`PLANNER_TIMEOUT_SECONDS`, default 60) with defensive playbook fallback
|
||||||
|
- Persists playbooks to database for audit trail
|
||||||
|
|
||||||
|
**Scenario Engine** (`scenario_engine.py`) — Local scenario matching
|
||||||
|
|
||||||
|
- Matches live market data against pre-computed playbook scenarios
|
||||||
|
- No AI calls during trading hours — pure Python matching logic
|
||||||
|
- Returns matched scenarios with confidence scores
|
||||||
|
- Configurable `MAX_SCENARIOS_PER_STOCK` (default 5)
|
||||||
|
- Periodic rescan at `RESCAN_INTERVAL_SECONDS` (default 300)
|
||||||
|
|
||||||
|
**Playbook Store** (`playbook_store.py`) — Playbook persistence
|
||||||
|
|
||||||
|
- SQLite-backed storage for daily playbooks
|
||||||
|
- Date and market-based retrieval
|
||||||
|
- Status tracking (generated, active, expired)
|
||||||
|
|
||||||
|
**Models** (`models.py`) — Pydantic data models
|
||||||
|
|
||||||
|
- Scenario, Playbook, MatchResult, and related type definitions
|
||||||
|
|
||||||
|
### 6. Context System (`src/context/`)
|
||||||
|
|
||||||
|
**Context Store** (`store.py`) — L1-L7 hierarchical memory
|
||||||
|
|
||||||
|
- 7-layer context system (see [docs/context-tree.md](./context-tree.md)):
|
||||||
|
- L1: Tick-level (real-time price)
|
||||||
|
- L2: Intraday (session summary)
|
||||||
|
- L3: Daily (end-of-day)
|
||||||
|
- L4: Weekly (trend analysis)
|
||||||
|
- L5: Monthly (strategy review)
|
||||||
|
- L6: Daily Review (scorecard)
|
||||||
|
- L7: Evolution (long-term learning)
|
||||||
|
- Key-value storage with timeframe tagging
|
||||||
|
- SQLite persistence in `contexts` table
|
||||||
|
|
||||||
|
**Context Scheduler** (`scheduler.py`) — Periodic aggregation
|
||||||
|
|
||||||
|
- Scheduled summarization from lower to higher layers
|
||||||
|
- Configurable aggregation intervals
|
||||||
|
|
||||||
|
**Context Summarizer** (`summarizer.py`) — Layer summarization
|
||||||
|
|
||||||
|
- Aggregates lower-layer data into higher-layer summaries
|
||||||
|
|
||||||
|
### 7. Dashboard (`src/dashboard/`)
|
||||||
|
|
||||||
|
**FastAPI App** (`app.py`) — Read-only monitoring dashboard
|
||||||
|
|
||||||
|
- Runs as daemon thread when enabled (`--dashboard` CLI flag or `DASHBOARD_ENABLED=true`)
|
||||||
|
- Configurable host/port (`DASHBOARD_HOST`, `DASHBOARD_PORT`, default `127.0.0.1:8080`)
|
||||||
|
- Serves static HTML frontend
|
||||||
|
|
||||||
|
**8 API Endpoints:**
|
||||||
|
|
||||||
|
| Endpoint | Method | Description |
|
||||||
|
|----------|--------|-------------|
|
||||||
|
| `/` | GET | Static HTML dashboard |
|
||||||
|
| `/api/status` | GET | Daily trading status by market |
|
||||||
|
| `/api/playbook/{date}` | GET | Playbook for specific date and market |
|
||||||
|
| `/api/scorecard/{date}` | GET | Daily scorecard from L6_DAILY context |
|
||||||
|
| `/api/performance` | GET | Trading performance metrics (by market + combined) |
|
||||||
|
| `/api/context/{layer}` | GET | Query context by layer (L1-L7) |
|
||||||
|
| `/api/decisions` | GET | Decision log entries with outcomes |
|
||||||
|
| `/api/scenarios/active` | GET | Today's matched scenarios |
|
||||||
|
|
||||||
|
### 8. Notifications (`src/notifications/telegram_client.py`)
|
||||||
|
|
||||||
**TelegramClient** — Real-time event notifications via Telegram Bot API
|
**TelegramClient** — Real-time event notifications via Telegram Bot API
|
||||||
|
|
||||||
@@ -126,7 +203,13 @@ High-frequency trading with individual stock analysis:
|
|||||||
- Non-blocking: failures are logged but never crash trading
|
- Non-blocking: failures are logged but never crash trading
|
||||||
- Rate-limited: 1 message/second default to respect Telegram API limits
|
- Rate-limited: 1 message/second default to respect Telegram API limits
|
||||||
- Auto-disabled when credentials missing
|
- Auto-disabled when credentials missing
|
||||||
- Gracefully handles API errors, network timeouts, invalid tokens
|
|
||||||
|
**TelegramCommandHandler** — Bidirectional command interface
|
||||||
|
|
||||||
|
- Long polling from Telegram API (configurable `TELEGRAM_POLLING_INTERVAL`)
|
||||||
|
- 9 interactive commands: `/help`, `/status`, `/positions`, `/report`, `/scenarios`, `/review`, `/dashboard`, `/stop`, `/resume`
|
||||||
|
- Authorization filtering by `TELEGRAM_CHAT_ID`
|
||||||
|
- Enable/disable via `TELEGRAM_COMMANDS_ENABLED` (default: true)
|
||||||
|
|
||||||
**Notification Types:**
|
**Notification Types:**
|
||||||
- Trade execution (BUY/SELL with confidence)
|
- Trade execution (BUY/SELL with confidence)
|
||||||
@@ -134,12 +217,12 @@ High-frequency trading with individual stock analysis:
|
|||||||
- Fat-finger protection triggers (order rejection)
|
- Fat-finger protection triggers (order rejection)
|
||||||
- Market open/close events
|
- Market open/close events
|
||||||
- System startup/shutdown status
|
- System startup/shutdown status
|
||||||
|
- Playbook generation results
|
||||||
|
- Stop-loss monitoring alerts
|
||||||
|
|
||||||
**Setup:** See [src/notifications/README.md](../src/notifications/README.md) for bot creation and configuration.
|
### 9. Evolution (`src/evolution/`)
|
||||||
|
|
||||||
### 6. Evolution (`src/evolution/optimizer.py`)
|
**StrategyOptimizer** (`optimizer.py`) — Self-improvement loop
|
||||||
|
|
||||||
**StrategyOptimizer** — Self-improvement loop
|
|
||||||
|
|
||||||
- Analyzes high-confidence losing trades from SQLite
|
- Analyzes high-confidence losing trades from SQLite
|
||||||
- Asks Gemini to generate new `BaseStrategy` subclasses
|
- Asks Gemini to generate new `BaseStrategy` subclasses
|
||||||
@@ -147,99 +230,196 @@ High-frequency trading with individual stock analysis:
|
|||||||
- Simulates PR creation for human review
|
- Simulates PR creation for human review
|
||||||
- Only activates strategies that pass all tests
|
- Only activates strategies that pass all tests
|
||||||
|
|
||||||
|
**DailyReview** (`daily_review.py`) — End-of-day review
|
||||||
|
|
||||||
|
- Generates comprehensive trade performance summary
|
||||||
|
- Stores results in L6_DAILY context layer
|
||||||
|
- Tracks win rate, P&L, confidence accuracy
|
||||||
|
|
||||||
|
**DailyScorecard** (`scorecard.py`) — Performance scoring
|
||||||
|
|
||||||
|
- Calculates daily metrics (trades, P&L, win rate, avg confidence)
|
||||||
|
- Enables trend tracking across days
|
||||||
|
|
||||||
|
**Stop-Loss Monitoring** — Real-time position protection
|
||||||
|
|
||||||
|
- Monitors positions against stop-loss levels from playbook scenarios
|
||||||
|
- Sends Telegram alerts when thresholds approached or breached
|
||||||
|
|
||||||
|
### 10. Decision Logger (`src/logging/decision_logger.py`)
|
||||||
|
|
||||||
|
**DecisionLogger** — Comprehensive audit trail
|
||||||
|
|
||||||
|
- Logs every trading decision with full context snapshot
|
||||||
|
- Captures input data, rationale, confidence, and outcomes
|
||||||
|
- Supports outcome tracking (P&L, accuracy) for post-analysis
|
||||||
|
- Stored in `decision_logs` table with indexed queries
|
||||||
|
- Review workflow support (reviewed flag, review notes)
|
||||||
|
|
||||||
|
### 11. Data Integration (`src/data/`)
|
||||||
|
|
||||||
|
**External Data Sources** (optional):
|
||||||
|
|
||||||
|
- `news_api.py` — News sentiment data
|
||||||
|
- `market_data.py` — Extended market data
|
||||||
|
- `economic_calendar.py` — Economic event calendar
|
||||||
|
|
||||||
|
### 12. Backup (`src/backup/`)
|
||||||
|
|
||||||
|
**Disaster Recovery** (see [docs/disaster_recovery.md](./disaster_recovery.md)):
|
||||||
|
|
||||||
|
- `scheduler.py` — Automated backup scheduling
|
||||||
|
- `exporter.py` — Data export to various formats
|
||||||
|
- `cloud_storage.py` — S3-compatible cloud backup
|
||||||
|
- `health_monitor.py` — Backup integrity verification
|
||||||
|
|
||||||
## Data Flow
|
## Data Flow
|
||||||
|
|
||||||
|
### Playbook Mode (Daily — Primary v2 Flow)
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ Pre-Market Phase (before market open) │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────────────────────────┐
|
||||||
|
│ Pre-Market Planner │
|
||||||
|
│ - 1 Gemini API call per market │
|
||||||
|
│ - Generate scenario playbook │
|
||||||
|
│ - Store in playbooks table │
|
||||||
|
└──────────────────┬───────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ Trading Hours (market open → close) │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────────────────────────┐
|
||||||
|
│ Market Schedule Check │
|
||||||
|
│ - Get open markets │
|
||||||
|
│ - Filter by enabled markets │
|
||||||
|
└──────────────────┬───────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────────────────────────┐
|
||||||
|
│ Scenario Engine (local) │
|
||||||
|
│ - Match live data vs playbook │
|
||||||
|
│ - No AI calls needed │
|
||||||
|
│ - Return matched scenarios │
|
||||||
|
└──────────────────┬───────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────────────────────────┐
|
||||||
|
│ Risk Manager: Validate Order │
|
||||||
|
│ - Check circuit breaker │
|
||||||
|
│ - Check fat-finger limit │
|
||||||
|
└──────────────────┬───────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────────────────────────┐
|
||||||
|
│ Broker: Execute Order │
|
||||||
|
│ - Domestic: send_order() │
|
||||||
|
│ - Overseas: send_overseas_order()│
|
||||||
|
└──────────────────┬───────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────────────────────────┐
|
||||||
|
│ Decision Logger + DB │
|
||||||
|
│ - Full audit trail │
|
||||||
|
│ - Context snapshot │
|
||||||
|
│ - Telegram notification │
|
||||||
|
└──────────────────┬───────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ Post-Market Phase │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────────────────────────┐
|
||||||
|
│ Daily Review + Scorecard │
|
||||||
|
│ - Performance summary │
|
||||||
|
│ - Store in L6_DAILY context │
|
||||||
|
│ - Evolution learning │
|
||||||
|
└──────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
### Realtime Mode (with Smart Scanner)
|
### Realtime Mode (with Smart Scanner)
|
||||||
|
|
||||||
```
|
```
|
||||||
┌─────────────────────────────────────────────────────────────┐
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
│ Main Loop (60s cycle per market) │
|
│ Main Loop (60s cycle per market) │
|
||||||
└─────────────────────────────────────────────────────────────┘
|
└─────────────────────────────────────────────────────────────┘
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
┌──────────────────────────────────┐
|
┌──────────────────────────────────┐
|
||||||
│ Market Schedule Check │
|
│ Market Schedule Check │
|
||||||
│ - Get open markets │
|
│ - Get open markets │
|
||||||
│ - Filter by enabled markets │
|
│ - Filter by enabled markets │
|
||||||
│ - Wait if all closed │
|
│ - Wait if all closed │
|
||||||
└──────────────────┬────────────────┘
|
└──────────────────┬───────────────┘
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
┌──────────────────────────────────┐
|
┌──────────────────────────────────┐
|
||||||
│ Smart Scanner (Python-first) │
|
│ Smart Scanner (Python-first) │
|
||||||
│ - Fetch volume rankings (KIS) │
|
│ - Fetch volume rankings (KIS) │
|
||||||
│ - Get 20d price history per stock│
|
│ - Get 20d price history per stock│
|
||||||
│ - Calculate RSI(14) + vol ratio │
|
│ - Calculate RSI(14) + vol ratio │
|
||||||
│ - Filter: vol>2x AND RSI extreme │
|
│ - Filter: vol>2x AND RSI extreme │
|
||||||
│ - Return top 3 qualified stocks │
|
│ - Return top 3 qualified stocks │
|
||||||
└──────────────────┬────────────────┘
|
└──────────────────┬───────────────┘
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
┌──────────────────────────────────┐
|
┌──────────────────────────────────┐
|
||||||
│ For Each Qualified Candidate │
|
│ For Each Qualified Candidate │
|
||||||
└──────────────────┬────────────────┘
|
└──────────────────┬───────────────┘
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
┌──────────────────────────────────┐
|
┌──────────────────────────────────┐
|
||||||
│ Broker: Fetch Market Data │
|
│ Broker: Fetch Market Data │
|
||||||
│ - Domestic: orderbook + balance │
|
│ - Domestic: orderbook + balance │
|
||||||
│ - Overseas: price + balance │
|
│ - Overseas: price + balance │
|
||||||
└──────────────────┬────────────────┘
|
└──────────────────┬───────────────┘
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
┌──────────────────────────────────┐
|
┌──────────────────────────────────┐
|
||||||
│ Calculate P&L │
|
│ Brain: Get Decision (AI) │
|
||||||
│ pnl_pct = (eval - cost) / cost │
|
│ - Build prompt with market data │
|
||||||
└──────────────────┬────────────────┘
|
│ - Call Gemini API │
|
||||||
|
│ - Parse JSON response │
|
||||||
|
│ - Return TradeDecision │
|
||||||
|
└──────────────────┬───────────────┘
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
┌──────────────────────────────────┐
|
┌──────────────────────────────────┐
|
||||||
│ Brain: Get Decision (AI) │
|
│ Risk Manager: Validate Order │
|
||||||
│ - Build prompt with market data │
|
│ - Check circuit breaker │
|
||||||
│ - Call Gemini API │
|
│ - Check fat-finger limit │
|
||||||
│ - Parse JSON response │
|
└──────────────────┬───────────────┘
|
||||||
│ - Return TradeDecision │
|
|
||||||
└──────────────────┬────────────────┘
|
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
┌──────────────────────────────────┐
|
┌──────────────────────────────────┐
|
||||||
│ Risk Manager: Validate Order │
|
│ Broker: Execute Order │
|
||||||
│ - Check circuit breaker │
|
│ - Domestic: send_order() │
|
||||||
│ - Check fat-finger limit │
|
│ - Overseas: send_overseas_order()│
|
||||||
│ - Raise if validation fails │
|
└──────────────────┬───────────────┘
|
||||||
└──────────────────┬────────────────┘
|
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
┌──────────────────────────────────┐
|
┌──────────────────────────────────┐
|
||||||
│ Broker: Execute Order │
|
│ Decision Logger + Notifications │
|
||||||
│ - Domestic: send_order() │
|
│ - Log trade to SQLite │
|
||||||
│ - Overseas: send_overseas_order() │
|
│ - selection_context (JSON) │
|
||||||
└──────────────────┬────────────────┘
|
│ - Telegram notification │
|
||||||
│
|
└──────────────────────────────────┘
|
||||||
▼
|
|
||||||
┌──────────────────────────────────┐
|
|
||||||
│ Notifications: Send Alert │
|
|
||||||
│ - Trade execution notification │
|
|
||||||
│ - Non-blocking (errors logged) │
|
|
||||||
│ - Rate-limited to 1/sec │
|
|
||||||
└──────────────────┬────────────────┘
|
|
||||||
│
|
|
||||||
▼
|
|
||||||
┌──────────────────────────────────┐
|
|
||||||
│ Database: Log Trade │
|
|
||||||
│ - SQLite (data/trades.db) │
|
|
||||||
│ - Track: action, confidence, │
|
|
||||||
│ rationale, market, exchange │
|
|
||||||
│ - NEW: selection_context (JSON) │
|
|
||||||
│ - RSI, volume_ratio, signal │
|
|
||||||
│ - For Evolution optimization │
|
|
||||||
└───────────────────────────────────┘
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Database Schema
|
## Database Schema
|
||||||
|
|
||||||
**SQLite** (`src/db.py`)
|
**SQLite** (`src/db.py`) — Database: `data/trades.db`
|
||||||
|
|
||||||
|
### trades
|
||||||
```sql
|
```sql
|
||||||
CREATE TABLE trades (
|
CREATE TABLE trades (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
@@ -251,25 +431,73 @@ CREATE TABLE trades (
|
|||||||
quantity INTEGER,
|
quantity INTEGER,
|
||||||
price REAL,
|
price REAL,
|
||||||
pnl REAL DEFAULT 0.0,
|
pnl REAL DEFAULT 0.0,
|
||||||
market TEXT DEFAULT 'KR', -- KR | US_NASDAQ | JP | etc.
|
market TEXT DEFAULT 'KR',
|
||||||
exchange_code TEXT DEFAULT 'KRX', -- KRX | NASD | NYSE | etc.
|
exchange_code TEXT DEFAULT 'KRX',
|
||||||
selection_context TEXT -- JSON: {rsi, volume_ratio, signal, score}
|
selection_context TEXT, -- JSON: {rsi, volume_ratio, signal, score}
|
||||||
|
decision_id TEXT -- Links to decision_logs
|
||||||
);
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
**Selection Context** (new in v0.9.0): Stores scanner selection criteria as JSON:
|
### contexts
|
||||||
```json
|
```sql
|
||||||
{
|
CREATE TABLE contexts (
|
||||||
"rsi": 28.5,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
"volume_ratio": 2.7,
|
layer TEXT NOT NULL, -- L1 through L7
|
||||||
"signal": "oversold",
|
timeframe TEXT,
|
||||||
"score": 85.2
|
key TEXT NOT NULL,
|
||||||
}
|
value TEXT NOT NULL, -- JSON data
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
-- Indices: idx_contexts_layer, idx_contexts_timeframe, idx_contexts_updated
|
||||||
```
|
```
|
||||||
|
|
||||||
Enables Evolution system to analyze correlation between selection criteria and trade outcomes.
|
### decision_logs
|
||||||
|
```sql
|
||||||
|
CREATE TABLE decision_logs (
|
||||||
|
decision_id TEXT PRIMARY KEY,
|
||||||
|
timestamp TEXT NOT NULL,
|
||||||
|
stock_code TEXT,
|
||||||
|
market TEXT,
|
||||||
|
exchange_code TEXT,
|
||||||
|
action TEXT,
|
||||||
|
confidence INTEGER,
|
||||||
|
rationale TEXT,
|
||||||
|
context_snapshot TEXT, -- JSON: full context at decision time
|
||||||
|
input_data TEXT, -- JSON: market data used
|
||||||
|
outcome_pnl REAL,
|
||||||
|
outcome_accuracy REAL,
|
||||||
|
reviewed INTEGER DEFAULT 0,
|
||||||
|
review_notes TEXT
|
||||||
|
);
|
||||||
|
-- Indices: idx_decision_logs_timestamp, idx_decision_logs_reviewed, idx_decision_logs_confidence
|
||||||
|
```
|
||||||
|
|
||||||
Auto-migration: Adds `market`, `exchange_code`, and `selection_context` columns if missing for backward compatibility.
|
### playbooks
|
||||||
|
```sql
|
||||||
|
CREATE TABLE playbooks (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
date TEXT NOT NULL,
|
||||||
|
market TEXT NOT NULL,
|
||||||
|
status TEXT DEFAULT 'generated',
|
||||||
|
playbook_json TEXT NOT NULL, -- Full playbook with scenarios
|
||||||
|
generated_at TEXT NOT NULL,
|
||||||
|
token_count INTEGER,
|
||||||
|
scenario_count INTEGER,
|
||||||
|
match_count INTEGER DEFAULT 0
|
||||||
|
);
|
||||||
|
-- Indices: idx_playbooks_date, idx_playbooks_market
|
||||||
|
```
|
||||||
|
|
||||||
|
### context_metadata
|
||||||
|
```sql
|
||||||
|
CREATE TABLE context_metadata (
|
||||||
|
layer TEXT PRIMARY KEY,
|
||||||
|
description TEXT,
|
||||||
|
retention_days INTEGER,
|
||||||
|
aggregation_source TEXT
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
@@ -284,29 +512,62 @@ KIS_APP_SECRET=your_app_secret
|
|||||||
KIS_ACCOUNT_NO=XXXXXXXX-XX
|
KIS_ACCOUNT_NO=XXXXXXXX-XX
|
||||||
GEMINI_API_KEY=your_gemini_key
|
GEMINI_API_KEY=your_gemini_key
|
||||||
|
|
||||||
# Optional
|
# Optional — Trading Mode
|
||||||
MODE=paper # paper | live
|
MODE=paper # paper | live
|
||||||
DB_PATH=data/trades.db
|
|
||||||
CONFIDENCE_THRESHOLD=80
|
|
||||||
MAX_LOSS_PCT=3.0
|
|
||||||
MAX_ORDER_PCT=30.0
|
|
||||||
ENABLED_MARKETS=KR,US_NASDAQ # Comma-separated market codes
|
|
||||||
|
|
||||||
# Trading Mode (API efficiency)
|
|
||||||
TRADE_MODE=daily # daily | realtime
|
TRADE_MODE=daily # daily | realtime
|
||||||
DAILY_SESSIONS=4 # Sessions per day (daily mode only)
|
DAILY_SESSIONS=4 # Sessions per day (daily mode only)
|
||||||
SESSION_INTERVAL_HOURS=6 # Hours between sessions (daily mode only)
|
SESSION_INTERVAL_HOURS=6 # Hours between sessions (daily mode only)
|
||||||
|
|
||||||
# Telegram Notifications (optional)
|
# Optional — Database
|
||||||
|
DB_PATH=data/trades.db
|
||||||
|
|
||||||
|
# Optional — Risk
|
||||||
|
CONFIDENCE_THRESHOLD=80
|
||||||
|
MAX_LOSS_PCT=3.0
|
||||||
|
MAX_ORDER_PCT=30.0
|
||||||
|
|
||||||
|
# Optional — Markets
|
||||||
|
ENABLED_MARKETS=KR,US # Comma-separated market codes
|
||||||
|
RATE_LIMIT_RPS=2.0 # KIS API requests per second
|
||||||
|
|
||||||
|
# Optional — Pre-Market Planner (v2)
|
||||||
|
PRE_MARKET_MINUTES=30 # Minutes before market open to generate playbook
|
||||||
|
MAX_SCENARIOS_PER_STOCK=5 # Max scenarios per stock in playbook
|
||||||
|
PLANNER_TIMEOUT_SECONDS=60 # Timeout for playbook generation
|
||||||
|
DEFENSIVE_PLAYBOOK_ON_FAILURE=true # Fallback on AI failure
|
||||||
|
RESCAN_INTERVAL_SECONDS=300 # Scenario rescan interval during trading
|
||||||
|
|
||||||
|
# Optional — Smart Scanner (realtime mode only)
|
||||||
|
RSI_OVERSOLD_THRESHOLD=30 # 0-50, oversold threshold
|
||||||
|
RSI_MOMENTUM_THRESHOLD=70 # 50-100, momentum threshold
|
||||||
|
VOL_MULTIPLIER=2.0 # Minimum volume ratio (2.0 = 200%)
|
||||||
|
SCANNER_TOP_N=3 # Max qualified candidates per scan
|
||||||
|
|
||||||
|
# Optional — Dashboard
|
||||||
|
DASHBOARD_ENABLED=false # Enable FastAPI dashboard
|
||||||
|
DASHBOARD_HOST=127.0.0.1 # Dashboard bind address
|
||||||
|
DASHBOARD_PORT=8080 # Dashboard port (1-65535)
|
||||||
|
|
||||||
|
# Optional — Telegram
|
||||||
TELEGRAM_BOT_TOKEN=1234567890:ABCdefGHIjklMNOpqrsTUVwxyz
|
TELEGRAM_BOT_TOKEN=1234567890:ABCdefGHIjklMNOpqrsTUVwxyz
|
||||||
TELEGRAM_CHAT_ID=123456789
|
TELEGRAM_CHAT_ID=123456789
|
||||||
TELEGRAM_ENABLED=true
|
TELEGRAM_ENABLED=true
|
||||||
|
TELEGRAM_COMMANDS_ENABLED=true # Enable bidirectional commands
|
||||||
|
TELEGRAM_POLLING_INTERVAL=1.0 # Command polling interval (seconds)
|
||||||
|
|
||||||
# Smart Scanner (optional, realtime mode only)
|
# Optional — Backup
|
||||||
RSI_OVERSOLD_THRESHOLD=30 # 0-50, oversold threshold
|
BACKUP_ENABLED=false
|
||||||
RSI_MOMENTUM_THRESHOLD=70 # 50-100, momentum threshold
|
BACKUP_DIR=data/backups
|
||||||
VOL_MULTIPLIER=2.0 # Minimum volume ratio (2.0 = 200%)
|
S3_ENDPOINT_URL=...
|
||||||
SCANNER_TOP_N=3 # Max qualified candidates per scan
|
S3_ACCESS_KEY=...
|
||||||
|
S3_SECRET_KEY=...
|
||||||
|
S3_BUCKET_NAME=...
|
||||||
|
S3_REGION=...
|
||||||
|
|
||||||
|
# Optional — External Data
|
||||||
|
NEWS_API_KEY=...
|
||||||
|
NEWS_API_PROVIDER=...
|
||||||
|
MARKET_DATA_API_KEY=...
|
||||||
```
|
```
|
||||||
|
|
||||||
Tests use in-memory SQLite (`DB_PATH=":memory:"`) and dummy credentials via `tests/conftest.py`.
|
Tests use in-memory SQLite (`DB_PATH=":memory:"`) and dummy credentials via `tests/conftest.py`.
|
||||||
@@ -340,4 +601,9 @@ Tests use in-memory SQLite (`DB_PATH=":memory:"`) and dummy credentials via `tes
|
|||||||
- Invalid token → log error, trading unaffected
|
- Invalid token → log error, trading unaffected
|
||||||
- Rate limit exceeded → queued via rate limiter
|
- Rate limit exceeded → queued via rate limiter
|
||||||
|
|
||||||
**Guarantee**: Notification failures never interrupt trading operations.
|
### Playbook Generation Failure
|
||||||
|
- Timeout → fall back to defensive playbook (`DEFENSIVE_PLAYBOOK_ON_FAILURE`)
|
||||||
|
- API error → use previous day's playbook if available
|
||||||
|
- No playbook → skip pre-market phase, fall back to direct AI calls
|
||||||
|
|
||||||
|
**Guarantee**: Notification and dashboard failures never interrupt trading operations.
|
||||||
|
|||||||
@@ -119,7 +119,7 @@ No decorator needed for async tests.
|
|||||||
# Install all dependencies (production + dev)
|
# Install all dependencies (production + dev)
|
||||||
pip install -e ".[dev]"
|
pip install -e ".[dev]"
|
||||||
|
|
||||||
# Run full test suite with coverage
|
# Run full test suite with coverage (551 tests across 25 files)
|
||||||
pytest -v --cov=src --cov-report=term-missing
|
pytest -v --cov=src --cov-report=term-missing
|
||||||
|
|
||||||
# Run a single test file
|
# Run a single test file
|
||||||
@@ -137,11 +137,61 @@ mypy src/ --strict
|
|||||||
# Run the trading agent
|
# Run the trading agent
|
||||||
python -m src.main --mode=paper
|
python -m src.main --mode=paper
|
||||||
|
|
||||||
|
# Run with dashboard enabled
|
||||||
|
python -m src.main --mode=paper --dashboard
|
||||||
|
|
||||||
# Docker
|
# Docker
|
||||||
docker compose up -d ouroboros # Run agent
|
docker compose up -d ouroboros # Run agent
|
||||||
docker compose --profile test up test # Run tests in container
|
docker compose --profile test up test # Run tests in container
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Dashboard
|
||||||
|
|
||||||
|
The FastAPI dashboard provides read-only monitoring of the trading system.
|
||||||
|
|
||||||
|
### Starting the Dashboard
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Via CLI flag
|
||||||
|
python -m src.main --mode=paper --dashboard
|
||||||
|
|
||||||
|
# Via environment variable
|
||||||
|
DASHBOARD_ENABLED=true python -m src.main --mode=paper
|
||||||
|
```
|
||||||
|
|
||||||
|
Dashboard runs as a daemon thread on `DASHBOARD_HOST:DASHBOARD_PORT` (default: `127.0.0.1:8080`).
|
||||||
|
|
||||||
|
### API Endpoints
|
||||||
|
|
||||||
|
| Endpoint | Description |
|
||||||
|
|----------|-------------|
|
||||||
|
| `GET /` | HTML dashboard UI |
|
||||||
|
| `GET /api/status` | Daily trading status by market |
|
||||||
|
| `GET /api/playbook/{date}` | Playbook for specific date (query: `market`) |
|
||||||
|
| `GET /api/scorecard/{date}` | Daily scorecard from L6_DAILY context |
|
||||||
|
| `GET /api/performance` | Performance metrics by market and combined |
|
||||||
|
| `GET /api/context/{layer}` | Context data by layer L1-L7 (query: `timeframe`) |
|
||||||
|
| `GET /api/decisions` | Decision log entries (query: `limit`, `market`) |
|
||||||
|
| `GET /api/scenarios/active` | Today's matched scenarios |
|
||||||
|
|
||||||
|
## Telegram Commands
|
||||||
|
|
||||||
|
When `TELEGRAM_COMMANDS_ENABLED=true` (default), the bot accepts these interactive commands:
|
||||||
|
|
||||||
|
| Command | Description |
|
||||||
|
|---------|-------------|
|
||||||
|
| `/help` | List available commands |
|
||||||
|
| `/status` | Show trading status (mode, markets, P&L) |
|
||||||
|
| `/positions` | Display account summary (balance, cash, P&L) |
|
||||||
|
| `/report` | Daily summary metrics (trades, P&L, win rate) |
|
||||||
|
| `/scenarios` | Show today's playbook scenarios |
|
||||||
|
| `/review` | Display recent scorecards (L6_DAILY layer) |
|
||||||
|
| `/dashboard` | Show dashboard URL if enabled |
|
||||||
|
| `/stop` | Pause trading |
|
||||||
|
| `/resume` | Resume trading |
|
||||||
|
|
||||||
|
Commands are only processed from the authorized `TELEGRAM_CHAT_ID`.
|
||||||
|
|
||||||
## Environment Setup
|
## Environment Setup
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -86,3 +86,28 @@
|
|||||||
- Plan Consistency (필수), Safety & Constraints, Quality, Workflow 4개 카테고리
|
- Plan Consistency (필수), Safety & Constraints, Quality, Workflow 4개 카테고리
|
||||||
|
|
||||||
**이슈/PR:** #114
|
**이슈/PR:** #114
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2026-02-16
|
||||||
|
|
||||||
|
### 문서 v2 동기화 (전체 문서 현행화)
|
||||||
|
|
||||||
|
**배경:**
|
||||||
|
- v2 기능 구현 완료 후 문서가 실제 코드 상태와 크게 괴리
|
||||||
|
- 문서에는 54 tests / 4 files로 기록되었으나 실제로는 551 tests / 25 files
|
||||||
|
- v2 핵심 기능(Playbook, Scenario Engine, Dashboard, Telegram Commands, Daily Review, Context System, Backup) 문서화 누락
|
||||||
|
|
||||||
|
**요구사항:**
|
||||||
|
1. `docs/testing.md` — 551 tests / 25 files 반영, 전체 테스트 파일 설명
|
||||||
|
2. `docs/architecture.md` — v2 컴포넌트(Strategy, Context, Dashboard, Decision Logger 등) 추가, Playbook Mode 데이터 플로우, DB 스키마 5개 테이블, v2 환경변수
|
||||||
|
3. `docs/commands.md` — Dashboard 실행 명령어, Telegram 명령어 9종 레퍼런스
|
||||||
|
4. `CLAUDE.md` — Project Structure 트리 확장, 테스트 수 업데이트, `--dashboard` 플래그
|
||||||
|
5. `docs/skills.md` — DB 파일명 `trades.db`로 통일, Dashboard 명령어 추가
|
||||||
|
6. 기존에 유효한 트러블슈팅, 코드 예제 등은 유지
|
||||||
|
|
||||||
|
**구현 결과:**
|
||||||
|
- 6개 문서 파일 업데이트
|
||||||
|
- 이전 시도(2개 커밋)는 기존 내용을 과도하게 삭제하여 폐기, main 기준으로 재작업
|
||||||
|
|
||||||
|
**이슈/PR:** #131, PR #134
|
||||||
|
|||||||
@@ -34,6 +34,12 @@ python -m src.main --mode=paper
|
|||||||
```
|
```
|
||||||
Runs the agent in paper-trading mode (no real orders).
|
Runs the agent in paper-trading mode (no real orders).
|
||||||
|
|
||||||
|
### Start Trading Agent with Dashboard
|
||||||
|
```bash
|
||||||
|
python -m src.main --mode=paper --dashboard
|
||||||
|
```
|
||||||
|
Runs the agent with FastAPI dashboard on `127.0.0.1:8080` (configurable via `DASHBOARD_HOST`/`DASHBOARD_PORT`).
|
||||||
|
|
||||||
### Start Trading Agent (Production)
|
### Start Trading Agent (Production)
|
||||||
```bash
|
```bash
|
||||||
docker compose up -d ouroboros
|
docker compose up -d ouroboros
|
||||||
@@ -59,7 +65,7 @@ Analyze the last 30 days of trade logs and generate performance metrics.
|
|||||||
python -m src.evolution.optimizer --evolve
|
python -m src.evolution.optimizer --evolve
|
||||||
```
|
```
|
||||||
Triggers the evolution engine to:
|
Triggers the evolution engine to:
|
||||||
1. Analyze `trade_logs.db` for failing patterns
|
1. Analyze `trades.db` for failing patterns
|
||||||
2. Ask Gemini to generate a new strategy
|
2. Ask Gemini to generate a new strategy
|
||||||
3. Run tests on the new strategy
|
3. Run tests on the new strategy
|
||||||
4. Create a PR if tests pass
|
4. Create a PR if tests pass
|
||||||
@@ -91,12 +97,12 @@ curl http://localhost:8080/health
|
|||||||
|
|
||||||
### View Trade Logs
|
### View Trade Logs
|
||||||
```bash
|
```bash
|
||||||
sqlite3 data/trade_logs.db "SELECT * FROM trades ORDER BY timestamp DESC LIMIT 20;"
|
sqlite3 data/trades.db "SELECT * FROM trades ORDER BY timestamp DESC LIMIT 20;"
|
||||||
```
|
```
|
||||||
|
|
||||||
### Export Trade History
|
### Export Trade History
|
||||||
```bash
|
```bash
|
||||||
sqlite3 -header -csv data/trade_logs.db "SELECT * FROM trades;" > trades_export.csv
|
sqlite3 -header -csv data/trades.db "SELECT * FROM trades;" > trades_export.csv
|
||||||
```
|
```
|
||||||
|
|
||||||
## Safety Checklist (Pre-Deploy)
|
## Safety Checklist (Pre-Deploy)
|
||||||
|
|||||||
206
docs/testing.md
206
docs/testing.md
@@ -2,51 +2,29 @@
|
|||||||
|
|
||||||
## Test Structure
|
## Test Structure
|
||||||
|
|
||||||
**54 tests** across four files. `asyncio_mode = "auto"` in pyproject.toml — async tests need no special decorator.
|
**551 tests** across **25 files**. `asyncio_mode = "auto"` in pyproject.toml — async tests need no special decorator.
|
||||||
|
|
||||||
The `settings` fixture in `conftest.py` provides safe defaults with test credentials and in-memory DB.
|
The `settings` fixture in `conftest.py` provides safe defaults with test credentials and in-memory DB.
|
||||||
|
|
||||||
### Test Files
|
### Test Files
|
||||||
|
|
||||||
#### `tests/test_risk.py` (11 tests)
|
#### Core Components
|
||||||
- Circuit breaker boundaries
|
|
||||||
- Fat-finger edge cases
|
##### `tests/test_risk.py` (14 tests)
|
||||||
|
- Circuit breaker boundaries and exact threshold triggers
|
||||||
|
- Fat-finger edge cases and percentage validation
|
||||||
- P&L calculation edge cases
|
- P&L calculation edge cases
|
||||||
- Order validation logic
|
- Order validation logic
|
||||||
|
|
||||||
**Example:**
|
##### `tests/test_broker.py` (11 tests)
|
||||||
```python
|
|
||||||
def test_circuit_breaker_exact_threshold(risk_manager):
|
|
||||||
"""Circuit breaker should trip at exactly -3.0%."""
|
|
||||||
with pytest.raises(CircuitBreakerTripped):
|
|
||||||
risk_manager.validate_order(
|
|
||||||
current_pnl_pct=-3.0,
|
|
||||||
order_amount=1000,
|
|
||||||
total_cash=10000
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
#### `tests/test_broker.py` (6 tests)
|
|
||||||
- OAuth token lifecycle
|
- OAuth token lifecycle
|
||||||
- Rate limiting enforcement
|
- Rate limiting enforcement
|
||||||
- Hash key generation
|
- Hash key generation
|
||||||
- Network error handling
|
- Network error handling
|
||||||
- SSL context configuration
|
- SSL context configuration
|
||||||
|
|
||||||
**Example:**
|
##### `tests/test_brain.py` (24 tests)
|
||||||
```python
|
- Valid JSON parsing and markdown-wrapped JSON handling
|
||||||
async def test_rate_limiter(broker):
|
|
||||||
"""Rate limiter should delay requests to stay under 10 RPS."""
|
|
||||||
start = time.monotonic()
|
|
||||||
for _ in range(15): # 15 requests
|
|
||||||
await broker._rate_limiter.acquire()
|
|
||||||
elapsed = time.monotonic() - start
|
|
||||||
assert elapsed >= 1.0 # Should take at least 1 second
|
|
||||||
```
|
|
||||||
|
|
||||||
#### `tests/test_brain.py` (18 tests)
|
|
||||||
- Valid JSON parsing
|
|
||||||
- Markdown-wrapped JSON handling
|
|
||||||
- Malformed JSON fallback
|
- Malformed JSON fallback
|
||||||
- Missing fields handling
|
- Missing fields handling
|
||||||
- Invalid action validation
|
- Invalid action validation
|
||||||
@@ -54,33 +32,143 @@ async def test_rate_limiter(broker):
|
|||||||
- Empty response handling
|
- Empty response handling
|
||||||
- Prompt construction for different markets
|
- Prompt construction for different markets
|
||||||
|
|
||||||
**Example:**
|
##### `tests/test_market_schedule.py` (24 tests)
|
||||||
```python
|
|
||||||
async def test_confidence_below_threshold_forces_hold(brain):
|
|
||||||
"""Decisions below confidence threshold should force HOLD."""
|
|
||||||
decision = brain.parse_response('{"action":"BUY","confidence":70,"rationale":"test"}')
|
|
||||||
assert decision.action == "HOLD"
|
|
||||||
assert decision.confidence == 70
|
|
||||||
```
|
|
||||||
|
|
||||||
#### `tests/test_market_schedule.py` (19 tests)
|
|
||||||
- Market open/close logic
|
- Market open/close logic
|
||||||
- Timezone handling (UTC, Asia/Seoul, America/New_York, etc.)
|
- Timezone handling (UTC, Asia/Seoul, America/New_York, etc.)
|
||||||
- DST (Daylight Saving Time) transitions
|
- DST (Daylight Saving Time) transitions
|
||||||
- Weekend handling
|
- Weekend handling and lunch break logic
|
||||||
- Lunch break logic
|
|
||||||
- Multiple market filtering
|
- Multiple market filtering
|
||||||
- Next market open calculation
|
- Next market open calculation
|
||||||
|
|
||||||
**Example:**
|
##### `tests/test_db.py` (3 tests)
|
||||||
```python
|
- Database initialization and table creation
|
||||||
def test_is_market_open_during_trading_hours():
|
- Trade logging with all fields (market, exchange_code, decision_id)
|
||||||
"""Market should be open during regular trading hours."""
|
- Query and retrieval operations
|
||||||
# KRX: 9:00-15:30 KST, no lunch break
|
|
||||||
market = MARKETS["KR"]
|
##### `tests/test_main.py` (37 tests)
|
||||||
trading_time = datetime(2026, 2, 3, 10, 0, tzinfo=ZoneInfo("Asia/Seoul")) # Monday 10:00
|
- Trading loop orchestration
|
||||||
assert is_market_open(market, trading_time) is True
|
- Market iteration and stock processing
|
||||||
```
|
- Dashboard integration (`--dashboard` flag)
|
||||||
|
- Telegram command handler wiring
|
||||||
|
- Error handling and graceful shutdown
|
||||||
|
|
||||||
|
#### Strategy & Playbook (v2)
|
||||||
|
|
||||||
|
##### `tests/test_pre_market_planner.py` (37 tests)
|
||||||
|
- Pre-market playbook generation
|
||||||
|
- Gemini API integration for scenario creation
|
||||||
|
- Timeout handling and defensive playbook fallback
|
||||||
|
- Multi-market playbook generation
|
||||||
|
|
||||||
|
##### `tests/test_scenario_engine.py` (44 tests)
|
||||||
|
- Scenario matching against live market data
|
||||||
|
- Confidence scoring and threshold filtering
|
||||||
|
- Multiple scenario type handling
|
||||||
|
- Edge cases (no match, partial match, expired scenarios)
|
||||||
|
|
||||||
|
##### `tests/test_playbook_store.py` (23 tests)
|
||||||
|
- Playbook persistence to SQLite
|
||||||
|
- Date-based retrieval and market filtering
|
||||||
|
- Playbook status management (generated, active, expired)
|
||||||
|
- JSON serialization/deserialization
|
||||||
|
|
||||||
|
##### `tests/test_strategy_models.py` (33 tests)
|
||||||
|
- Pydantic model validation for scenarios, playbooks, decisions
|
||||||
|
- Field constraints and default values
|
||||||
|
- Serialization round-trips
|
||||||
|
|
||||||
|
#### Analysis & Scanning
|
||||||
|
|
||||||
|
##### `tests/test_volatility.py` (24 tests)
|
||||||
|
- ATR and RSI calculation accuracy
|
||||||
|
- Volume surge ratio computation
|
||||||
|
- Momentum scoring
|
||||||
|
- Breakout/breakdown pattern detection
|
||||||
|
- Market scanner watchlist management
|
||||||
|
|
||||||
|
##### `tests/test_smart_scanner.py` (13 tests)
|
||||||
|
- Python-first filtering pipeline
|
||||||
|
- RSI and volume ratio filter logic
|
||||||
|
- Candidate scoring and ranking
|
||||||
|
- Fallback to static watchlist
|
||||||
|
|
||||||
|
#### Context & Memory
|
||||||
|
|
||||||
|
##### `tests/test_context.py` (18 tests)
|
||||||
|
- L1-L7 layer storage and retrieval
|
||||||
|
- Context key-value CRUD operations
|
||||||
|
- Timeframe-based queries
|
||||||
|
- Layer metadata management
|
||||||
|
|
||||||
|
##### `tests/test_context_scheduler.py` (5 tests)
|
||||||
|
- Periodic context aggregation scheduling
|
||||||
|
- Layer summarization triggers
|
||||||
|
|
||||||
|
#### Evolution & Review
|
||||||
|
|
||||||
|
##### `tests/test_evolution.py` (24 tests)
|
||||||
|
- Strategy optimization loop
|
||||||
|
- High-confidence losing trade analysis
|
||||||
|
- Generated strategy validation
|
||||||
|
|
||||||
|
##### `tests/test_daily_review.py` (10 tests)
|
||||||
|
- End-of-day review generation
|
||||||
|
- Trade performance summarization
|
||||||
|
- Context layer (L6_DAILY) integration
|
||||||
|
|
||||||
|
##### `tests/test_scorecard.py` (3 tests)
|
||||||
|
- Daily scorecard metrics calculation
|
||||||
|
- Win rate, P&L, confidence tracking
|
||||||
|
|
||||||
|
#### Notifications & Commands
|
||||||
|
|
||||||
|
##### `tests/test_telegram.py` (25 tests)
|
||||||
|
- Message sending and formatting
|
||||||
|
- Rate limiting (leaky bucket)
|
||||||
|
- Error handling (network timeout, invalid token)
|
||||||
|
- Auto-disable on missing credentials
|
||||||
|
- Notification types (trade, circuit breaker, fat-finger, market events)
|
||||||
|
|
||||||
|
##### `tests/test_telegram_commands.py` (31 tests)
|
||||||
|
- 9 command handlers (/help, /status, /positions, /report, /scenarios, /review, /dashboard, /stop, /resume)
|
||||||
|
- Long polling and command dispatch
|
||||||
|
- Authorization filtering by chat_id
|
||||||
|
- Command response formatting
|
||||||
|
|
||||||
|
#### Dashboard
|
||||||
|
|
||||||
|
##### `tests/test_dashboard.py` (14 tests)
|
||||||
|
- FastAPI endpoint responses (8 API routes)
|
||||||
|
- Status, playbook, scorecard, performance, context, decisions, scenarios
|
||||||
|
- Query parameter handling (market, date, limit)
|
||||||
|
|
||||||
|
#### Performance & Quality
|
||||||
|
|
||||||
|
##### `tests/test_token_efficiency.py` (34 tests)
|
||||||
|
- Gemini token usage optimization
|
||||||
|
- Prompt size reduction verification
|
||||||
|
- Cache effectiveness
|
||||||
|
|
||||||
|
##### `tests/test_latency_control.py` (30 tests)
|
||||||
|
- API call latency measurement
|
||||||
|
- Rate limiter timing accuracy
|
||||||
|
- Async operation overhead
|
||||||
|
|
||||||
|
##### `tests/test_decision_logger.py` (9 tests)
|
||||||
|
- Decision audit trail completeness
|
||||||
|
- Context snapshot capture
|
||||||
|
- Outcome tracking (P&L, accuracy)
|
||||||
|
|
||||||
|
##### `tests/test_data_integration.py` (38 tests)
|
||||||
|
- External data source integration
|
||||||
|
- News API, market data, economic calendar
|
||||||
|
- Error handling for API failures
|
||||||
|
|
||||||
|
##### `tests/test_backup.py` (23 tests)
|
||||||
|
- Backup scheduler and execution
|
||||||
|
- Cloud storage (S3) upload
|
||||||
|
- Health monitoring
|
||||||
|
- Data export functionality
|
||||||
|
|
||||||
## Coverage Requirements
|
## Coverage Requirements
|
||||||
|
|
||||||
@@ -91,20 +179,6 @@ Check coverage:
|
|||||||
pytest -v --cov=src --cov-report=term-missing
|
pytest -v --cov=src --cov-report=term-missing
|
||||||
```
|
```
|
||||||
|
|
||||||
Expected output:
|
|
||||||
```
|
|
||||||
Name Stmts Miss Cover Missing
|
|
||||||
-----------------------------------------------------------
|
|
||||||
src/brain/gemini_client.py 85 5 94% 165-169
|
|
||||||
src/broker/kis_api.py 120 12 90% ...
|
|
||||||
src/core/risk_manager.py 35 2 94% ...
|
|
||||||
src/db.py 25 1 96% ...
|
|
||||||
src/main.py 150 80 47% (excluded from CI)
|
|
||||||
src/markets/schedule.py 95 3 97% ...
|
|
||||||
-----------------------------------------------------------
|
|
||||||
TOTAL 510 103 80%
|
|
||||||
```
|
|
||||||
|
|
||||||
**Note:** `main.py` has lower coverage as it contains the main loop which is tested via integration/manual testing.
|
**Note:** `main.py` has lower coverage as it contains the main loop which is tested via integration/manual testing.
|
||||||
|
|
||||||
## Test Configuration
|
## Test Configuration
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ dependencies = [
|
|||||||
"pydantic-settings>=2.1,<3",
|
"pydantic-settings>=2.1,<3",
|
||||||
"google-genai>=1.0,<2",
|
"google-genai>=1.0,<2",
|
||||||
"scipy>=1.11,<2",
|
"scipy>=1.11,<2",
|
||||||
|
"fastapi>=0.110,<1",
|
||||||
|
"uvicorn>=0.29,<1",
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
|
|||||||
@@ -83,6 +83,11 @@ class Settings(BaseSettings):
|
|||||||
TELEGRAM_COMMANDS_ENABLED: bool = True
|
TELEGRAM_COMMANDS_ENABLED: bool = True
|
||||||
TELEGRAM_POLLING_INTERVAL: float = 1.0 # seconds
|
TELEGRAM_POLLING_INTERVAL: float = 1.0 # seconds
|
||||||
|
|
||||||
|
# Dashboard (optional)
|
||||||
|
DASHBOARD_ENABLED: bool = False
|
||||||
|
DASHBOARD_HOST: str = "127.0.0.1"
|
||||||
|
DASHBOARD_PORT: int = Field(default=8080, ge=1, le=65535)
|
||||||
|
|
||||||
model_config = {"env_file": ".env", "env_file_encoding": "utf-8"}
|
model_config = {"env_file": ".env", "env_file_encoding": "utf-8"}
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@@ -96,4 +101,7 @@ class Settings(BaseSettings):
|
|||||||
@property
|
@property
|
||||||
def enabled_market_list(self) -> list[str]:
|
def enabled_market_list(self) -> list[str]:
|
||||||
"""Parse ENABLED_MARKETS into list of market codes."""
|
"""Parse ENABLED_MARKETS into list of market codes."""
|
||||||
return [m.strip() for m in self.ENABLED_MARKETS.split(",") if m.strip()]
|
from src.markets.schedule import expand_market_codes
|
||||||
|
|
||||||
|
raw = [m.strip() for m in self.ENABLED_MARKETS.split(",") if m.strip()]
|
||||||
|
return expand_market_codes(raw)
|
||||||
|
|||||||
5
src/dashboard/__init__.py
Normal file
5
src/dashboard/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
"""FastAPI dashboard package for observability APIs."""
|
||||||
|
|
||||||
|
from src.dashboard.app import create_dashboard_app
|
||||||
|
|
||||||
|
__all__ = ["create_dashboard_app"]
|
||||||
361
src/dashboard/app.py
Normal file
361
src/dashboard/app.py
Normal file
@@ -0,0 +1,361 @@
|
|||||||
|
"""FastAPI application for observability dashboard endpoints."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sqlite3
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import FastAPI, HTTPException, Query
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
|
||||||
|
|
||||||
|
def create_dashboard_app(db_path: str) -> FastAPI:
|
||||||
|
"""Create dashboard FastAPI app bound to a SQLite database path."""
|
||||||
|
app = FastAPI(title="The Ouroboros Dashboard", version="1.0.0")
|
||||||
|
app.state.db_path = db_path
|
||||||
|
|
||||||
|
@app.get("/")
|
||||||
|
def index() -> FileResponse:
|
||||||
|
index_path = Path(__file__).parent / "static" / "index.html"
|
||||||
|
return FileResponse(index_path)
|
||||||
|
|
||||||
|
@app.get("/api/status")
|
||||||
|
def get_status() -> dict[str, Any]:
|
||||||
|
today = datetime.now(UTC).date().isoformat()
|
||||||
|
with _connect(db_path) as conn:
|
||||||
|
market_rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT DISTINCT market FROM (
|
||||||
|
SELECT market FROM trades WHERE DATE(timestamp) = ?
|
||||||
|
UNION
|
||||||
|
SELECT market FROM decision_logs WHERE DATE(timestamp) = ?
|
||||||
|
UNION
|
||||||
|
SELECT market FROM playbooks WHERE date = ?
|
||||||
|
) ORDER BY market
|
||||||
|
""",
|
||||||
|
(today, today, today),
|
||||||
|
).fetchall()
|
||||||
|
markets = [row[0] for row in market_rows] if market_rows else []
|
||||||
|
market_status: dict[str, Any] = {}
|
||||||
|
total_trades = 0
|
||||||
|
total_pnl = 0.0
|
||||||
|
total_decisions = 0
|
||||||
|
for market in markets:
|
||||||
|
trade_row = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT COUNT(*) AS c, COALESCE(SUM(pnl), 0.0) AS p
|
||||||
|
FROM trades
|
||||||
|
WHERE DATE(timestamp) = ? AND market = ?
|
||||||
|
""",
|
||||||
|
(today, market),
|
||||||
|
).fetchone()
|
||||||
|
decision_row = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT COUNT(*) AS c
|
||||||
|
FROM decision_logs
|
||||||
|
WHERE DATE(timestamp) = ? AND market = ?
|
||||||
|
""",
|
||||||
|
(today, market),
|
||||||
|
).fetchone()
|
||||||
|
playbook_row = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT status
|
||||||
|
FROM playbooks
|
||||||
|
WHERE date = ? AND market = ?
|
||||||
|
LIMIT 1
|
||||||
|
""",
|
||||||
|
(today, market),
|
||||||
|
).fetchone()
|
||||||
|
market_status[market] = {
|
||||||
|
"trade_count": int(trade_row["c"] if trade_row else 0),
|
||||||
|
"total_pnl": float(trade_row["p"] if trade_row else 0.0),
|
||||||
|
"decision_count": int(decision_row["c"] if decision_row else 0),
|
||||||
|
"playbook_status": playbook_row["status"] if playbook_row else None,
|
||||||
|
}
|
||||||
|
total_trades += market_status[market]["trade_count"]
|
||||||
|
total_pnl += market_status[market]["total_pnl"]
|
||||||
|
total_decisions += market_status[market]["decision_count"]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"date": today,
|
||||||
|
"markets": market_status,
|
||||||
|
"totals": {
|
||||||
|
"trade_count": total_trades,
|
||||||
|
"total_pnl": round(total_pnl, 2),
|
||||||
|
"decision_count": total_decisions,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
@app.get("/api/playbook/{date_str}")
|
||||||
|
def get_playbook(date_str: str, market: str = Query("KR")) -> dict[str, Any]:
|
||||||
|
with _connect(db_path) as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT date, market, status, playbook_json, generated_at,
|
||||||
|
token_count, scenario_count, match_count
|
||||||
|
FROM playbooks
|
||||||
|
WHERE date = ? AND market = ?
|
||||||
|
""",
|
||||||
|
(date_str, market),
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise HTTPException(status_code=404, detail="playbook not found")
|
||||||
|
return {
|
||||||
|
"date": row["date"],
|
||||||
|
"market": row["market"],
|
||||||
|
"status": row["status"],
|
||||||
|
"playbook": json.loads(row["playbook_json"]),
|
||||||
|
"generated_at": row["generated_at"],
|
||||||
|
"token_count": row["token_count"],
|
||||||
|
"scenario_count": row["scenario_count"],
|
||||||
|
"match_count": row["match_count"],
|
||||||
|
}
|
||||||
|
|
||||||
|
@app.get("/api/scorecard/{date_str}")
|
||||||
|
def get_scorecard(date_str: str, market: str = Query("KR")) -> dict[str, Any]:
|
||||||
|
key = f"scorecard_{market}"
|
||||||
|
with _connect(db_path) as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT value
|
||||||
|
FROM contexts
|
||||||
|
WHERE layer = 'L6_DAILY' AND timeframe = ? AND key = ?
|
||||||
|
""",
|
||||||
|
(date_str, key),
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise HTTPException(status_code=404, detail="scorecard not found")
|
||||||
|
return {"date": date_str, "market": market, "scorecard": json.loads(row["value"])}
|
||||||
|
|
||||||
|
@app.get("/api/performance")
|
||||||
|
def get_performance(market: str = Query("all")) -> dict[str, Any]:
|
||||||
|
with _connect(db_path) as conn:
|
||||||
|
if market == "all":
|
||||||
|
by_market_rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT market,
|
||||||
|
COUNT(*) AS total_trades,
|
||||||
|
SUM(CASE WHEN pnl > 0 THEN 1 ELSE 0 END) AS wins,
|
||||||
|
SUM(CASE WHEN pnl < 0 THEN 1 ELSE 0 END) AS losses,
|
||||||
|
COALESCE(SUM(pnl), 0.0) AS total_pnl,
|
||||||
|
COALESCE(AVG(confidence), 0.0) AS avg_confidence
|
||||||
|
FROM trades
|
||||||
|
GROUP BY market
|
||||||
|
ORDER BY market
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
combined = _performance_from_rows(by_market_rows)
|
||||||
|
return {
|
||||||
|
"market": "all",
|
||||||
|
"combined": combined,
|
||||||
|
"by_market": [
|
||||||
|
_row_to_performance(row)
|
||||||
|
for row in by_market_rows
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT market,
|
||||||
|
COUNT(*) AS total_trades,
|
||||||
|
SUM(CASE WHEN pnl > 0 THEN 1 ELSE 0 END) AS wins,
|
||||||
|
SUM(CASE WHEN pnl < 0 THEN 1 ELSE 0 END) AS losses,
|
||||||
|
COALESCE(SUM(pnl), 0.0) AS total_pnl,
|
||||||
|
COALESCE(AVG(confidence), 0.0) AS avg_confidence
|
||||||
|
FROM trades
|
||||||
|
WHERE market = ?
|
||||||
|
GROUP BY market
|
||||||
|
""",
|
||||||
|
(market,),
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
return {"market": market, "metrics": _empty_performance(market)}
|
||||||
|
return {"market": market, "metrics": _row_to_performance(row)}
|
||||||
|
|
||||||
|
@app.get("/api/context/{layer}")
|
||||||
|
def get_context_layer(
|
||||||
|
layer: str,
|
||||||
|
timeframe: str | None = Query(default=None),
|
||||||
|
limit: int = Query(default=100, ge=1, le=1000),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
with _connect(db_path) as conn:
|
||||||
|
if timeframe is None:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT timeframe, key, value, updated_at
|
||||||
|
FROM contexts
|
||||||
|
WHERE layer = ?
|
||||||
|
ORDER BY updated_at DESC
|
||||||
|
LIMIT ?
|
||||||
|
""",
|
||||||
|
(layer, limit),
|
||||||
|
).fetchall()
|
||||||
|
else:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT timeframe, key, value, updated_at
|
||||||
|
FROM contexts
|
||||||
|
WHERE layer = ? AND timeframe = ?
|
||||||
|
ORDER BY key
|
||||||
|
LIMIT ?
|
||||||
|
""",
|
||||||
|
(layer, timeframe, limit),
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
entries = [
|
||||||
|
{
|
||||||
|
"timeframe": row["timeframe"],
|
||||||
|
"key": row["key"],
|
||||||
|
"value": json.loads(row["value"]),
|
||||||
|
"updated_at": row["updated_at"],
|
||||||
|
}
|
||||||
|
for row in rows
|
||||||
|
]
|
||||||
|
return {
|
||||||
|
"layer": layer,
|
||||||
|
"timeframe": timeframe,
|
||||||
|
"count": len(entries),
|
||||||
|
"entries": entries,
|
||||||
|
}
|
||||||
|
|
||||||
|
@app.get("/api/decisions")
|
||||||
|
def get_decisions(
|
||||||
|
market: str = Query("KR"),
|
||||||
|
limit: int = Query(default=50, ge=1, le=500),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
with _connect(db_path) as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT decision_id, timestamp, stock_code, market, exchange_code,
|
||||||
|
action, confidence, rationale, context_snapshot, input_data,
|
||||||
|
outcome_pnl, outcome_accuracy
|
||||||
|
FROM decision_logs
|
||||||
|
WHERE market = ?
|
||||||
|
ORDER BY timestamp DESC
|
||||||
|
LIMIT ?
|
||||||
|
""",
|
||||||
|
(market, limit),
|
||||||
|
).fetchall()
|
||||||
|
decisions = []
|
||||||
|
for row in rows:
|
||||||
|
decisions.append(
|
||||||
|
{
|
||||||
|
"decision_id": row["decision_id"],
|
||||||
|
"timestamp": row["timestamp"],
|
||||||
|
"stock_code": row["stock_code"],
|
||||||
|
"market": row["market"],
|
||||||
|
"exchange_code": row["exchange_code"],
|
||||||
|
"action": row["action"],
|
||||||
|
"confidence": row["confidence"],
|
||||||
|
"rationale": row["rationale"],
|
||||||
|
"context_snapshot": json.loads(row["context_snapshot"]),
|
||||||
|
"input_data": json.loads(row["input_data"]),
|
||||||
|
"outcome_pnl": row["outcome_pnl"],
|
||||||
|
"outcome_accuracy": row["outcome_accuracy"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return {"market": market, "count": len(decisions), "decisions": decisions}
|
||||||
|
|
||||||
|
@app.get("/api/scenarios/active")
|
||||||
|
def get_active_scenarios(
|
||||||
|
market: str = Query("US"),
|
||||||
|
date_str: str | None = Query(default=None),
|
||||||
|
limit: int = Query(default=50, ge=1, le=500),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
if date_str is None:
|
||||||
|
date_str = datetime.now(UTC).date().isoformat()
|
||||||
|
|
||||||
|
with _connect(db_path) as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT timestamp, stock_code, action, confidence, rationale, context_snapshot
|
||||||
|
FROM decision_logs
|
||||||
|
WHERE market = ? AND DATE(timestamp) = ?
|
||||||
|
ORDER BY timestamp DESC
|
||||||
|
LIMIT ?
|
||||||
|
""",
|
||||||
|
(market, date_str, limit),
|
||||||
|
).fetchall()
|
||||||
|
matches: list[dict[str, Any]] = []
|
||||||
|
for row in rows:
|
||||||
|
snapshot = json.loads(row["context_snapshot"])
|
||||||
|
scenario_match = snapshot.get("scenario_match", {})
|
||||||
|
if not isinstance(scenario_match, dict) or not scenario_match:
|
||||||
|
continue
|
||||||
|
matches.append(
|
||||||
|
{
|
||||||
|
"timestamp": row["timestamp"],
|
||||||
|
"stock_code": row["stock_code"],
|
||||||
|
"action": row["action"],
|
||||||
|
"confidence": row["confidence"],
|
||||||
|
"rationale": row["rationale"],
|
||||||
|
"scenario_match": scenario_match,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return {"market": market, "date": date_str, "count": len(matches), "matches": matches}
|
||||||
|
|
||||||
|
return app
|
||||||
|
|
||||||
|
|
||||||
|
def _connect(db_path: str) -> sqlite3.Connection:
|
||||||
|
conn = sqlite3.connect(db_path)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
return conn
|
||||||
|
|
||||||
|
|
||||||
|
def _row_to_performance(row: sqlite3.Row) -> dict[str, Any]:
|
||||||
|
wins = int(row["wins"] or 0)
|
||||||
|
losses = int(row["losses"] or 0)
|
||||||
|
total = int(row["total_trades"] or 0)
|
||||||
|
win_rate = round((wins / (wins + losses) * 100), 2) if (wins + losses) > 0 else 0.0
|
||||||
|
return {
|
||||||
|
"market": row["market"],
|
||||||
|
"total_trades": total,
|
||||||
|
"wins": wins,
|
||||||
|
"losses": losses,
|
||||||
|
"win_rate": win_rate,
|
||||||
|
"total_pnl": round(float(row["total_pnl"] or 0.0), 2),
|
||||||
|
"avg_confidence": round(float(row["avg_confidence"] or 0.0), 2),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _performance_from_rows(rows: list[sqlite3.Row]) -> dict[str, Any]:
|
||||||
|
total_trades = 0
|
||||||
|
wins = 0
|
||||||
|
losses = 0
|
||||||
|
total_pnl = 0.0
|
||||||
|
confidence_weighted = 0.0
|
||||||
|
for row in rows:
|
||||||
|
market_total = int(row["total_trades"] or 0)
|
||||||
|
market_conf = float(row["avg_confidence"] or 0.0)
|
||||||
|
total_trades += market_total
|
||||||
|
wins += int(row["wins"] or 0)
|
||||||
|
losses += int(row["losses"] or 0)
|
||||||
|
total_pnl += float(row["total_pnl"] or 0.0)
|
||||||
|
confidence_weighted += market_total * market_conf
|
||||||
|
win_rate = round((wins / (wins + losses) * 100), 2) if (wins + losses) > 0 else 0.0
|
||||||
|
avg_confidence = round(confidence_weighted / total_trades, 2) if total_trades > 0 else 0.0
|
||||||
|
return {
|
||||||
|
"market": "all",
|
||||||
|
"total_trades": total_trades,
|
||||||
|
"wins": wins,
|
||||||
|
"losses": losses,
|
||||||
|
"win_rate": win_rate,
|
||||||
|
"total_pnl": round(total_pnl, 2),
|
||||||
|
"avg_confidence": avg_confidence,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _empty_performance(market: str) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"market": market,
|
||||||
|
"total_trades": 0,
|
||||||
|
"wins": 0,
|
||||||
|
"losses": 0,
|
||||||
|
"win_rate": 0.0,
|
||||||
|
"total_pnl": 0.0,
|
||||||
|
"avg_confidence": 0.0,
|
||||||
|
}
|
||||||
61
src/dashboard/static/index.html
Normal file
61
src/dashboard/static/index.html
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>The Ouroboros Dashboard</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--bg: #0b1724;
|
||||||
|
--panel: #12263a;
|
||||||
|
--fg: #e6eef7;
|
||||||
|
--muted: #9fb3c8;
|
||||||
|
--accent: #3cb371;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||||
|
background: radial-gradient(circle at top left, #173b58, var(--bg));
|
||||||
|
color: var(--fg);
|
||||||
|
}
|
||||||
|
.wrap {
|
||||||
|
max-width: 900px;
|
||||||
|
margin: 48px auto;
|
||||||
|
padding: 0 16px;
|
||||||
|
}
|
||||||
|
.card {
|
||||||
|
background: color-mix(in oklab, var(--panel), black 12%);
|
||||||
|
border: 1px solid #28455f;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
h1 {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
code {
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
li {
|
||||||
|
margin: 6px 0;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="wrap">
|
||||||
|
<div class="card">
|
||||||
|
<h1>The Ouroboros Dashboard API</h1>
|
||||||
|
<p>Use the following endpoints:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>/api/status</code></li>
|
||||||
|
<li><code>/api/playbook/{date}?market=KR</code></li>
|
||||||
|
<li><code>/api/scorecard/{date}?market=KR</code></li>
|
||||||
|
<li><code>/api/performance?market=all</code></li>
|
||||||
|
<li><code>/api/context/{layer}</code></li>
|
||||||
|
<li><code>/api/decisions?market=KR</code></li>
|
||||||
|
<li><code>/api/scenarios/active?market=US</code></li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
21
src/db.py
21
src/db.py
@@ -214,3 +214,24 @@ def get_latest_buy_trade(
|
|||||||
if not row:
|
if not row:
|
||||||
return None
|
return None
|
||||||
return {"decision_id": row[0], "price": row[1], "quantity": row[2]}
|
return {"decision_id": row[0], "price": row[1], "quantity": row[2]}
|
||||||
|
|
||||||
|
|
||||||
|
def get_open_position(
|
||||||
|
conn: sqlite3.Connection, stock_code: str, market: str
|
||||||
|
) -> dict[str, Any] | None:
|
||||||
|
"""Return open position if latest trade is BUY, else None."""
|
||||||
|
cursor = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT action, decision_id, price, quantity
|
||||||
|
FROM trades
|
||||||
|
WHERE stock_code = ?
|
||||||
|
AND market = ?
|
||||||
|
ORDER BY timestamp DESC
|
||||||
|
LIMIT 1
|
||||||
|
""",
|
||||||
|
(stock_code, market),
|
||||||
|
)
|
||||||
|
row = cursor.fetchone()
|
||||||
|
if not row or row[0] != "BUY":
|
||||||
|
return None
|
||||||
|
return {"decision_id": row[1], "price": row[2], "quantity": row[3]}
|
||||||
|
|||||||
329
src/main.py
329
src/main.py
@@ -8,8 +8,10 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import json
|
||||||
import logging
|
import logging
|
||||||
import signal
|
import signal
|
||||||
|
import threading
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -22,12 +24,14 @@ from src.broker.overseas import OverseasBroker
|
|||||||
from src.config import Settings
|
from src.config import Settings
|
||||||
from src.context.aggregator import ContextAggregator
|
from src.context.aggregator import ContextAggregator
|
||||||
from src.context.layer import ContextLayer
|
from src.context.layer import ContextLayer
|
||||||
|
from src.context.scheduler import ContextScheduler
|
||||||
from src.context.store import ContextStore
|
from src.context.store import ContextStore
|
||||||
from src.core.criticality import CriticalityAssessor
|
from src.core.criticality import CriticalityAssessor
|
||||||
from src.core.priority_queue import PriorityTaskQueue
|
from src.core.priority_queue import PriorityTaskQueue
|
||||||
from src.core.risk_manager import CircuitBreakerTripped, FatFingerRejected, RiskManager
|
from src.core.risk_manager import CircuitBreakerTripped, FatFingerRejected, RiskManager
|
||||||
from src.db import get_latest_buy_trade, init_db, log_trade
|
from src.db import get_latest_buy_trade, get_open_position, init_db, log_trade
|
||||||
from src.evolution.daily_review import DailyReviewer
|
from src.evolution.daily_review import DailyReviewer
|
||||||
|
from src.evolution.optimizer import EvolutionOptimizer
|
||||||
from src.logging.decision_logger import DecisionLogger
|
from src.logging.decision_logger import DecisionLogger
|
||||||
from src.logging_config import setup_logging
|
from src.logging_config import setup_logging
|
||||||
from src.markets.schedule import MarketInfo, get_next_market_open, get_open_markets
|
from src.markets.schedule import MarketInfo, get_next_market_open, get_open_markets
|
||||||
@@ -111,6 +115,7 @@ async def trading_cycle(
|
|||||||
|
|
||||||
current_price = safe_float(orderbook.get("output1", {}).get("stck_prpr", "0"))
|
current_price = safe_float(orderbook.get("output1", {}).get("stck_prpr", "0"))
|
||||||
foreigner_net = safe_float(orderbook.get("output1", {}).get("frgn_ntby_qty", "0"))
|
foreigner_net = safe_float(orderbook.get("output1", {}).get("frgn_ntby_qty", "0"))
|
||||||
|
price_change_pct = safe_float(orderbook.get("output1", {}).get("prdy_ctrt", "0"))
|
||||||
else:
|
else:
|
||||||
# Overseas market
|
# Overseas market
|
||||||
price_data = await overseas_broker.get_overseas_price(
|
price_data = await overseas_broker.get_overseas_price(
|
||||||
@@ -133,6 +138,7 @@ async def trading_cycle(
|
|||||||
|
|
||||||
current_price = safe_float(price_data.get("output", {}).get("last", "0"))
|
current_price = safe_float(price_data.get("output", {}).get("last", "0"))
|
||||||
foreigner_net = 0.0 # Not available for overseas
|
foreigner_net = 0.0 # Not available for overseas
|
||||||
|
price_change_pct = safe_float(price_data.get("output", {}).get("rate", "0"))
|
||||||
|
|
||||||
# Calculate daily P&L %
|
# Calculate daily P&L %
|
||||||
pnl_pct = (
|
pnl_pct = (
|
||||||
@@ -146,6 +152,7 @@ async def trading_cycle(
|
|||||||
"market_name": market.name,
|
"market_name": market.name,
|
||||||
"current_price": current_price,
|
"current_price": current_price,
|
||||||
"foreigner_net": foreigner_net,
|
"foreigner_net": foreigner_net,
|
||||||
|
"price_change_pct": price_change_pct,
|
||||||
}
|
}
|
||||||
|
|
||||||
# Enrich market_data with scanner metrics for scenario engine
|
# Enrich market_data with scanner metrics for scenario engine
|
||||||
@@ -237,6 +244,34 @@ async def trading_cycle(
|
|||||||
confidence=match.confidence,
|
confidence=match.confidence,
|
||||||
rationale=match.rationale,
|
rationale=match.rationale,
|
||||||
)
|
)
|
||||||
|
stock_playbook = playbook.get_stock_playbook(stock_code)
|
||||||
|
|
||||||
|
if decision.action == "HOLD":
|
||||||
|
open_position = get_open_position(db_conn, stock_code, market.code)
|
||||||
|
if open_position:
|
||||||
|
entry_price = safe_float(open_position.get("price"), 0.0)
|
||||||
|
if entry_price > 0:
|
||||||
|
loss_pct = (current_price - entry_price) / entry_price * 100
|
||||||
|
stop_loss_threshold = -2.0
|
||||||
|
if stock_playbook and stock_playbook.scenarios:
|
||||||
|
stop_loss_threshold = stock_playbook.scenarios[0].stop_loss_pct
|
||||||
|
|
||||||
|
if loss_pct <= stop_loss_threshold:
|
||||||
|
decision = TradeDecision(
|
||||||
|
action="SELL",
|
||||||
|
confidence=95,
|
||||||
|
rationale=(
|
||||||
|
f"Stop-loss triggered ({loss_pct:.2f}% <= "
|
||||||
|
f"{stop_loss_threshold:.2f}%)"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Stop-loss override for %s (%s): %.2f%% <= %.2f%%",
|
||||||
|
stock_code,
|
||||||
|
market.name,
|
||||||
|
loss_pct,
|
||||||
|
stop_loss_threshold,
|
||||||
|
)
|
||||||
logger.info(
|
logger.info(
|
||||||
"Decision for %s (%s): %s (confidence=%d)",
|
"Decision for %s (%s): %s (confidence=%d)",
|
||||||
stock_code,
|
stock_code,
|
||||||
@@ -275,6 +310,7 @@ async def trading_cycle(
|
|||||||
input_data = {
|
input_data = {
|
||||||
"current_price": current_price,
|
"current_price": current_price,
|
||||||
"foreigner_net": foreigner_net,
|
"foreigner_net": foreigner_net,
|
||||||
|
"price_change_pct": price_change_pct,
|
||||||
"total_eval": total_eval,
|
"total_eval": total_eval,
|
||||||
"total_cash": total_cash,
|
"total_cash": total_cash,
|
||||||
"pnl_pct": pnl_pct,
|
"pnl_pct": pnl_pct,
|
||||||
@@ -504,6 +540,9 @@ async def run_daily_session(
|
|||||||
foreigner_net = safe_float(
|
foreigner_net = safe_float(
|
||||||
orderbook.get("output1", {}).get("frgn_ntby_qty", "0")
|
orderbook.get("output1", {}).get("frgn_ntby_qty", "0")
|
||||||
)
|
)
|
||||||
|
price_change_pct = safe_float(
|
||||||
|
orderbook.get("output1", {}).get("prdy_ctrt", "0")
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
price_data = await overseas_broker.get_overseas_price(
|
price_data = await overseas_broker.get_overseas_price(
|
||||||
market.exchange_code, stock_code
|
market.exchange_code, stock_code
|
||||||
@@ -512,12 +551,16 @@ async def run_daily_session(
|
|||||||
price_data.get("output", {}).get("last", "0")
|
price_data.get("output", {}).get("last", "0")
|
||||||
)
|
)
|
||||||
foreigner_net = 0.0
|
foreigner_net = 0.0
|
||||||
|
price_change_pct = safe_float(
|
||||||
|
price_data.get("output", {}).get("rate", "0")
|
||||||
|
)
|
||||||
|
|
||||||
stock_data: dict[str, Any] = {
|
stock_data: dict[str, Any] = {
|
||||||
"stock_code": stock_code,
|
"stock_code": stock_code,
|
||||||
"market_name": market.name,
|
"market_name": market.name,
|
||||||
"current_price": current_price,
|
"current_price": current_price,
|
||||||
"foreigner_net": foreigner_net,
|
"foreigner_net": foreigner_net,
|
||||||
|
"price_change_pct": price_change_pct,
|
||||||
}
|
}
|
||||||
# Enrich with scanner metrics
|
# Enrich with scanner metrics
|
||||||
cand = candidate_map.get(stock_code)
|
cand = candidate_map.get(stock_code)
|
||||||
@@ -744,6 +787,7 @@ async def _handle_market_close(
|
|||||||
telegram: TelegramClient,
|
telegram: TelegramClient,
|
||||||
context_aggregator: ContextAggregator,
|
context_aggregator: ContextAggregator,
|
||||||
daily_reviewer: DailyReviewer,
|
daily_reviewer: DailyReviewer,
|
||||||
|
evolution_optimizer: EvolutionOptimizer | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Handle market-close tasks: notify, aggregate, review, and store context."""
|
"""Handle market-close tasks: notify, aggregate, review, and store context."""
|
||||||
await telegram.notify_market_close(market_name, 0.0)
|
await telegram.notify_market_close(market_name, 0.0)
|
||||||
@@ -771,6 +815,117 @@ async def _handle_market_close(
|
|||||||
f"Lessons: {', '.join(scorecard.lessons) if scorecard.lessons else 'N/A'}"
|
f"Lessons: {', '.join(scorecard.lessons) if scorecard.lessons else 'N/A'}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if evolution_optimizer is not None:
|
||||||
|
await _run_evolution_loop(
|
||||||
|
evolution_optimizer=evolution_optimizer,
|
||||||
|
telegram=telegram,
|
||||||
|
market_code=market_code,
|
||||||
|
market_date=market_date,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _run_context_scheduler(
|
||||||
|
scheduler: ContextScheduler, now: datetime | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Run periodic context scheduler tasks and log when anything executes."""
|
||||||
|
result = scheduler.run_if_due(now=now)
|
||||||
|
if any(
|
||||||
|
[
|
||||||
|
result.weekly,
|
||||||
|
result.monthly,
|
||||||
|
result.quarterly,
|
||||||
|
result.annual,
|
||||||
|
result.legacy,
|
||||||
|
result.cleanup,
|
||||||
|
]
|
||||||
|
):
|
||||||
|
logger.info(
|
||||||
|
(
|
||||||
|
"Context scheduler ran (weekly=%s, monthly=%s, quarterly=%s, "
|
||||||
|
"annual=%s, legacy=%s, cleanup=%s)"
|
||||||
|
),
|
||||||
|
result.weekly,
|
||||||
|
result.monthly,
|
||||||
|
result.quarterly,
|
||||||
|
result.annual,
|
||||||
|
result.legacy,
|
||||||
|
result.cleanup,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def _run_evolution_loop(
|
||||||
|
evolution_optimizer: EvolutionOptimizer,
|
||||||
|
telegram: TelegramClient,
|
||||||
|
market_code: str,
|
||||||
|
market_date: str,
|
||||||
|
) -> None:
|
||||||
|
"""Run evolution loop once at US close (end of trading day)."""
|
||||||
|
if not market_code.startswith("US"):
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
pr_info = await evolution_optimizer.evolve()
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Evolution loop failed on %s: %s", market_date, exc)
|
||||||
|
return
|
||||||
|
|
||||||
|
if pr_info is None:
|
||||||
|
logger.info("Evolution loop skipped on %s (no actionable failures)", market_date)
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
await telegram.send_message(
|
||||||
|
"<b>Evolution Update</b>\n"
|
||||||
|
f"Date: {market_date}\n"
|
||||||
|
f"PR: {pr_info.get('title', 'N/A')}\n"
|
||||||
|
f"Branch: {pr_info.get('branch', 'N/A')}\n"
|
||||||
|
f"Status: {pr_info.get('status', 'N/A')}"
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Evolution notification failed on %s: %s", market_date, exc)
|
||||||
|
|
||||||
|
|
||||||
|
def _start_dashboard_server(settings: Settings) -> threading.Thread | None:
|
||||||
|
"""Start FastAPI dashboard in a daemon thread when enabled."""
|
||||||
|
if not settings.DASHBOARD_ENABLED:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _serve() -> None:
|
||||||
|
try:
|
||||||
|
import uvicorn
|
||||||
|
|
||||||
|
from src.dashboard import create_dashboard_app
|
||||||
|
|
||||||
|
app = create_dashboard_app(settings.DB_PATH)
|
||||||
|
uvicorn.run(
|
||||||
|
app,
|
||||||
|
host=settings.DASHBOARD_HOST,
|
||||||
|
port=settings.DASHBOARD_PORT,
|
||||||
|
log_level="info",
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Dashboard server failed to start: %s", exc)
|
||||||
|
|
||||||
|
thread = threading.Thread(
|
||||||
|
target=_serve,
|
||||||
|
name="dashboard-server",
|
||||||
|
daemon=True,
|
||||||
|
)
|
||||||
|
thread.start()
|
||||||
|
logger.info(
|
||||||
|
"Dashboard server started at http://%s:%d",
|
||||||
|
settings.DASHBOARD_HOST,
|
||||||
|
settings.DASHBOARD_PORT,
|
||||||
|
)
|
||||||
|
return thread
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_dashboard_flag(settings: Settings, dashboard_flag: bool) -> Settings:
|
||||||
|
"""Apply CLI dashboard flag over environment settings."""
|
||||||
|
if dashboard_flag and not settings.DASHBOARD_ENABLED:
|
||||||
|
return settings.model_copy(update={"DASHBOARD_ENABLED": True})
|
||||||
|
return settings
|
||||||
|
|
||||||
|
|
||||||
async def run(settings: Settings) -> None:
|
async def run(settings: Settings) -> None:
|
||||||
"""Main async loop — iterate over open markets on a timer."""
|
"""Main async loop — iterate over open markets on a timer."""
|
||||||
@@ -782,6 +937,11 @@ async def run(settings: Settings) -> None:
|
|||||||
decision_logger = DecisionLogger(db_conn)
|
decision_logger = DecisionLogger(db_conn)
|
||||||
context_store = ContextStore(db_conn)
|
context_store = ContextStore(db_conn)
|
||||||
context_aggregator = ContextAggregator(db_conn)
|
context_aggregator = ContextAggregator(db_conn)
|
||||||
|
context_scheduler = ContextScheduler(
|
||||||
|
aggregator=context_aggregator,
|
||||||
|
store=context_store,
|
||||||
|
)
|
||||||
|
evolution_optimizer = EvolutionOptimizer(settings)
|
||||||
|
|
||||||
# V2 proactive strategy components
|
# V2 proactive strategy components
|
||||||
context_selector = ContextSelector(context_store)
|
context_selector = ContextSelector(context_store)
|
||||||
@@ -816,6 +976,10 @@ async def run(settings: Settings) -> None:
|
|||||||
"/help - Show available commands\n"
|
"/help - Show available commands\n"
|
||||||
"/status - Trading status (mode, markets, P&L)\n"
|
"/status - Trading status (mode, markets, P&L)\n"
|
||||||
"/positions - Current holdings\n"
|
"/positions - Current holdings\n"
|
||||||
|
"/report - Daily summary report\n"
|
||||||
|
"/scenarios - Today's playbook scenarios\n"
|
||||||
|
"/review - Recent scorecards\n"
|
||||||
|
"/dashboard - Dashboard URL/status\n"
|
||||||
"/stop - Pause trading\n"
|
"/stop - Pause trading\n"
|
||||||
"/resume - Resume trading"
|
"/resume - Resume trading"
|
||||||
)
|
)
|
||||||
@@ -935,11 +1099,164 @@ async def run(settings: Settings) -> None:
|
|||||||
"<b>⚠️ Error</b>\n\nFailed to retrieve positions."
|
"<b>⚠️ Error</b>\n\nFailed to retrieve positions."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
async def handle_report() -> None:
|
||||||
|
"""Handle /report command - show daily summary metrics."""
|
||||||
|
try:
|
||||||
|
today = datetime.now(UTC).date().isoformat()
|
||||||
|
trade_row = db_conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT COUNT(*) AS trade_count,
|
||||||
|
COALESCE(SUM(pnl), 0.0) AS total_pnl,
|
||||||
|
SUM(CASE WHEN pnl > 0 THEN 1 ELSE 0 END) AS wins
|
||||||
|
FROM trades
|
||||||
|
WHERE DATE(timestamp) = ?
|
||||||
|
""",
|
||||||
|
(today,),
|
||||||
|
).fetchone()
|
||||||
|
decision_row = db_conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT COUNT(*) AS decision_count,
|
||||||
|
COALESCE(AVG(confidence), 0.0) AS avg_confidence
|
||||||
|
FROM decision_logs
|
||||||
|
WHERE DATE(timestamp) = ?
|
||||||
|
""",
|
||||||
|
(today,),
|
||||||
|
).fetchone()
|
||||||
|
|
||||||
|
trade_count = int(trade_row[0] if trade_row else 0)
|
||||||
|
total_pnl = float(trade_row[1] if trade_row else 0.0)
|
||||||
|
wins = int(trade_row[2] if trade_row and trade_row[2] is not None else 0)
|
||||||
|
decision_count = int(decision_row[0] if decision_row else 0)
|
||||||
|
avg_confidence = float(decision_row[1] if decision_row else 0.0)
|
||||||
|
win_rate = (wins / trade_count * 100.0) if trade_count > 0 else 0.0
|
||||||
|
|
||||||
|
await telegram.send_message(
|
||||||
|
"<b>📈 Daily Report</b>\n\n"
|
||||||
|
f"<b>Date:</b> {today}\n"
|
||||||
|
f"<b>Trades:</b> {trade_count}\n"
|
||||||
|
f"<b>Total P&L:</b> {total_pnl:+.2f}\n"
|
||||||
|
f"<b>Win Rate:</b> {win_rate:.2f}%\n"
|
||||||
|
f"<b>Decisions:</b> {decision_count}\n"
|
||||||
|
f"<b>Avg Confidence:</b> {avg_confidence:.2f}"
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.error("Error in /report handler: %s", exc)
|
||||||
|
await telegram.send_message(
|
||||||
|
"<b>⚠️ Error</b>\n\nFailed to generate daily report."
|
||||||
|
)
|
||||||
|
|
||||||
|
async def handle_scenarios() -> None:
|
||||||
|
"""Handle /scenarios command - show today's playbook scenarios."""
|
||||||
|
try:
|
||||||
|
today = datetime.now(UTC).date().isoformat()
|
||||||
|
rows = db_conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT market, playbook_json
|
||||||
|
FROM playbooks
|
||||||
|
WHERE date = ?
|
||||||
|
ORDER BY market
|
||||||
|
""",
|
||||||
|
(today,),
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
if not rows:
|
||||||
|
await telegram.send_message(
|
||||||
|
"<b>🧠 Today's Scenarios</b>\n\nNo playbooks found for today."
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
lines = ["<b>🧠 Today's Scenarios</b>", ""]
|
||||||
|
for market, playbook_json in rows:
|
||||||
|
lines.append(f"<b>{market}</b>")
|
||||||
|
playbook_data = {}
|
||||||
|
try:
|
||||||
|
playbook_data = json.loads(playbook_json)
|
||||||
|
except Exception:
|
||||||
|
playbook_data = {}
|
||||||
|
|
||||||
|
stock_playbooks = playbook_data.get("stock_playbooks", [])
|
||||||
|
if not stock_playbooks:
|
||||||
|
lines.append("- No scenarios")
|
||||||
|
lines.append("")
|
||||||
|
continue
|
||||||
|
|
||||||
|
for stock_pb in stock_playbooks:
|
||||||
|
stock_code = stock_pb.get("stock_code", "N/A")
|
||||||
|
scenarios = stock_pb.get("scenarios", [])
|
||||||
|
for sc in scenarios:
|
||||||
|
action = sc.get("action", "HOLD")
|
||||||
|
confidence = sc.get("confidence", 0)
|
||||||
|
lines.append(f"- {stock_code}: {action} ({confidence})")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
await telegram.send_message("\n".join(lines).strip())
|
||||||
|
except Exception as exc:
|
||||||
|
logger.error("Error in /scenarios handler: %s", exc)
|
||||||
|
await telegram.send_message(
|
||||||
|
"<b>⚠️ Error</b>\n\nFailed to retrieve scenarios."
|
||||||
|
)
|
||||||
|
|
||||||
|
async def handle_review() -> None:
|
||||||
|
"""Handle /review command - show recent scorecards."""
|
||||||
|
try:
|
||||||
|
rows = db_conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT timeframe, key, value
|
||||||
|
FROM contexts
|
||||||
|
WHERE layer = 'L6_DAILY' AND key LIKE 'scorecard_%'
|
||||||
|
ORDER BY updated_at DESC
|
||||||
|
LIMIT 5
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
if not rows:
|
||||||
|
await telegram.send_message(
|
||||||
|
"<b>📝 Recent Reviews</b>\n\nNo scorecards available."
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
lines = ["<b>📝 Recent Reviews</b>", ""]
|
||||||
|
for timeframe, key, value in rows:
|
||||||
|
scorecard = json.loads(value)
|
||||||
|
market = key.replace("scorecard_", "")
|
||||||
|
total_pnl = float(scorecard.get("total_pnl", 0.0))
|
||||||
|
win_rate = float(scorecard.get("win_rate", 0.0))
|
||||||
|
decisions = int(scorecard.get("total_decisions", 0))
|
||||||
|
lines.append(
|
||||||
|
f"- {timeframe} {market}: P&L {total_pnl:+.2f}, "
|
||||||
|
f"Win {win_rate:.2f}%, Decisions {decisions}"
|
||||||
|
)
|
||||||
|
|
||||||
|
await telegram.send_message("\n".join(lines))
|
||||||
|
except Exception as exc:
|
||||||
|
logger.error("Error in /review handler: %s", exc)
|
||||||
|
await telegram.send_message(
|
||||||
|
"<b>⚠️ Error</b>\n\nFailed to retrieve reviews."
|
||||||
|
)
|
||||||
|
|
||||||
|
async def handle_dashboard() -> None:
|
||||||
|
"""Handle /dashboard command - show dashboard URL if enabled."""
|
||||||
|
if not settings.DASHBOARD_ENABLED:
|
||||||
|
await telegram.send_message(
|
||||||
|
"<b>🖥️ Dashboard</b>\n\nDashboard is not enabled."
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
url = f"http://{settings.DASHBOARD_HOST}:{settings.DASHBOARD_PORT}"
|
||||||
|
await telegram.send_message(
|
||||||
|
"<b>🖥️ Dashboard</b>\n\n"
|
||||||
|
f"<b>URL:</b> {url}"
|
||||||
|
)
|
||||||
|
|
||||||
command_handler.register_command("help", handle_help)
|
command_handler.register_command("help", handle_help)
|
||||||
command_handler.register_command("stop", handle_stop)
|
command_handler.register_command("stop", handle_stop)
|
||||||
command_handler.register_command("resume", handle_resume)
|
command_handler.register_command("resume", handle_resume)
|
||||||
command_handler.register_command("status", handle_status)
|
command_handler.register_command("status", handle_status)
|
||||||
command_handler.register_command("positions", handle_positions)
|
command_handler.register_command("positions", handle_positions)
|
||||||
|
command_handler.register_command("report", handle_report)
|
||||||
|
command_handler.register_command("scenarios", handle_scenarios)
|
||||||
|
command_handler.register_command("review", handle_review)
|
||||||
|
command_handler.register_command("dashboard", handle_dashboard)
|
||||||
|
|
||||||
# Initialize volatility hunter
|
# Initialize volatility hunter
|
||||||
volatility_analyzer = VolatilityAnalyzer(min_volume_surge=2.0, min_price_change=1.0)
|
volatility_analyzer = VolatilityAnalyzer(min_volume_surge=2.0, min_price_change=1.0)
|
||||||
@@ -965,6 +1282,7 @@ async def run(settings: Settings) -> None:
|
|||||||
low_volatility_threshold=30.0,
|
low_volatility_threshold=30.0,
|
||||||
)
|
)
|
||||||
priority_queue = PriorityTaskQueue(max_size=1000)
|
priority_queue = PriorityTaskQueue(max_size=1000)
|
||||||
|
_start_dashboard_server(settings)
|
||||||
|
|
||||||
# Track last scan time for each market
|
# Track last scan time for each market
|
||||||
last_scan_time: dict[str, float] = {}
|
last_scan_time: dict[str, float] = {}
|
||||||
@@ -1015,6 +1333,7 @@ async def run(settings: Settings) -> None:
|
|||||||
while not shutdown.is_set():
|
while not shutdown.is_set():
|
||||||
# Wait for trading to be unpaused
|
# Wait for trading to be unpaused
|
||||||
await pause_trading.wait()
|
await pause_trading.wait()
|
||||||
|
_run_context_scheduler(context_scheduler, now=datetime.now(UTC))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await run_daily_session(
|
await run_daily_session(
|
||||||
@@ -1053,6 +1372,7 @@ async def run(settings: Settings) -> None:
|
|||||||
while not shutdown.is_set():
|
while not shutdown.is_set():
|
||||||
# Wait for trading to be unpaused
|
# Wait for trading to be unpaused
|
||||||
await pause_trading.wait()
|
await pause_trading.wait()
|
||||||
|
_run_context_scheduler(context_scheduler, now=datetime.now(UTC))
|
||||||
|
|
||||||
# Get currently open markets
|
# Get currently open markets
|
||||||
open_markets = get_open_markets(settings.enabled_market_list)
|
open_markets = get_open_markets(settings.enabled_market_list)
|
||||||
@@ -1073,6 +1393,7 @@ async def run(settings: Settings) -> None:
|
|||||||
telegram=telegram,
|
telegram=telegram,
|
||||||
context_aggregator=context_aggregator,
|
context_aggregator=context_aggregator,
|
||||||
daily_reviewer=daily_reviewer,
|
daily_reviewer=daily_reviewer,
|
||||||
|
evolution_optimizer=evolution_optimizer,
|
||||||
)
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.warning("Market close notification failed: %s", exc)
|
logger.warning("Market close notification failed: %s", exc)
|
||||||
@@ -1315,10 +1636,16 @@ def main() -> None:
|
|||||||
default="paper",
|
default="paper",
|
||||||
help="Trading mode (default: paper)",
|
help="Trading mode (default: paper)",
|
||||||
)
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--dashboard",
|
||||||
|
action="store_true",
|
||||||
|
help="Enable FastAPI dashboard server in background thread",
|
||||||
|
)
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
setup_logging()
|
setup_logging()
|
||||||
settings = Settings(MODE=args.mode) # type: ignore[call-arg]
|
settings = Settings(MODE=args.mode) # type: ignore[call-arg]
|
||||||
|
settings = _apply_dashboard_flag(settings, args.dashboard)
|
||||||
asyncio.run(run(settings))
|
asyncio.run(run(settings))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -123,6 +123,23 @@ MARKETS: dict[str, MarketInfo] = {
|
|||||||
),
|
),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
MARKET_SHORTHAND: dict[str, list[str]] = {
|
||||||
|
"US": ["US_NASDAQ", "US_NYSE", "US_AMEX"],
|
||||||
|
"CN": ["CN_SHA", "CN_SZA"],
|
||||||
|
"VN": ["VN_HAN", "VN_HCM"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def expand_market_codes(codes: list[str]) -> list[str]:
|
||||||
|
"""Expand shorthand market codes into concrete exchange market codes."""
|
||||||
|
expanded: list[str] = []
|
||||||
|
for code in codes:
|
||||||
|
if code in MARKET_SHORTHAND:
|
||||||
|
expanded.extend(MARKET_SHORTHAND[code])
|
||||||
|
else:
|
||||||
|
expanded.append(code)
|
||||||
|
return expanded
|
||||||
|
|
||||||
|
|
||||||
def is_market_open(market: MarketInfo, now: datetime | None = None) -> bool:
|
def is_market_open(market: MarketInfo, now: datetime | None = None) -> bool:
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -16,6 +16,10 @@ from src.evolution.daily_review import DailyReviewer
|
|||||||
from src.evolution.scorecard import DailyScorecard
|
from src.evolution.scorecard import DailyScorecard
|
||||||
from src.logging.decision_logger import DecisionLogger
|
from src.logging.decision_logger import DecisionLogger
|
||||||
|
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
|
TODAY = datetime.now(UTC).strftime("%Y-%m-%d")
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def db_conn() -> sqlite3.Connection:
|
def db_conn() -> sqlite3.Connection:
|
||||||
@@ -116,7 +120,7 @@ def test_generate_scorecard_market_scoped(
|
|||||||
exchange_code="NASDAQ",
|
exchange_code="NASDAQ",
|
||||||
)
|
)
|
||||||
|
|
||||||
scorecard = reviewer.generate_scorecard("2026-02-14", "KR")
|
scorecard = reviewer.generate_scorecard(TODAY, "KR")
|
||||||
|
|
||||||
assert scorecard.market == "KR"
|
assert scorecard.market == "KR"
|
||||||
assert scorecard.total_decisions == 2
|
assert scorecard.total_decisions == 2
|
||||||
@@ -158,7 +162,7 @@ def test_generate_scorecard_top_winners_and_losers(
|
|||||||
decision_id=decision_id,
|
decision_id=decision_id,
|
||||||
)
|
)
|
||||||
|
|
||||||
scorecard = reviewer.generate_scorecard("2026-02-14", "KR")
|
scorecard = reviewer.generate_scorecard(TODAY, "KR")
|
||||||
assert scorecard.top_winners == ["005930", "000660"]
|
assert scorecard.top_winners == ["005930", "000660"]
|
||||||
assert scorecard.top_losers == ["035420", "051910"]
|
assert scorecard.top_losers == ["035420", "051910"]
|
||||||
|
|
||||||
@@ -167,7 +171,7 @@ def test_generate_scorecard_empty_day(
|
|||||||
db_conn: sqlite3.Connection, context_store: ContextStore,
|
db_conn: sqlite3.Connection, context_store: ContextStore,
|
||||||
) -> None:
|
) -> None:
|
||||||
reviewer = DailyReviewer(db_conn, context_store)
|
reviewer = DailyReviewer(db_conn, context_store)
|
||||||
scorecard = reviewer.generate_scorecard("2026-02-14", "KR")
|
scorecard = reviewer.generate_scorecard(TODAY, "KR")
|
||||||
|
|
||||||
assert scorecard.total_decisions == 0
|
assert scorecard.total_decisions == 0
|
||||||
assert scorecard.total_pnl == 0.0
|
assert scorecard.total_pnl == 0.0
|
||||||
|
|||||||
298
tests/test_dashboard.py
Normal file
298
tests/test_dashboard.py
Normal file
@@ -0,0 +1,298 @@
|
|||||||
|
"""Tests for dashboard endpoint handlers."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sqlite3
|
||||||
|
from collections.abc import Callable
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
|
||||||
|
from src.dashboard.app import create_dashboard_app
|
||||||
|
from src.db import init_db
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_db(conn: sqlite3.Connection) -> None:
|
||||||
|
today = datetime.now(UTC).date().isoformat()
|
||||||
|
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO playbooks (
|
||||||
|
date, market, status, playbook_json, generated_at,
|
||||||
|
token_count, scenario_count, match_count
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
"2026-02-14",
|
||||||
|
"KR",
|
||||||
|
"ready",
|
||||||
|
json.dumps({"market": "KR", "stock_playbooks": []}),
|
||||||
|
"2026-02-14T08:30:00+00:00",
|
||||||
|
123,
|
||||||
|
2,
|
||||||
|
1,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO playbooks (
|
||||||
|
date, market, status, playbook_json, generated_at,
|
||||||
|
token_count, scenario_count, match_count
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
today,
|
||||||
|
"US_NASDAQ",
|
||||||
|
"ready",
|
||||||
|
json.dumps({"market": "US_NASDAQ", "stock_playbooks": []}),
|
||||||
|
f"{today}T08:30:00+00:00",
|
||||||
|
100,
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO contexts (layer, timeframe, key, value, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
"L6_DAILY",
|
||||||
|
"2026-02-14",
|
||||||
|
"scorecard_KR",
|
||||||
|
json.dumps({"market": "KR", "total_pnl": 1.5, "win_rate": 60.0}),
|
||||||
|
"2026-02-14T15:30:00+00:00",
|
||||||
|
"2026-02-14T15:30:00+00:00",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO contexts (layer, timeframe, key, value, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
"L7_REALTIME",
|
||||||
|
"2026-02-14T10:00:00+00:00",
|
||||||
|
"volatility_KR_005930",
|
||||||
|
json.dumps({"momentum_score": 70.0}),
|
||||||
|
"2026-02-14T10:00:00+00:00",
|
||||||
|
"2026-02-14T10:00:00+00:00",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO decision_logs (
|
||||||
|
decision_id, timestamp, stock_code, market, exchange_code,
|
||||||
|
action, confidence, rationale, context_snapshot, input_data
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
"d-kr-1",
|
||||||
|
f"{today}T09:10:00+00:00",
|
||||||
|
"005930",
|
||||||
|
"KR",
|
||||||
|
"KRX",
|
||||||
|
"BUY",
|
||||||
|
85,
|
||||||
|
"signal matched",
|
||||||
|
json.dumps({"scenario_match": {"rsi": 28.0}}),
|
||||||
|
json.dumps({"current_price": 70000}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO decision_logs (
|
||||||
|
decision_id, timestamp, stock_code, market, exchange_code,
|
||||||
|
action, confidence, rationale, context_snapshot, input_data
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
"d-us-1",
|
||||||
|
f"{today}T21:10:00+00:00",
|
||||||
|
"AAPL",
|
||||||
|
"US_NASDAQ",
|
||||||
|
"NASDAQ",
|
||||||
|
"SELL",
|
||||||
|
80,
|
||||||
|
"no match",
|
||||||
|
json.dumps({"scenario_match": {}}),
|
||||||
|
json.dumps({"current_price": 200}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO trades (
|
||||||
|
timestamp, stock_code, action, confidence, rationale,
|
||||||
|
quantity, price, pnl, market, exchange_code, selection_context, decision_id
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
f"{today}T09:11:00+00:00",
|
||||||
|
"005930",
|
||||||
|
"BUY",
|
||||||
|
85,
|
||||||
|
"buy",
|
||||||
|
1,
|
||||||
|
70000,
|
||||||
|
2.0,
|
||||||
|
"KR",
|
||||||
|
"KRX",
|
||||||
|
None,
|
||||||
|
"d-kr-1",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO trades (
|
||||||
|
timestamp, stock_code, action, confidence, rationale,
|
||||||
|
quantity, price, pnl, market, exchange_code, selection_context, decision_id
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
f"{today}T21:11:00+00:00",
|
||||||
|
"AAPL",
|
||||||
|
"SELL",
|
||||||
|
80,
|
||||||
|
"sell",
|
||||||
|
1,
|
||||||
|
200,
|
||||||
|
-1.0,
|
||||||
|
"US_NASDAQ",
|
||||||
|
"NASDAQ",
|
||||||
|
None,
|
||||||
|
"d-us-1",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def _app(tmp_path: Path) -> Any:
|
||||||
|
db_path = tmp_path / "dashboard_test.db"
|
||||||
|
conn = init_db(str(db_path))
|
||||||
|
_seed_db(conn)
|
||||||
|
conn.close()
|
||||||
|
return create_dashboard_app(str(db_path))
|
||||||
|
|
||||||
|
|
||||||
|
def _endpoint(app: Any, path: str) -> Callable[..., Any]:
|
||||||
|
for route in app.routes:
|
||||||
|
if getattr(route, "path", None) == path:
|
||||||
|
return route.endpoint
|
||||||
|
raise AssertionError(f"route not found: {path}")
|
||||||
|
|
||||||
|
|
||||||
|
def test_index_serves_html(tmp_path: Path) -> None:
|
||||||
|
app = _app(tmp_path)
|
||||||
|
index = _endpoint(app, "/")
|
||||||
|
resp = index()
|
||||||
|
assert isinstance(resp, FileResponse)
|
||||||
|
assert "index.html" in str(resp.path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_status_endpoint(tmp_path: Path) -> None:
|
||||||
|
app = _app(tmp_path)
|
||||||
|
get_status = _endpoint(app, "/api/status")
|
||||||
|
body = get_status()
|
||||||
|
assert "KR" in body["markets"]
|
||||||
|
assert "US_NASDAQ" in body["markets"]
|
||||||
|
assert "totals" in body
|
||||||
|
|
||||||
|
|
||||||
|
def test_playbook_found(tmp_path: Path) -> None:
|
||||||
|
app = _app(tmp_path)
|
||||||
|
get_playbook = _endpoint(app, "/api/playbook/{date_str}")
|
||||||
|
body = get_playbook("2026-02-14", market="KR")
|
||||||
|
assert body["market"] == "KR"
|
||||||
|
|
||||||
|
|
||||||
|
def test_playbook_not_found(tmp_path: Path) -> None:
|
||||||
|
app = _app(tmp_path)
|
||||||
|
get_playbook = _endpoint(app, "/api/playbook/{date_str}")
|
||||||
|
with pytest.raises(HTTPException, match="playbook not found"):
|
||||||
|
get_playbook("2026-02-15", market="KR")
|
||||||
|
|
||||||
|
|
||||||
|
def test_scorecard_found(tmp_path: Path) -> None:
|
||||||
|
app = _app(tmp_path)
|
||||||
|
get_scorecard = _endpoint(app, "/api/scorecard/{date_str}")
|
||||||
|
body = get_scorecard("2026-02-14", market="KR")
|
||||||
|
assert body["scorecard"]["total_pnl"] == 1.5
|
||||||
|
|
||||||
|
|
||||||
|
def test_scorecard_not_found(tmp_path: Path) -> None:
|
||||||
|
app = _app(tmp_path)
|
||||||
|
get_scorecard = _endpoint(app, "/api/scorecard/{date_str}")
|
||||||
|
with pytest.raises(HTTPException, match="scorecard not found"):
|
||||||
|
get_scorecard("2026-02-15", market="KR")
|
||||||
|
|
||||||
|
|
||||||
|
def test_performance_all(tmp_path: Path) -> None:
|
||||||
|
app = _app(tmp_path)
|
||||||
|
get_performance = _endpoint(app, "/api/performance")
|
||||||
|
body = get_performance(market="all")
|
||||||
|
assert body["market"] == "all"
|
||||||
|
assert body["combined"]["total_trades"] == 2
|
||||||
|
assert len(body["by_market"]) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_performance_market_filter(tmp_path: Path) -> None:
|
||||||
|
app = _app(tmp_path)
|
||||||
|
get_performance = _endpoint(app, "/api/performance")
|
||||||
|
body = get_performance(market="KR")
|
||||||
|
assert body["market"] == "KR"
|
||||||
|
assert body["metrics"]["total_trades"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_performance_empty_market(tmp_path: Path) -> None:
|
||||||
|
app = _app(tmp_path)
|
||||||
|
get_performance = _endpoint(app, "/api/performance")
|
||||||
|
body = get_performance(market="JP")
|
||||||
|
assert body["metrics"]["total_trades"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_context_layer_all(tmp_path: Path) -> None:
|
||||||
|
app = _app(tmp_path)
|
||||||
|
get_context_layer = _endpoint(app, "/api/context/{layer}")
|
||||||
|
body = get_context_layer("L7_REALTIME", timeframe=None, limit=100)
|
||||||
|
assert body["layer"] == "L7_REALTIME"
|
||||||
|
assert body["count"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_context_layer_timeframe_filter(tmp_path: Path) -> None:
|
||||||
|
app = _app(tmp_path)
|
||||||
|
get_context_layer = _endpoint(app, "/api/context/{layer}")
|
||||||
|
body = get_context_layer("L6_DAILY", timeframe="2026-02-14", limit=100)
|
||||||
|
assert body["count"] == 1
|
||||||
|
assert body["entries"][0]["key"] == "scorecard_KR"
|
||||||
|
|
||||||
|
|
||||||
|
def test_decisions_endpoint(tmp_path: Path) -> None:
|
||||||
|
app = _app(tmp_path)
|
||||||
|
get_decisions = _endpoint(app, "/api/decisions")
|
||||||
|
body = get_decisions(market="KR", limit=50)
|
||||||
|
assert body["count"] == 1
|
||||||
|
assert body["decisions"][0]["decision_id"] == "d-kr-1"
|
||||||
|
|
||||||
|
|
||||||
|
def test_scenarios_active_filters_non_matched(tmp_path: Path) -> None:
|
||||||
|
app = _app(tmp_path)
|
||||||
|
get_active_scenarios = _endpoint(app, "/api/scenarios/active")
|
||||||
|
body = get_active_scenarios(
|
||||||
|
market="KR",
|
||||||
|
date_str=datetime.now(UTC).date().isoformat(),
|
||||||
|
limit=50,
|
||||||
|
)
|
||||||
|
assert body["count"] == 1
|
||||||
|
assert body["matches"][0]["stock_code"] == "005930"
|
||||||
|
|
||||||
|
|
||||||
|
def test_scenarios_active_empty_when_no_matches(tmp_path: Path) -> None:
|
||||||
|
app = _app(tmp_path)
|
||||||
|
get_active_scenarios = _endpoint(app, "/api/scenarios/active")
|
||||||
|
body = get_active_scenarios(market="US", date_str="2026-02-14", limit=50)
|
||||||
|
assert body["count"] == 0
|
||||||
60
tests/test_db.py
Normal file
60
tests/test_db.py
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
"""Tests for database helper functions."""
|
||||||
|
|
||||||
|
from src.db import get_open_position, init_db, log_trade
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_open_position_returns_latest_buy() -> None:
|
||||||
|
conn = init_db(":memory:")
|
||||||
|
log_trade(
|
||||||
|
conn=conn,
|
||||||
|
stock_code="005930",
|
||||||
|
action="BUY",
|
||||||
|
confidence=90,
|
||||||
|
rationale="entry",
|
||||||
|
quantity=2,
|
||||||
|
price=70000.0,
|
||||||
|
market="KR",
|
||||||
|
exchange_code="KRX",
|
||||||
|
decision_id="d-buy-1",
|
||||||
|
)
|
||||||
|
|
||||||
|
position = get_open_position(conn, "005930", "KR")
|
||||||
|
assert position is not None
|
||||||
|
assert position["decision_id"] == "d-buy-1"
|
||||||
|
assert position["price"] == 70000.0
|
||||||
|
assert position["quantity"] == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_open_position_returns_none_when_latest_is_sell() -> None:
|
||||||
|
conn = init_db(":memory:")
|
||||||
|
log_trade(
|
||||||
|
conn=conn,
|
||||||
|
stock_code="005930",
|
||||||
|
action="BUY",
|
||||||
|
confidence=90,
|
||||||
|
rationale="entry",
|
||||||
|
quantity=1,
|
||||||
|
price=70000.0,
|
||||||
|
market="KR",
|
||||||
|
exchange_code="KRX",
|
||||||
|
decision_id="d-buy-1",
|
||||||
|
)
|
||||||
|
log_trade(
|
||||||
|
conn=conn,
|
||||||
|
stock_code="005930",
|
||||||
|
action="SELL",
|
||||||
|
confidence=95,
|
||||||
|
rationale="exit",
|
||||||
|
quantity=1,
|
||||||
|
price=71000.0,
|
||||||
|
market="KR",
|
||||||
|
exchange_code="KRX",
|
||||||
|
decision_id="d-sell-1",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert get_open_position(conn, "005930", "KR") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_open_position_returns_none_when_no_trades() -> None:
|
||||||
|
conn = init_db(":memory:")
|
||||||
|
assert get_open_position(conn, "AAPL", "US_NASDAQ") is None
|
||||||
@@ -1,16 +1,26 @@
|
|||||||
"""Tests for main trading loop integration."""
|
"""Tests for main trading loop integration."""
|
||||||
|
|
||||||
from datetime import UTC, date
|
from datetime import UTC, date, datetime
|
||||||
from unittest.mock import ANY, AsyncMock, MagicMock, patch
|
from unittest.mock import ANY, AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
from src.config import Settings
|
||||||
from src.context.layer import ContextLayer
|
from src.context.layer import ContextLayer
|
||||||
|
from src.context.scheduler import ScheduleResult
|
||||||
from src.core.risk_manager import CircuitBreakerTripped, FatFingerRejected
|
from src.core.risk_manager import CircuitBreakerTripped, FatFingerRejected
|
||||||
from src.db import init_db, log_trade
|
from src.db import init_db, log_trade
|
||||||
from src.evolution.scorecard import DailyScorecard
|
from src.evolution.scorecard import DailyScorecard
|
||||||
from src.logging.decision_logger import DecisionLogger
|
from src.logging.decision_logger import DecisionLogger
|
||||||
from src.main import _handle_market_close, safe_float, trading_cycle
|
from src.main import (
|
||||||
|
_apply_dashboard_flag,
|
||||||
|
_handle_market_close,
|
||||||
|
_run_context_scheduler,
|
||||||
|
_run_evolution_loop,
|
||||||
|
_start_dashboard_server,
|
||||||
|
safe_float,
|
||||||
|
trading_cycle,
|
||||||
|
)
|
||||||
from src.strategy.models import (
|
from src.strategy.models import (
|
||||||
DayPlaybook,
|
DayPlaybook,
|
||||||
ScenarioAction,
|
ScenarioAction,
|
||||||
@@ -106,6 +116,7 @@ class TestTradingCycleTelegramIntegration:
|
|||||||
"output1": {
|
"output1": {
|
||||||
"stck_prpr": "50000",
|
"stck_prpr": "50000",
|
||||||
"frgn_ntby_qty": "100",
|
"frgn_ntby_qty": "100",
|
||||||
|
"prdy_ctrt": "1.23",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
@@ -737,7 +748,7 @@ class TestScenarioEngineIntegration:
|
|||||||
broker = MagicMock()
|
broker = MagicMock()
|
||||||
broker.get_orderbook = AsyncMock(
|
broker.get_orderbook = AsyncMock(
|
||||||
return_value={
|
return_value={
|
||||||
"output1": {"stck_prpr": "50000", "frgn_ntby_qty": "100"}
|
"output1": {"stck_prpr": "50000", "frgn_ntby_qty": "100", "prdy_ctrt": "2.50"}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
broker.get_balance = AsyncMock(
|
broker.get_balance = AsyncMock(
|
||||||
@@ -820,6 +831,7 @@ class TestScenarioEngineIntegration:
|
|||||||
assert market_data["rsi"] == 25.0
|
assert market_data["rsi"] == 25.0
|
||||||
assert market_data["volume_ratio"] == 3.5
|
assert market_data["volume_ratio"] == 3.5
|
||||||
assert market_data["current_price"] == 50000.0
|
assert market_data["current_price"] == 50000.0
|
||||||
|
assert market_data["price_change_pct"] == 2.5
|
||||||
|
|
||||||
# Portfolio data should include pnl
|
# Portfolio data should include pnl
|
||||||
assert "portfolio_pnl_pct" in portfolio_data
|
assert "portfolio_pnl_pct" in portfolio_data
|
||||||
@@ -1222,6 +1234,107 @@ async def test_sell_updates_original_buy_decision_outcome() -> None:
|
|||||||
assert updated_buy.outcome_accuracy == 1
|
assert updated_buy.outcome_accuracy == 1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_hold_overridden_to_sell_when_stop_loss_triggered() -> None:
|
||||||
|
"""HOLD decision should be overridden to SELL when stop-loss threshold is breached."""
|
||||||
|
db_conn = init_db(":memory:")
|
||||||
|
decision_logger = DecisionLogger(db_conn)
|
||||||
|
|
||||||
|
buy_decision_id = decision_logger.log_decision(
|
||||||
|
stock_code="005930",
|
||||||
|
market="KR",
|
||||||
|
exchange_code="KRX",
|
||||||
|
action="BUY",
|
||||||
|
confidence=90,
|
||||||
|
rationale="entry",
|
||||||
|
context_snapshot={},
|
||||||
|
input_data={},
|
||||||
|
)
|
||||||
|
log_trade(
|
||||||
|
conn=db_conn,
|
||||||
|
stock_code="005930",
|
||||||
|
action="BUY",
|
||||||
|
confidence=90,
|
||||||
|
rationale="entry",
|
||||||
|
quantity=1,
|
||||||
|
price=100.0,
|
||||||
|
market="KR",
|
||||||
|
exchange_code="KRX",
|
||||||
|
decision_id=buy_decision_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
broker = MagicMock()
|
||||||
|
broker.get_orderbook = AsyncMock(
|
||||||
|
return_value={"output1": {"stck_prpr": "95", "frgn_ntby_qty": "0", "prdy_ctrt": "-5.0"}}
|
||||||
|
)
|
||||||
|
broker.get_balance = AsyncMock(
|
||||||
|
return_value={
|
||||||
|
"output2": [
|
||||||
|
{
|
||||||
|
"tot_evlu_amt": "100000",
|
||||||
|
"dnca_tot_amt": "10000",
|
||||||
|
"pchs_amt_smtl_amt": "90000",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
)
|
||||||
|
broker.send_order = AsyncMock(return_value={"msg1": "OK"})
|
||||||
|
|
||||||
|
scenario = StockScenario(
|
||||||
|
condition=StockCondition(rsi_below=30),
|
||||||
|
action=ScenarioAction.BUY,
|
||||||
|
confidence=88,
|
||||||
|
stop_loss_pct=-2.0,
|
||||||
|
rationale="stop loss policy",
|
||||||
|
)
|
||||||
|
playbook = DayPlaybook(
|
||||||
|
date=date(2026, 2, 8),
|
||||||
|
market="KR",
|
||||||
|
stock_playbooks=[
|
||||||
|
{"stock_code": "005930", "stock_name": "Samsung", "scenarios": [scenario]}
|
||||||
|
],
|
||||||
|
)
|
||||||
|
engine = MagicMock(spec=ScenarioEngine)
|
||||||
|
engine.evaluate = MagicMock(return_value=_make_hold_match())
|
||||||
|
|
||||||
|
market = MagicMock()
|
||||||
|
market.name = "Korea"
|
||||||
|
market.code = "KR"
|
||||||
|
market.exchange_code = "KRX"
|
||||||
|
market.is_domestic = True
|
||||||
|
|
||||||
|
telegram = MagicMock()
|
||||||
|
telegram.notify_trade_execution = AsyncMock()
|
||||||
|
telegram.notify_fat_finger = AsyncMock()
|
||||||
|
telegram.notify_circuit_breaker = AsyncMock()
|
||||||
|
telegram.notify_scenario_matched = AsyncMock()
|
||||||
|
|
||||||
|
await trading_cycle(
|
||||||
|
broker=broker,
|
||||||
|
overseas_broker=MagicMock(),
|
||||||
|
scenario_engine=engine,
|
||||||
|
playbook=playbook,
|
||||||
|
risk=MagicMock(),
|
||||||
|
db_conn=db_conn,
|
||||||
|
decision_logger=decision_logger,
|
||||||
|
context_store=MagicMock(
|
||||||
|
get_latest_timeframe=MagicMock(return_value=None),
|
||||||
|
set_context=MagicMock(),
|
||||||
|
),
|
||||||
|
criticality_assessor=MagicMock(
|
||||||
|
assess_market_conditions=MagicMock(return_value=MagicMock(value="NORMAL")),
|
||||||
|
get_timeout=MagicMock(return_value=5.0),
|
||||||
|
),
|
||||||
|
telegram=telegram,
|
||||||
|
market=market,
|
||||||
|
stock_code="005930",
|
||||||
|
scan_candidates={},
|
||||||
|
)
|
||||||
|
|
||||||
|
broker.send_order.assert_called_once()
|
||||||
|
assert broker.send_order.call_args.kwargs["order_type"] == "SELL"
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_handle_market_close_runs_daily_review_flow() -> None:
|
async def test_handle_market_close_runs_daily_review_flow() -> None:
|
||||||
"""Market close should aggregate, create scorecard, lessons, and notify."""
|
"""Market close should aggregate, create scorecard, lessons, and notify."""
|
||||||
@@ -1295,3 +1408,196 @@ async def test_handle_market_close_without_lessons_stores_once() -> None:
|
|||||||
)
|
)
|
||||||
|
|
||||||
assert reviewer.store_scorecard_in_context.call_count == 1
|
assert reviewer.store_scorecard_in_context.call_count == 1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_handle_market_close_triggers_evolution_for_us() -> None:
|
||||||
|
telegram = MagicMock()
|
||||||
|
telegram.notify_market_close = AsyncMock()
|
||||||
|
telegram.send_message = AsyncMock()
|
||||||
|
|
||||||
|
context_aggregator = MagicMock()
|
||||||
|
reviewer = MagicMock()
|
||||||
|
reviewer.generate_scorecard.return_value = DailyScorecard(
|
||||||
|
date="2026-02-14",
|
||||||
|
market="US",
|
||||||
|
total_decisions=2,
|
||||||
|
buys=1,
|
||||||
|
sells=1,
|
||||||
|
holds=0,
|
||||||
|
total_pnl=3.0,
|
||||||
|
win_rate=50.0,
|
||||||
|
avg_confidence=80.0,
|
||||||
|
scenario_match_rate=100.0,
|
||||||
|
)
|
||||||
|
reviewer.generate_lessons = AsyncMock(return_value=[])
|
||||||
|
|
||||||
|
evolution_optimizer = MagicMock()
|
||||||
|
evolution_optimizer.evolve = AsyncMock(return_value=None)
|
||||||
|
|
||||||
|
await _handle_market_close(
|
||||||
|
market_code="US",
|
||||||
|
market_name="United States",
|
||||||
|
market_timezone=UTC,
|
||||||
|
telegram=telegram,
|
||||||
|
context_aggregator=context_aggregator,
|
||||||
|
daily_reviewer=reviewer,
|
||||||
|
evolution_optimizer=evolution_optimizer,
|
||||||
|
)
|
||||||
|
|
||||||
|
evolution_optimizer.evolve.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_handle_market_close_skips_evolution_for_kr() -> None:
|
||||||
|
telegram = MagicMock()
|
||||||
|
telegram.notify_market_close = AsyncMock()
|
||||||
|
telegram.send_message = AsyncMock()
|
||||||
|
|
||||||
|
context_aggregator = MagicMock()
|
||||||
|
reviewer = MagicMock()
|
||||||
|
reviewer.generate_scorecard.return_value = DailyScorecard(
|
||||||
|
date="2026-02-14",
|
||||||
|
market="KR",
|
||||||
|
total_decisions=1,
|
||||||
|
buys=1,
|
||||||
|
sells=0,
|
||||||
|
holds=0,
|
||||||
|
total_pnl=1.0,
|
||||||
|
win_rate=100.0,
|
||||||
|
avg_confidence=90.0,
|
||||||
|
scenario_match_rate=100.0,
|
||||||
|
)
|
||||||
|
reviewer.generate_lessons = AsyncMock(return_value=[])
|
||||||
|
|
||||||
|
evolution_optimizer = MagicMock()
|
||||||
|
evolution_optimizer.evolve = AsyncMock(return_value=None)
|
||||||
|
|
||||||
|
await _handle_market_close(
|
||||||
|
market_code="KR",
|
||||||
|
market_name="Korea",
|
||||||
|
market_timezone=UTC,
|
||||||
|
telegram=telegram,
|
||||||
|
context_aggregator=context_aggregator,
|
||||||
|
daily_reviewer=reviewer,
|
||||||
|
evolution_optimizer=evolution_optimizer,
|
||||||
|
)
|
||||||
|
|
||||||
|
evolution_optimizer.evolve.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_context_scheduler_invokes_scheduler() -> None:
|
||||||
|
"""Scheduler helper should call run_if_due with provided datetime."""
|
||||||
|
scheduler = MagicMock()
|
||||||
|
scheduler.run_if_due = MagicMock(return_value=ScheduleResult(cleanup=True))
|
||||||
|
|
||||||
|
_run_context_scheduler(scheduler, now=datetime(2026, 2, 14, tzinfo=UTC))
|
||||||
|
|
||||||
|
scheduler.run_if_due.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_run_evolution_loop_skips_non_us_market() -> None:
|
||||||
|
optimizer = MagicMock()
|
||||||
|
optimizer.evolve = AsyncMock()
|
||||||
|
telegram = MagicMock()
|
||||||
|
telegram.send_message = AsyncMock()
|
||||||
|
|
||||||
|
await _run_evolution_loop(
|
||||||
|
evolution_optimizer=optimizer,
|
||||||
|
telegram=telegram,
|
||||||
|
market_code="KR",
|
||||||
|
market_date="2026-02-14",
|
||||||
|
)
|
||||||
|
|
||||||
|
optimizer.evolve.assert_not_called()
|
||||||
|
telegram.send_message.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_run_evolution_loop_notifies_when_pr_generated() -> None:
|
||||||
|
optimizer = MagicMock()
|
||||||
|
optimizer.evolve = AsyncMock(
|
||||||
|
return_value={
|
||||||
|
"title": "[Evolution] New strategy: v20260214_050000",
|
||||||
|
"branch": "evolution/v20260214_050000",
|
||||||
|
"status": "ready_for_review",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
telegram = MagicMock()
|
||||||
|
telegram.send_message = AsyncMock()
|
||||||
|
|
||||||
|
await _run_evolution_loop(
|
||||||
|
evolution_optimizer=optimizer,
|
||||||
|
telegram=telegram,
|
||||||
|
market_code="US_NASDAQ",
|
||||||
|
market_date="2026-02-14",
|
||||||
|
)
|
||||||
|
|
||||||
|
optimizer.evolve.assert_called_once()
|
||||||
|
telegram.send_message.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_run_evolution_loop_notification_error_is_ignored() -> None:
|
||||||
|
optimizer = MagicMock()
|
||||||
|
optimizer.evolve = AsyncMock(
|
||||||
|
return_value={
|
||||||
|
"title": "[Evolution] New strategy: v20260214_050000",
|
||||||
|
"branch": "evolution/v20260214_050000",
|
||||||
|
"status": "ready_for_review",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
telegram = MagicMock()
|
||||||
|
telegram.send_message = AsyncMock(side_effect=RuntimeError("telegram down"))
|
||||||
|
|
||||||
|
await _run_evolution_loop(
|
||||||
|
evolution_optimizer=optimizer,
|
||||||
|
telegram=telegram,
|
||||||
|
market_code="US_NYSE",
|
||||||
|
market_date="2026-02-14",
|
||||||
|
)
|
||||||
|
|
||||||
|
optimizer.evolve.assert_called_once()
|
||||||
|
telegram.send_message.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
def test_apply_dashboard_flag_enables_dashboard() -> None:
|
||||||
|
settings = Settings(
|
||||||
|
KIS_APP_KEY="test_key",
|
||||||
|
KIS_APP_SECRET="test_secret",
|
||||||
|
KIS_ACCOUNT_NO="12345678-01",
|
||||||
|
GEMINI_API_KEY="test_gemini_key",
|
||||||
|
DASHBOARD_ENABLED=False,
|
||||||
|
)
|
||||||
|
updated = _apply_dashboard_flag(settings, dashboard_flag=True)
|
||||||
|
assert updated.DASHBOARD_ENABLED is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_start_dashboard_server_disabled_returns_none() -> None:
|
||||||
|
settings = Settings(
|
||||||
|
KIS_APP_KEY="test_key",
|
||||||
|
KIS_APP_SECRET="test_secret",
|
||||||
|
KIS_ACCOUNT_NO="12345678-01",
|
||||||
|
GEMINI_API_KEY="test_gemini_key",
|
||||||
|
DASHBOARD_ENABLED=False,
|
||||||
|
)
|
||||||
|
thread = _start_dashboard_server(settings)
|
||||||
|
assert thread is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_start_dashboard_server_enabled_starts_thread() -> None:
|
||||||
|
settings = Settings(
|
||||||
|
KIS_APP_KEY="test_key",
|
||||||
|
KIS_APP_SECRET="test_secret",
|
||||||
|
KIS_ACCOUNT_NO="12345678-01",
|
||||||
|
GEMINI_API_KEY="test_gemini_key",
|
||||||
|
DASHBOARD_ENABLED=True,
|
||||||
|
)
|
||||||
|
mock_thread = MagicMock()
|
||||||
|
with patch("src.main.threading.Thread", return_value=mock_thread) as mock_thread_cls:
|
||||||
|
thread = _start_dashboard_server(settings)
|
||||||
|
|
||||||
|
assert thread == mock_thread
|
||||||
|
mock_thread_cls.assert_called_once()
|
||||||
|
mock_thread.start.assert_called_once()
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import pytest
|
|||||||
|
|
||||||
from src.markets.schedule import (
|
from src.markets.schedule import (
|
||||||
MARKETS,
|
MARKETS,
|
||||||
|
expand_market_codes,
|
||||||
get_next_market_open,
|
get_next_market_open,
|
||||||
get_open_markets,
|
get_open_markets,
|
||||||
is_market_open,
|
is_market_open,
|
||||||
@@ -199,3 +200,28 @@ class TestGetNextMarketOpen:
|
|||||||
enabled_markets=["INVALID", "KR"], now=test_time
|
enabled_markets=["INVALID", "KR"], now=test_time
|
||||||
)
|
)
|
||||||
assert market.code == "KR"
|
assert market.code == "KR"
|
||||||
|
|
||||||
|
|
||||||
|
class TestExpandMarketCodes:
|
||||||
|
"""Test shorthand market expansion."""
|
||||||
|
|
||||||
|
def test_expand_us_shorthand(self) -> None:
|
||||||
|
assert expand_market_codes(["US"]) == ["US_NASDAQ", "US_NYSE", "US_AMEX"]
|
||||||
|
|
||||||
|
def test_expand_cn_shorthand(self) -> None:
|
||||||
|
assert expand_market_codes(["CN"]) == ["CN_SHA", "CN_SZA"]
|
||||||
|
|
||||||
|
def test_expand_vn_shorthand(self) -> None:
|
||||||
|
assert expand_market_codes(["VN"]) == ["VN_HAN", "VN_HCM"]
|
||||||
|
|
||||||
|
def test_expand_mixed_codes(self) -> None:
|
||||||
|
assert expand_market_codes(["KR", "US", "JP"]) == [
|
||||||
|
"KR",
|
||||||
|
"US_NASDAQ",
|
||||||
|
"US_NYSE",
|
||||||
|
"US_AMEX",
|
||||||
|
"JP",
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_expand_preserves_unknown_code(self) -> None:
|
||||||
|
assert expand_market_codes(["KR", "UNKNOWN"]) == ["KR", "UNKNOWN"]
|
||||||
|
|||||||
@@ -682,6 +682,10 @@ class TestBasicCommands:
|
|||||||
"/help - Show available commands\n"
|
"/help - Show available commands\n"
|
||||||
"/status - Trading status (mode, markets, P&L)\n"
|
"/status - Trading status (mode, markets, P&L)\n"
|
||||||
"/positions - Current holdings\n"
|
"/positions - Current holdings\n"
|
||||||
|
"/report - Daily summary report\n"
|
||||||
|
"/scenarios - Today's playbook scenarios\n"
|
||||||
|
"/review - Recent scorecards\n"
|
||||||
|
"/dashboard - Dashboard URL/status\n"
|
||||||
"/stop - Pause trading\n"
|
"/stop - Pause trading\n"
|
||||||
"/resume - Resume trading"
|
"/resume - Resume trading"
|
||||||
)
|
)
|
||||||
@@ -707,10 +711,106 @@ class TestBasicCommands:
|
|||||||
assert "/help" in payload["text"]
|
assert "/help" in payload["text"]
|
||||||
assert "/status" in payload["text"]
|
assert "/status" in payload["text"]
|
||||||
assert "/positions" in payload["text"]
|
assert "/positions" in payload["text"]
|
||||||
|
assert "/report" in payload["text"]
|
||||||
|
assert "/scenarios" in payload["text"]
|
||||||
|
assert "/review" in payload["text"]
|
||||||
|
assert "/dashboard" in payload["text"]
|
||||||
assert "/stop" in payload["text"]
|
assert "/stop" in payload["text"]
|
||||||
assert "/resume" in payload["text"]
|
assert "/resume" in payload["text"]
|
||||||
|
|
||||||
|
|
||||||
|
class TestExtendedCommands:
|
||||||
|
"""Test additional bot commands."""
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_report_command(self) -> None:
|
||||||
|
client = TelegramClient(bot_token="123:abc", chat_id="456", enabled=True)
|
||||||
|
handler = TelegramCommandHandler(client)
|
||||||
|
|
||||||
|
mock_resp = AsyncMock()
|
||||||
|
mock_resp.status = 200
|
||||||
|
mock_resp.__aenter__ = AsyncMock(return_value=mock_resp)
|
||||||
|
mock_resp.__aexit__ = AsyncMock(return_value=False)
|
||||||
|
|
||||||
|
async def mock_report() -> None:
|
||||||
|
await client.send_message("<b>📈 Daily Report</b>\n\nTrades: 1")
|
||||||
|
|
||||||
|
handler.register_command("report", mock_report)
|
||||||
|
|
||||||
|
with patch("aiohttp.ClientSession.post", return_value=mock_resp) as mock_post:
|
||||||
|
await handler._handle_update(
|
||||||
|
{"update_id": 1, "message": {"chat": {"id": 456}, "text": "/report"}}
|
||||||
|
)
|
||||||
|
payload = mock_post.call_args.kwargs["json"]
|
||||||
|
assert "Daily Report" in payload["text"]
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_scenarios_command(self) -> None:
|
||||||
|
client = TelegramClient(bot_token="123:abc", chat_id="456", enabled=True)
|
||||||
|
handler = TelegramCommandHandler(client)
|
||||||
|
|
||||||
|
mock_resp = AsyncMock()
|
||||||
|
mock_resp.status = 200
|
||||||
|
mock_resp.__aenter__ = AsyncMock(return_value=mock_resp)
|
||||||
|
mock_resp.__aexit__ = AsyncMock(return_value=False)
|
||||||
|
|
||||||
|
async def mock_scenarios() -> None:
|
||||||
|
await client.send_message("<b>🧠 Today's Scenarios</b>\n\n- AAPL: BUY (85)")
|
||||||
|
|
||||||
|
handler.register_command("scenarios", mock_scenarios)
|
||||||
|
|
||||||
|
with patch("aiohttp.ClientSession.post", return_value=mock_resp) as mock_post:
|
||||||
|
await handler._handle_update(
|
||||||
|
{"update_id": 1, "message": {"chat": {"id": 456}, "text": "/scenarios"}}
|
||||||
|
)
|
||||||
|
payload = mock_post.call_args.kwargs["json"]
|
||||||
|
assert "Today's Scenarios" in payload["text"]
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_review_command(self) -> None:
|
||||||
|
client = TelegramClient(bot_token="123:abc", chat_id="456", enabled=True)
|
||||||
|
handler = TelegramCommandHandler(client)
|
||||||
|
|
||||||
|
mock_resp = AsyncMock()
|
||||||
|
mock_resp.status = 200
|
||||||
|
mock_resp.__aenter__ = AsyncMock(return_value=mock_resp)
|
||||||
|
mock_resp.__aexit__ = AsyncMock(return_value=False)
|
||||||
|
|
||||||
|
async def mock_review() -> None:
|
||||||
|
await client.send_message("<b>📝 Recent Reviews</b>\n\n- 2026-02-14 KR")
|
||||||
|
|
||||||
|
handler.register_command("review", mock_review)
|
||||||
|
|
||||||
|
with patch("aiohttp.ClientSession.post", return_value=mock_resp) as mock_post:
|
||||||
|
await handler._handle_update(
|
||||||
|
{"update_id": 1, "message": {"chat": {"id": 456}, "text": "/review"}}
|
||||||
|
)
|
||||||
|
payload = mock_post.call_args.kwargs["json"]
|
||||||
|
assert "Recent Reviews" in payload["text"]
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_dashboard_command(self) -> None:
|
||||||
|
client = TelegramClient(bot_token="123:abc", chat_id="456", enabled=True)
|
||||||
|
handler = TelegramCommandHandler(client)
|
||||||
|
|
||||||
|
mock_resp = AsyncMock()
|
||||||
|
mock_resp.status = 200
|
||||||
|
mock_resp.__aenter__ = AsyncMock(return_value=mock_resp)
|
||||||
|
mock_resp.__aexit__ = AsyncMock(return_value=False)
|
||||||
|
|
||||||
|
async def mock_dashboard() -> None:
|
||||||
|
await client.send_message("<b>🖥️ Dashboard</b>\n\nURL: http://127.0.0.1:8080")
|
||||||
|
|
||||||
|
handler.register_command("dashboard", mock_dashboard)
|
||||||
|
|
||||||
|
with patch("aiohttp.ClientSession.post", return_value=mock_resp) as mock_post:
|
||||||
|
await handler._handle_update(
|
||||||
|
{"update_id": 1, "message": {"chat": {"id": 456}, "text": "/dashboard"}}
|
||||||
|
)
|
||||||
|
payload = mock_post.call_args.kwargs["json"]
|
||||||
|
assert "Dashboard" in payload["text"]
|
||||||
|
|
||||||
|
|
||||||
class TestGetUpdates:
|
class TestGetUpdates:
|
||||||
"""Test getUpdates API interaction."""
|
"""Test getUpdates API interaction."""
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user