Files
The-Ouroboros/CLAUDE.md
agentson 6b34367656
Some checks failed
Gitea CI / test (push) Failing after 3s
Gitea CI / test (pull_request) Failing after 3s
docs: v2/v3 구현 감사 문서 피드백 전체 반영 (#349)
11회 리뷰 사이클에서 남긴 [코멘트]를 모두 본문에 반영하고 블록을 제거한다.

변경 문서:
- docs/architecture.md: SmartScanner 동작 모드(both), 대시보드 10 API,
  DB 스키마(session_id/fx_pnl/mode), config 변수 갱신
- docs/commands.md: /api/pnl/history, /api/positions 엔드포인트 추가
- docs/testing.md: 테스트 수 고정값 제거, SmartScanner fallback 최신화,
  Dashboard 10 API routes 반영
- README.md: 고정 수치 제거, Gitea CI 명시, 파일별 수치 'CI 기준 변동' 표기
- CLAUDE.md: SmartScanner 섹션명 변경, 고정 수치 제거
- docs/requirements-log.md: #318~#331 구현 항목 추가
- docs/ouroboros/80_implementation_audit.md: ROOT-5/6/7 분리,
  REQ-V3-008 함수명 병기, v3 ~85% / 거버넌스 ~60%로 갱신
- docs/ouroboros/85_loss_recovery_action_plan.md: ACT-07 함수명 병기,
  테스트 수 갱신, 6.1/6.2 정확도 개선
- docs/ouroboros/60_repo_enforcement_checklist.md: CI job/step 구분 표 추가
- docs/ouroboros/README.md: 50_* 문서 (A)/(B) 보조 표기

Closes #349
2026-03-01 17:06:56 +09:00

7.2 KiB
Raw Permalink Blame History

The Ouroboros

AI-powered trading agent for global stock markets with self-evolution capabilities.

Quick Start

# Setup
pip install -e ".[dev]"
cp .env.example .env
# Edit .env with your KIS and Gemini API credentials

# Test
pytest -v --cov=src

# Run (paper trading)
python -m src.main --mode=paper

# Run with dashboard
python -m src.main --mode=paper --dashboard

Telegram Notifications (Optional)

Get real-time alerts for trades, circuit breakers, and system events via Telegram.

Quick Setup

  1. Create bot: Message @BotFather on Telegram → /newbot
  2. Get chat ID: Message @userinfobot/start
  3. Configure: Add to .env:
    TELEGRAM_BOT_TOKEN=1234567890:ABCdefGHIjklMNOpqrsTUVwxyz
    TELEGRAM_CHAT_ID=123456789
    TELEGRAM_ENABLED=true
    
  4. Test: Start bot conversation (/start), then run the agent

Full documentation: src/notifications/README.md

What You'll Get

  • 🟢 Trade execution alerts (BUY/SELL with confidence)
  • 🚨 Circuit breaker trips (automatic trading halt)
  • ⚠️ Fat-finger rejections (oversized orders blocked)
  • Market open/close notifications
  • 📝 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.

Smart Volatility Scanner (Optional)

Python-first filtering pipeline that reduces Gemini API calls by pre-filtering stocks using technical indicators.

How It Works

  1. Fetch Rankings — KIS API volume surge rankings (top 30 stocks)
  2. Python Filter — RSI + volume ratio calculations (no AI)
    • Volume > 200% of previous day
    • RSI(14) < 30 (oversold) OR RSI(14) > 70 (momentum)
  3. AI Judgment — Only qualified candidates (1-3 stocks) sent to Gemini

Configuration

Add to .env (optional, has sensible defaults):

RSI_OVERSOLD_THRESHOLD=30    # 0-50, default 30
RSI_MOMENTUM_THRESHOLD=70    # 50-100, default 70
VOL_MULTIPLIER=2.0           # Volume threshold (2.0 = 200%)
SCANNER_TOP_N=3              # Max candidates per scan

Benefits

  • Reduces API costs — Process 1-3 stocks instead of 20-30
  • Python-based filtering — Fast technical analysis before AI
  • Evolution-ready — Selection context logged for strategy optimization
  • Fault-tolerant — Falls back to static watchlist on API failure

Trading Mode Integration

Smart Scanner runs in both TRADE_MODE=realtime and daily paths. On API failure, domestic stocks fall back to a static watchlist; overseas stocks fall back to a dynamic universe (active positions, recent holdings).

Documentation

Core Principles

  1. Safety First — Risk manager is READ-ONLY and enforces circuit breakers
  2. Test Everything — 80% coverage minimum, all changes require tests
  3. Issue-Driven Development — All work goes through Gitea issues → feature branches → PRs
  4. Agent Specialization — Use dedicated agents for design, coding, testing, docs, review

Requirements Management

User requirements and feedback are tracked in docs/requirements-log.md:

  • New requirements are added chronologically with dates
  • Code changes should reference related requirements
  • Helps maintain project evolution aligned with user needs
  • Preserves context across conversations and development cycles

Project Structure

src/
├── 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)
├── context/         # L1-L7 hierarchical memory system
├── core/            # Risk manager (READ-ONLY)
├── dashboard/       # FastAPI read-only monitoring (10 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
├── notifications/   # Telegram alerts + bidirectional commands (9 commands)
├── strategy/        # Pre-market planner, scenario engine, playbook store
├── db.py            # SQLite trade logging
├── main.py          # Trading loop orchestrator
└── config.py        # Settings (from .env)

tests/               # 998 tests across 41 files
docs/                # Extended documentation

Key Commands

pytest -v --cov=src              # Run tests with coverage
ruff check src/ tests/           # Lint
mypy src/ --strict               # Type check

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)

# Gitea workflow (requires tea CLI)
YES="" ~/bin/tea issues create --repo jihoson/The-Ouroboros --title "..." --description "..."
YES="" ~/bin/tea pulls create --head feature-branch --base main --title "..." --description "..."

Markets Supported

  • 🇰🇷 Korea (KRX)
  • 🇺🇸 United States (NASDAQ, NYSE, AMEX)
  • 🇯🇵 Japan (TSE)
  • 🇭🇰 Hong Kong (SEHK)
  • 🇨🇳 China (Shanghai, Shenzhen)
  • 🇻🇳 Vietnam (Hanoi, HCM)

Markets auto-detected based on timezone and enabled in ENABLED_MARKETS env variable.

Critical Constraints

⚠️ Non-Negotiable Rules (see docs/agents.md):

  • src/core/risk_manager.py is READ-ONLY — changes require human approval
  • Circuit breaker at -3.0% P&L — may only be made stricter
  • Fat-finger protection: max 30% of cash per order — always enforced
  • Confidence 임계값 (market_outlook별, 낮출 수 없음): BEARISH ≥ 90, NEUTRAL/기본 ≥ 80, BULLISH ≥ 75
  • All code changes → corresponding tests → coverage ≥ 80%

Contributing

See docs/workflow.md for the complete development process.

TL;DR:

  1. Create issue in Gitea
  2. Create feature branch: feature/issue-N-description
  3. Implement with tests
  4. Open PR
  5. Merge after review