1 line
7.0 KiB
JSON
1 line
7.0 KiB
JSON
{"repo": "akaradje/base-trading-agent", "files": {"CLAUDE.md": {"3d27b1659032694d7ae967ffc898b5cc3a101f02": {"t": 1785595239.9368405, "n": 6769, "h": "d2fc150f68d92a18", "c": "# CLAUDE.md\n\nThis file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.\n\n## Project Overview\n\nMulti-agent cryptocurrency trading bot for **Base blockchain** tokens (Coinbase L2). Currently in **paper trading** mode. Uses LLMs via OpenRouter for decision-making with a deterministic EMA/RSI fallback when no API key is set. Comments and README are in **Thai**.\n\n## Commands\n\n```bash\npip install -r requirements.txt # Install dependencies (requests, PyYAML, openai)\npython run.py run # Start 24/7 paper trading bot (Ctrl+C to stop)\npython run.py backtest --days 90 # Backtest deterministic strategy (no LLM)\npython run.py status # Show portfolio state\npython run.py health # Check bot health (heartbeat)\npython run.py --config path/to.yaml run # Custom config\npython -m compileall -q basebot run.py # Syntax check (no test suite exists)\n```\n\nSet `OPENROUTER_API_KEY` in `.env` (see `.env.example`) for LLM-powered agents. Without it, the bot runs in deterministic-only mode.\n\nOptional env vars for on-chain signals and alerting:\n- `GLASSNODE_API_KEY` — exchange flow signal (Glassnode)\n- `BASESCAN_API_KEY` — whale tracking on Base (Basescan)\n- `TELEGRAM_BOT_TOKEN` + `TELEGRAM_CHAT_ID` — Telegram alerts\n\n## Architecture\n\nThe pipeline is a multi-agent loop with deterministic safety rails that **always override** LLM output:\n\n```\nCoinGecko prices → EMA/RSI/ATR/Bollinger indicators\n │\n 0. RiskManager (deterministic): stop-loss, take-profit, trailing stop, tiered circuit breakers\n 0.5. Connectivity Kill Switch: data stale > 3 cycles → sell everything\n 1. Strategist (LLM): market regime (risk_on/neutral/risk_off), allowed symbols\n 1.5. OnChain Agent (deterministic): exchange flow, funding rate, whale signals → composite score\n 1.6. Liquidation Cascade (deterministic): OI drop + price move → mean-reversion signal (1.5x boost)\n 2. Analyst (LLM): action + conviction (assesses momentum from price action)\n 3. RiskCritic (LLM): approve/veto/shrink position size (called before chain conviction)\n 4. Confidence-Weighted Consensus: appetite × analyst_conv × onchain_conv × critic_size × cascade_boost\n 5. Executor: paper trade or on-chain swap (LiveExecutor uses GasOracle for L1/L2 fee breakdown)\n 6. Alerts: Telegram notifications for kill switches, emergencies, daily P&L\n 7. Training Collector: logs decisions + outcomes for LoRA fine-tuning\n```\n\n**Key invariant:** `risk.py` enforces stop-loss, take-profit, max position size, trailing stops, and tiered circuit breakers in code. LLM agents can only *reduce* trade activity, never increase it beyond these limits.\n\n## Source Layout\n\n| File | Role |\n|---|---|\n| `run.py` | CLI entry point (argparse: `run`, `backtest`, `status`, `health`) |\n| `config.yaml` | All configuration — mode, symbols, strategy params, risk params, agent models, onchain, alerts |\n| `basebot/config.py` | Loads `config.yaml` into `Config` dataclass |\n| `basebot/data.py` | CoinGecko API client with retry/backoff, OHLC endpoint |\n| `basebot/indicators.py` | Pure-Python EMA, RSI (Wilder), ATR, Bollinger Bands, crossover detection |\n| `basebot/portfolio.py` | Simulated portfolio with JSON persistence to `state/portfolio.json` (atomic save) |\n| `basebot/risk.py` | Deterministic risk rules — trailing stops, tiered circuit breakers, ATR-weighted sizing |\n| `basebot/executor.py` | `PaperExecutor` + `LiveExecutor` + `GasOracle` + `Multicall3Client` (batch reads) |\n| `basebot/llm.py` | OpenRouter client (OpenAI SDK). Forces JSON output. Graceful None on failure |\n| `basebot/orchestrator.py` | Full pipeline: risk exits → kill switch → strategist → onchain → liquidation → analyst → critic → consensus → executor |\n| `basebot/engine.py` | 24/7 loop: warmup → poll/orchestrate/save + connectivity kill switch + heartbeat healthcheck |\n| `basebot/backtest.py` | Historical replay, deterministic strategy only |\n| `basebot/alerts.py` | Telegram notifications for kill switches, emergencies, daily P&L |\n| `basebot/liquidation.py` | Liquidation cascade detection (OI tracking, mean-reversion signals) |\n| `basebot/agents/` | `strategist.py`, `analyst.py`, `risk_critic.py`, `onchain.py` |\n| `basebot/training/` | LoRA fine-tuning: `collector.py`, `dataset.py`, `train.py`, `inference.py` |\n\n## LLM Configuration\n\nAgents use OpenRouter with cost-optimized models configured in `config.yaml`:\n- **Strategist:** `qwen/qwen3.7-max`\n- **Analyst:** `qwen/qwen3-coder-flash`\n- **RiskCritic:** `xiaomi/mimo-v2.5-pro`\n\nAll agents force structured JSON output via `response_format=json_object` and schema in system prompts. The `_extract_json` helper in `llm.py` handles markdown code fences.\n\n## Dashboard\n\nReal-time monitoring dashboard built with **Next.js 15 + Phaser 3 + Supabase + ECharts**.\n\n```bash\ncd dashboard && npm install # Install dependencies\nnpm run dev # Start dev server (localhost:3000)\nnpm run build # Production build\n```\n\n**Architecture:**\n- **Phaser 3 canvas** renders a pixel-art isometric office with animated agent sprites\n- **React overlay** provides chat, analytics, and UI panels on top of the canvas\n- **EventBus** singleton bridges Phaser ↔ React for all interactions\n- **Supabase Realtime** subscribes to agent_states, portfolio, trades tables\n- **SSE Chat** streams agent responses via `/api/chat/stream` (proxies to `basebot.chat_server`)\n\n**Key files:**\n| File | Role |\n|---|---|\n| `dashboard/phaser/` | Phaser 3 scenes (Boot, Preload, Office) |\n| `dashboard/lib/EventBus.ts` | Phaser ↔ React event bridge |\n| `dashboard/components/chat/` | Chat UI (ChatBox, ContactList, Message, Input) |\n| `dashboard/components/analytics/` | ECharts dashboards (tokens, P&L, activity, cost) |\n| `dashboard/components/office/` | AgentStatusBar, PhaserGame wrapper |\n| `dashboard/app/api/chat/stream/` | Next.js API route → Python chat server proxy |\n| `basebot/chat_server.py` | FastAPI SSE server wrapping agent pipeline |\n\n**Run chat backend:**\n```bash\npip install fastapi uvicorn\npython -m basebot.chat_server # Starts on port 8001\n```\n\n## Development Notes\n\n- **No test suite, linter, formatter, or CI/CD exists.** Use `python -m compileall -q basebot run.py` to catch syntax errors.\n- Portfolio state persists to `basebot/state/portfolio.json` (gitignored).\n- `LiveExecutor` is intentionally unimplemented — intended for Base MCP on-chain swaps.\n- The Strategist agent result is cached and refreshes every ~30 min.\n- `.env` and `state/` are gitignored — never commit API keys or portfolio state.\n- **Deployment:** `deploy/` contains systemd service, Dockerfile, and docker-compose.yml. Use `python run.py health` for healthcheck (exit 0=healthy, 1=unhealthy).\n"}}}} |