diff --git a/README.md b/README.md
index 60b2aa4..6fc0b3f 100644
--- a/README.md
+++ b/README.md
@@ -4,32 +4,12 @@
[](https://python.org)
[](LICENSE)
-[](./Communication.md)
-[](./Communication.md)
+[](https://docker.com)
+[](https://fastapi.tiangolo.com)
-**Five AIs battle for NASDAQ 100 supremacy. Zero human input. Pure competition.**
+**REST API service for autonomous AI trading competitions. Run multiple AI models in NASDAQ 100 trading simulations with zero human intervention.**
-## ๐ Current Championship Leaderboard ๐
-[*Click Here: AI Live Trading*](https://hkuds.github.io/AI-Trader/)
-
-
-
-### **Championship Period: (Last Update 2025/10/29)**
-
-| ๐ Rank | ๐ค AI Model | ๐ Total Earnings |
-|---------|-------------|----------------|
-| **๐ฅ 1st** | **DeepSeek** | ๐ +16.46% |
-| ๐ฅ 2nd | MiniMax-M2 | ๐ +12.03% |
-| ๐ฅ 3rd | GPT-5 | ๐ +9.98% |
-| 4th | Claude-3.7 | ๐ +9.80% |
-| 5th | Qwen3-max | ๐ +7.96% |
-| Baseline | QQQ | ๐ +5.39% |
-| 6th | Gemini-2.5-flash | ๐ +0.48% |
-
-### ๐ **Live Performance Dashboard**
-
-
-*Daily Performance Tracking of AI Models in NASDAQ 100 Trading*
+[๐ Quick Start](#-quick-start) โข [๐ API Documentation](#-api-documentation) โข [๐ณ Docker Deployment](#-docker-deployment) โข [ไธญๆๆๆกฃ](README_CN.md)
@@ -39,209 +19,123 @@
**Major Architecture Upgrade - REST API Service**
-- ๐ **REST API Server** - Complete FastAPI implementation for external orchestration
- - Trigger simulations via HTTP POST
- - Monitor job progress in real-time
- - Query results with flexible filtering
- - Health checks and monitoring
-- ๐พ **SQLite Database** - Full persistence layer with 6 relational tables
+- ๐ **REST API Server** - Complete FastAPI implementation
+ - `POST /simulate/trigger` - Start simulation jobs
+ - `GET /simulate/status/{job_id}` - Monitor progress
+ - `GET /results` - Query results with filtering
+ - `GET /health` - Service health checks
+- ๐พ **SQLite Database** - Persistent storage
- Job tracking and lifecycle management
- Position records with P&L tracking
- AI reasoning logs and tool usage analytics
-- ๐ณ **Docker Deployment** - Persistent REST API service
+- ๐ณ **Production-Ready Docker** - Single-command deployment
- Health checks and automatic restarts
- - Volume persistence for database and logs
-- ๐งช **Comprehensive Testing** - 102 tests with 85% coverage
- - Unit tests for all components
- - Integration tests for API endpoints
- - Validation scripts for Docker deployment
-- ๐ **Production Documentation** - Complete deployment guides
- - DOCKER_API.md - API deployment and usage
- - TESTING_GUIDE.md - Validation procedures
+ - Volume persistence for data and logs
+ - Simplified configuration
+- ๐งช **Comprehensive Testing** - 102 tests, 85% coverage
+- ๐ **Complete Documentation** - Deployment and validation guides
-See [CHANGELOG.md](CHANGELOG.md) for full details.
+See [CHANGELOG.md](CHANGELOG.md) for full release notes.
---
-[๐ Quick Start](#-quick-start) โข [๐ Performance Analysis](#-performance-analysis) โข [๐ ๏ธ Configuration Guide](#-configuration-guide) โข [ไธญๆๆๆกฃ](README_CN.md)
+## ๐ What is AI-Trader?
-
-
----
-
-## ๐ Project Introduction
-
-> **AI-Trader enables five distinct AI models, each employing unique investment strategies, to compete autonomously in the same market and determine which can generate the highest profits in NASDAQ 100 trading!**
+> **AI-Trader enables multiple AI models to compete autonomously in NASDAQ 100 trading, making 100% independent decisions through a standardized tool-based architecture.**
### ๐ฏ Core Features
-- ๐ค **Fully Autonomous Decision-Making**: AI agents perform 100% independent analysis, decision-making, and execution without human intervention
-- ๐ ๏ธ **Pure Tool-Driven Architecture**: Built on MCP toolchain, enabling AI to complete all trading operations through standardized tool calls
-- ๐ **Multi-Model Competition Arena**: Deploy multiple AI models (GPT, Claude, Qwen, etc.) for competitive trading
-- ๐ **Real-Time Performance Analytics**: Comprehensive trading records, position monitoring, and profit/loss analysis
-- ๐ **Intelligent Market Intelligence**: Integrated Jina search for real-time market news and financial reports
-- โก **MCP Toolchain Integration**: Modular tool ecosystem based on Model Context Protocol
-- ๐ **Extensible Strategy Framework**: Support for third-party strategies and custom AI agent integration
-- โฐ **Historical Replay Capability**: Time-period replay functionality with automatic future information filtering
+- ๐ค **Fully Autonomous Trading** - AI agents analyze, decide, and execute without human intervention
+- ๐ **REST API Architecture** - Trigger simulations and monitor results via HTTP
+- ๐ ๏ธ **MCP Toolchain** - Standardized tools for market research, price queries, and trade execution
+- ๐ **Multi-Model Competition** - Deploy GPT, Claude, Qwen, DeepSeek, or custom models
+- ๐ **Real-Time Analytics** - Track positions, P&L, and AI decision reasoning
+- โฐ **Historical Replay** - Backtest with anti-look-ahead controls
+- ๐พ **Persistent Storage** - SQLite database for all results and analytics
+- ๐ **External Orchestration** - Integrate with Windmill.dev or any HTTP client
---
-### ๐ฎ Trading Environment
-Each AI model starts with $10,000 to trade NASDAQ 100 stocks in a controlled environment with real market data and historical replay capabilities.
-
-- ๐ฐ **Initial Capital**: $10,000 USD starting balance
-- ๐ **Trading Universe**: NASDAQ 100 component stocks (top 100 technology stocks)
-- โฐ **Trading Schedule**: Weekday market hours with historical simulation support
-- ๐ **Data Integration**: Alpha Vantage API combined with Jina AI market intelligence
-- ๐ **Time Management**: Historical period replay with automated future information filtering
-
----
-
-### ๐ง Agentic Trading Capabilities
-AI agents operate with complete autonomy, conducting market research, making trading decisions, and continuously evolving their strategies without human intervention.
-
-- ๐ฐ **Autonomous Market Research**: Intelligent retrieval and filtering of market news, analyst reports, and financial data
-- ๐ก **Independent Decision Engine**: Multi-dimensional analysis driving fully autonomous buy/sell execution
-- ๐ **Comprehensive Trade Logging**: Automated documentation of trading rationale, execution details, and portfolio changes
-- ๐ **Adaptive Strategy Evolution**: Self-optimizing algorithms that adjust based on market performance feedback
-
----
-
-### ๐ Competition Rules
-All AI models compete under identical conditions with the same capital, data access, tools, and evaluation metrics to ensure fair comparison.
-
-- ๐ฐ **Starting Capital**: $10,000 USD initial investment
-- ๐ **Data Access**: Uniform market data and information feeds
-- โฐ **Operating Hours**: Synchronized trading time windows
-- ๐ **Performance Metrics**: Standardized evaluation criteria across all models
-- ๐ ๏ธ **Tool Access**: Identical MCP toolchain for all participants
-
-๐ฏ **Objective**: Determine which AI model achieves superior investment returns through pure autonomous operation!
-
-### ๐ซ Zero Human Intervention
-AI agents operate with complete autonomy, making all trading decisions and strategy adjustments without any human programming, guidance, or intervention.
-
-- โ **No Pre-Programming**: Zero preset trading strategies or algorithmic rules
-- โ **No Human Input**: Complete reliance on inherent AI reasoning capabilities
-- โ **No Manual Override**: Absolute prohibition of human intervention during trading
-- โ
**Tool-Only Execution**: All operations executed exclusively through standardized tool calls
-- โ
**Self-Adaptive Learning**: Independent strategy refinement based on market performance feedback
-
----
-
-## โฐ Historical Replay Architecture
-
-A core innovation of AI-Trader Bench is its **fully replayable** trading environment, ensuring scientific rigor and reproducibility in AI agent performance evaluation on historical market data.
-
-### ๐ Temporal Control Framework
-
-#### ๐
Flexible Time Settings
-```json
-{
- "date_range": {
- "init_date": "2025-01-01", // Any start date
- "end_date": "2025-01-31" // Any end date
- }
-}
-```
----
-
-### ๐ก๏ธ Anti-Look-Ahead Data Controls
-AI can only access market data from current time and before. No future information allowed.
-
-- ๐ **Price Data Boundaries**: Market data access limited to simulation timestamp and historical records
-- ๐ฐ **News Chronology Enforcement**: Real-time filtering prevents access to future-dated news and announcements
-- ๐ **Financial Report Timeline**: Information restricted to officially published data as of current simulation date
-- ๐ **Historical Intelligence Scope**: Market analysis constrained to chronologically appropriate data availability
-
-### ๐ฏ Replay Advantages
-
-#### ๐ฌ Empirical Research Framework
-- ๐ **Market Efficiency Studies**: Evaluate AI performance across diverse market conditions and volatility regimes
-- ๐ง **Decision Consistency Analysis**: Examine temporal stability and behavioral patterns in AI trading logic
-- ๐ **Risk Management Assessment**: Validate effectiveness of AI-driven risk mitigation strategies
-
-#### ๐ฏ Fair Competition Framework
-- ๐ **Equal Information Access**: All AI models operate with identical historical datasets
-- ๐ **Standardized Evaluation**: Performance metrics calculated using uniform data sources
-- ๐ **Full Reproducibility**: Complete experimental transparency with verifiable results
-
----
-
-## ๐ Project Architecture
+## ๐๏ธ Architecture
```
-AI-Trader Bench/
-โโโ ๐ค Core System
-โ โโโ main.py # ๐ฏ Main program entry
-โ โโโ agent/base_agent/ # ๐ง AI agent core
-โ โโโ configs/ # โ๏ธ Configuration files
-โ
-โโโ ๐ ๏ธ MCP Toolchain
-โ โโโ agent_tools/
-โ โ โโโ tool_trade.py # ๐ฐ Trade execution
-โ โ โโโ tool_get_price_local.py # ๐ Price queries
-โ โ โโโ tool_jina_search.py # ๐ Information search
-โ โ โโโ tool_math.py # ๐งฎ Mathematical calculations
-โ โโโ tools/ # ๐ง Auxiliary tools
-โ
-โโโ ๐ Data System
-โ โโโ data/
-โ โ โโโ daily_prices_*.json # ๐ Stock price data
-โ โ โโโ merged.jsonl # ๐ Unified data format
-โ โ โโโ agent_data/ # ๐ AI trading records
-โ โโโ calculate_performance.py # ๐ Performance analysis
-โ
-โโโ ๐จ Frontend Interface
-โ โโโ frontend/ # ๐ Web dashboard
-โ
-โโโ ๐ Configuration & Documentation
- โโโ configs/ # โ๏ธ System configuration
- โโโ prompts/ # ๐ฌ AI prompts
- โโโ calc_perf.sh # ๐ Performance calculation script
+โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
+โ REST API (Port 8080) โ
+โ POST /simulate/trigger โ GET /status โ GET /results โ
+โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
+ โ
+ โผ
+โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
+โ Simulation Worker โ
+โ โข Job Manager (concurrent job prevention) โ
+โ โข Date-sequential, model-parallel execution โ
+โ โข Isolated runtime configs per model-day โ
+โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
+ โ
+ โโโโโโโโโโโโโโโดโโโโโโโโโโโโโโ
+ โผ โผ
+โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
+โ AI Agent (Model-Day) โ โ SQLite Database โ
+โ โข GPT-4, Claude, etc. โ โ โข Jobs & Details โ
+โ โข MCP Tool Access โ โ โข Positions & Holdings โ
+โ โข Decision Logging โ โ โข Reasoning Logs โ
+โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
+ โ
+ โผ
+โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
+โ MCP Services (Internal) โ
+โ โข Math (8000) โข Search (8001) โข Trade (8002) โ
+โ โข Price (8003) - All localhost-only โ
+โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
```
-### ๐ง Core Components Details
+### Key Components
-#### ๐ฏ Main Program (`main.py`)
-- **Multi-Model Concurrency**: Run multiple AI models simultaneously for trading
-- **Configuration Management**: Support for JSON configuration files and environment variables
-- **Date Management**: Flexible trading calendar and date range settings
-- **Error Handling**: Comprehensive exception handling and retry mechanisms
+- **FastAPI Server** - RESTful interface for job management and results
+- **Job Manager** - Coordinates simulation execution, prevents concurrent jobs
+- **Simulation Worker** - Orchestrates date-sequential, model-parallel execution
+- **Model-Day Executor** - Runs single model for single date with isolated config
+- **SQLite Database** - Persistent storage with 6 relational tables
+- **MCP Services** - Internal tool ecosystem (math, search, trade, price)
-#### ๐ ๏ธ MCP Toolchain
-| Tool | Function | API |
-|------|----------|-----|
-| **Trading Tool** | Buy/sell stocks, position management | `buy()`, `sell()` |
-| **Price Tool** | Real-time and historical price queries | `get_price_local()` |
-| **Search Tool** | Market information search | `get_information()` |
-| **Math Tool** | Financial calculations and analysis | Basic mathematical operations |
-
-#### ๐ Data System
-- **๐ Price Data**: Complete OHLCV data for NASDAQ 100 component stocks
-- **๐ Trading Records**: Detailed trading history for each AI model
-- **๐ Performance Metrics**: Sharpe ratio, maximum drawdown, annualized returns, etc.
-- **๐ Data Synchronization**: Automated data acquisition and update mechanisms
+---
## ๐ Quick Start
-### ๐ณ **Docker Deployment (Recommended)**
+### ๐ณ Docker Deployment (Recommended)
-#### ๐ REST API Server (Windmill Integration)
+**1. Prerequisites**
+- Docker and Docker Compose installed
+- API keys: OpenAI, Alpha Vantage, Jina AI
+
+**2. Setup**
```bash
-# 1. Clone and configure
+# Clone repository
git clone https://github.com/Xe138/AI-Trader.git
cd AI-Trader
-cp .env.example .env
-# Edit .env and add your API keys
-# 2. Start API server
+# Configure environment
+cp .env.example .env
+# Edit .env and add your API keys:
+# OPENAI_API_KEY=your_key_here
+# ALPHAADVANTAGE_API_KEY=your_key_here
+# JINA_API_KEY=your_key_here
+```
+
+**3. Start API Server**
+```bash
+# Start in background
docker-compose up -d
-# 3. Test API
-curl http://localhost:8080/health
+# View logs
+docker logs -f ai-trader
-# 4. Trigger simulation
+# Verify health
+curl http://localhost:8080/health
+```
+
+**4. Trigger Simulation**
+```bash
curl -X POST http://localhost:8080/simulate/trigger \
-H "Content-Type: application/json" \
-d '{
@@ -251,180 +145,136 @@ curl -X POST http://localhost:8080/simulate/trigger \
}'
```
-See [DOCKER_API.md](DOCKER_API.md) for complete API documentation and [TESTING_GUIDE.md](TESTING_GUIDE.md) for validation procedures.
+**5. Monitor Progress**
+```bash
+# Get job status (use job_id from trigger response)
+curl http://localhost:8080/simulate/status/{job_id}
+
+# View results
+curl http://localhost:8080/results?job_id={job_id}
+```
---
-### ๐ป **Local Installation (Development)**
+## ๐ API Documentation
-#### ๐ Prerequisites
+### Endpoints
-- **Python 3.10+**
-- **API Keys**: OpenAI, Alpha Vantage, Jina AI
-- **Optional**: Docker (for containerized deployment)
+#### `POST /simulate/trigger`
+Start a new simulation job.
-#### โก Installation Steps
-
-```bash
-# 1. Clone project
-git clone https://github.com/Xe138/AI-Trader.git
-cd AI-Trader
-
-# 2. Install dependencies
-pip install -r requirements.txt
-
-# 3. Configure environment variables
-cp .env.example .env
-# Edit .env file and fill in your API keys
-```
-
-### ๐ Environment Configuration
-
-Create `.env` file and configure the following variables:
-
-```bash
-# ๐ค AI Model API Configuration
-OPENAI_API_BASE=https://your-openai-proxy.com/v1
-OPENAI_API_KEY=your_openai_key
-
-# ๐ Data Source Configuration
-ALPHAADVANTAGE_API_KEY=your_alpha_vantage_key
-JINA_API_KEY=your_jina_api_key
-
-# ๐ง AI Agent Configuration
-AGENT_MAX_STEP=30 # Maximum reasoning steps
-```
-
-### ๐ฆ Dependencies
-
-```bash
-# Install production dependencies
-pip install -r requirements.txt
-
-# Or manually install core dependencies
-pip install langchain langchain-openai langchain-mcp-adapters fastmcp python-dotenv requests numpy pandas
-```
-
-## ๐ฎ Running Guide
-
-### ๐ Step 1: Data Preparation (`./fresh_data.sh`)
-
-```bash
-# ๐ Get NASDAQ 100 stock data
-cd data
-python get_daily_price.py
-
-# ๐ Merge data into unified format
-python merge_jsonl.py
-```
-
-### ๐ ๏ธ Step 2: Start MCP Services
-
-```bash
-cd ./agent_tools
-python start_mcp_services.py
-```
-
-### ๐ Step 3: Start AI Arena
-
-```bash
-# ๐ฏ Run main program - let AIs start trading!
-python main.py
-
-# ๐ฏ Or use custom configuration
-python main.py configs/my_config.json
-```
-
-### โฐ Time Settings Example
-
-#### ๐
Create Custom Time Configuration
+**Request:**
```json
{
- "agent_type": "BaseAgent",
- "date_range": {
- "init_date": "2024-01-01", // Backtest start date
- "end_date": "2024-03-31" // Backtest end date
+ "config_path": "/app/configs/default_config.json",
+ "date_range": ["2025-01-16", "2025-01-17"],
+ "models": ["gpt-4", "claude-3.7-sonnet"]
+}
+```
+
+**Response:**
+```json
+{
+ "job_id": "550e8400-e29b-41d4-a716-446655440000",
+ "status": "pending",
+ "total_model_days": 4,
+ "message": "Simulation job created and started"
+}
+```
+
+#### `GET /simulate/status/{job_id}`
+Query job execution status and progress.
+
+**Response:**
+```json
+{
+ "job_id": "550e8400-...",
+ "status": "running",
+ "progress": {
+ "completed": 2,
+ "failed": 0,
+ "pending": 2,
+ "total": 4
},
- "models": [
+ "details": [
{
- "name": "claude-3.7-sonnet",
- "basemodel": "anthropic/claude-3.7-sonnet",
- "signature": "claude-3.7-sonnet",
- "enabled": true
+ "model_signature": "gpt-4",
+ "trading_date": "2025-01-16",
+ "status": "completed",
+ "start_time": "2025-01-16T10:00:00",
+ "end_time": "2025-01-16T10:05:00"
}
]
}
```
-### ๐ Start Web Interface
+#### `GET /results`
+Retrieve simulation results with optional filtering.
-```bash
-cd docs
-python3 -m http.server 8000
-# Visit http://localhost:8000
+**Query Parameters:**
+- `job_id` - Filter by job UUID
+- `date` - Filter by trading date (YYYY-MM-DD)
+- `model` - Filter by model signature
+
+**Response:**
+```json
+{
+ "count": 2,
+ "results": [
+ {
+ "job_id": "550e8400-...",
+ "model_signature": "gpt-4",
+ "trading_date": "2025-01-16",
+ "final_cash": 9850.50,
+ "total_value": 10250.75,
+ "profit_loss": 250.75,
+ "positions": {...},
+ "holdings": [...]
+ }
+ ]
+}
```
-## ๐ณ Docker Deployment
+#### `GET /health`
+Service health check.
-### Using Docker Compose (Recommended)
-
-The easiest way to run AI-Trader is with Docker Compose:
-
-```bash
-# 1. Clone and setup
-git clone https://github.com/Xe138/AI-Trader.git
-cd AI-Trader
-
-# 2. Configure environment
-cp .env.example .env
-# Edit .env with your API keys:
-# - OPENAI_API_KEY
-# - ALPHAADVANTAGE_API_KEY
-# - JINA_API_KEY
-
-# 3. Run with Docker Compose
-docker-compose up
+**Response:**
+```json
+{
+ "status": "healthy",
+ "database": "connected",
+ "timestamp": "2025-01-16T10:00:00Z"
+}
```
-The container automatically:
-- Fetches latest NASDAQ 100 price data
-- Starts all MCP services
-- Runs AI trading agents
-
-### Using Pre-built Images
-
-Pull and run pre-built images from GitHub Container Registry:
-
-```bash
-# Pull latest version
-docker pull ghcr.io/hkuds/ai-trader:latest
-
-# Run container
-docker run --env-file .env \
- -v $(pwd)/data:/app/data \
- -v $(pwd)/logs:/app/logs \
- ghcr.io/hkuds/ai-trader:latest
-```
-
-**๐ See [docs/DOCKER.md](docs/DOCKER.md) for detailed Docker usage, troubleshooting, and advanced configuration.**
-
---
-## ๐ Performance Analysis
+## ๐ ๏ธ Configuration
-### ๐ Competition Rules
+### Environment Variables
-| Rule Item | Setting | Description |
-|-----------|---------|-------------|
-| **๐ฐ Initial Capital** | $10,000 | Starting capital for each AI model |
-| **๐ Trading Targets** | NASDAQ 100 | 100 top tech stocks |
-| **โฐ Trading Hours** | Weekdays | Monday to Friday |
-| **๐ฒ Price Benchmark** | Opening Price | Trade using daily opening price |
-| **๐ Recording Method** | JSONL Format | Complete trading history records |
+```bash
+# AI Model API Configuration
+OPENAI_API_BASE= # Optional: custom OpenAI proxy
+OPENAI_API_KEY=your_key_here # Required: OpenAI API key
-## โ๏ธ Configuration Guide
+# Data Source Configuration
+ALPHAADVANTAGE_API_KEY=your_key_here # Required: Alpha Vantage
+JINA_API_KEY=your_key_here # Required: Jina AI search
-### ๐ Configuration File Structure
+# API Server Port (host-side mapping)
+API_PORT=8080 # Change if port 8080 is occupied
+
+# Agent Configuration
+AGENT_MAX_STEP=30 # Maximum reasoning steps per day
+
+# Data Volume Configuration
+VOLUME_PATH=. # Base directory for persistent data
+```
+
+### Configuration File
+
+Create custom configs in `configs/` directory:
```json
{
@@ -435,16 +285,15 @@ docker run --env-file .env \
},
"models": [
{
- "name": "claude-3.7-sonnet",
- "basemodel": "anthropic/claude-3.7-sonnet",
- "signature": "claude-3.7-sonnet",
+ "name": "GPT-4",
+ "basemodel": "openai/gpt-4",
+ "signature": "gpt-4",
"enabled": true
}
],
"agent_config": {
"max_steps": 30,
"max_retries": 3,
- "base_delay": 1.0,
"initial_cash": 10000.0
},
"log_config": {
@@ -453,236 +302,287 @@ docker run --env-file .env \
}
```
-### ๐ง Configuration Parameters
+---
-| Parameter | Description | Default Value |
-|-----------|-------------|---------------|
-| `agent_type` | AI agent type | "BaseAgent" |
-| `max_steps` | Maximum reasoning steps | 30 |
-| `max_retries` | Maximum retry attempts | 3 |
-| `base_delay` | Operation delay (seconds) | 1.0 |
-| `initial_cash` | Initial capital | $10,000 |
+## ๐งช Testing & Validation
-### ๐ Data Format
+### Automated Validation
-#### ๐ฐ Position Records (position.jsonl)
-```json
-{
- "date": "2025-01-20",
- "id": 1,
- "this_action": {
- "action": "buy",
- "symbol": "AAPL",
- "amount": 10
- },
- "positions": {
- "AAPL": 10,
- "MSFT": 0,
- "CASH": 9737.6
- }
-}
+```bash
+# Make scripts executable
+chmod +x scripts/*.sh
+
+# Validate Docker build and startup
+bash scripts/validate_docker_build.sh
+
+# Test all API endpoints
+bash scripts/test_api_endpoints.sh
```
-#### ๐ Price Data (merged.jsonl)
-```json
-{
- "Meta Data": {
- "2. Symbol": "AAPL",
- "3. Last Refreshed": "2025-01-20"
- },
- "Time Series (Daily)": {
- "2025-01-20": {
- "1. buy price": "255.8850",
- "2. high": "264.3750",
- "3. low": "255.6300",
- "4. sell price": "262.2400",
- "5. volume": "90483029"
+### Manual Testing
+
+```bash
+# 1. Start API server
+docker-compose up -d
+
+# 2. Health check
+curl http://localhost:8080/health
+
+# 3. Trigger small test job
+curl -X POST http://localhost:8080/simulate/trigger \
+ -H "Content-Type: application/json" \
+ -d '{
+ "config_path": "/app/configs/default_config.json",
+ "date_range": ["2025-01-16"],
+ "models": ["gpt-4"]
+ }'
+
+# 4. Monitor until complete
+curl http://localhost:8080/simulate/status/{job_id}
+
+# 5. View results
+curl http://localhost:8080/results?job_id={job_id}
+```
+
+See [TESTING_GUIDE.md](TESTING_GUIDE.md) for comprehensive testing procedures and troubleshooting.
+
+---
+
+## ๐ฏ Trading Environment
+
+- ๐ฐ **Initial Capital**: $10,000 per AI model
+- ๐ **Trading Universe**: NASDAQ 100 stocks
+- โฐ **Trading Schedule**: Weekdays only (historical simulation)
+- ๐ **Data Sources**: Alpha Vantage (prices) + Jina AI (market intelligence)
+- ๐ **Anti-Look-Ahead**: Data access limited to current date and earlier
+
+---
+
+## ๐ง AI Agent Capabilities
+
+Through the MCP (Model Context Protocol) toolchain, AI agents can:
+
+- ๐ฐ **Research Markets** - Search news, analyst reports, financial data (Jina AI)
+- ๐ **Query Prices** - Get real-time and historical OHLCV data
+- ๐ฐ **Execute Trades** - Buy/sell stocks, manage positions
+- ๐งฎ **Perform Calculations** - Mathematical analysis and computations
+- ๐ **Log Reasoning** - Document decision-making process
+
+**All operations are 100% autonomous - zero human intervention or pre-programmed strategies.**
+
+---
+
+## ๐ Project Structure
+
+```
+AI-Trader/
+โโโ api/ # FastAPI application
+โ โโโ main.py # API server entry point
+โ โโโ database.py # SQLite schema and operations
+โ โโโ job_manager.py # Job lifecycle management
+โ โโโ simulation_worker.py # Job orchestration
+โ โโโ model_day_executor.py # Single model-day execution
+โ โโโ runtime_manager.py # Isolated runtime configs
+โ โโโ models.py # Pydantic request/response models
+โ
+โโโ agent/ # AI agent core
+โ โโโ base_agent/
+โ โโโ base_agent.py # BaseAgent implementation
+โ
+โโโ agent_tools/ # MCP service implementations
+โ โโโ tool_math.py # Mathematical calculations
+โ โโโ tool_jina_search.py # Market intelligence search
+โ โโโ tool_trade.py # Trading execution
+โ โโโ tool_get_price_local.py # Price queries
+โ โโโ start_mcp_services.py # Service orchestration
+โ
+โโโ tests/ # Test suite (102 tests, 85% coverage)
+โ โโโ unit/ # Unit tests
+โ โโโ integration/ # Integration tests
+โ
+โโโ configs/ # Configuration files
+โ โโโ default_config.json # Default simulation config
+โ
+โโโ scripts/ # Validation scripts
+โ โโโ validate_docker_build.sh # Docker build validation
+โ โโโ test_api_endpoints.sh # API endpoint testing
+โ
+โโโ data/ # Persistent data (volume mount)
+โ โโโ jobs.db # SQLite database
+โ โโโ agent_data/ # Agent execution data
+โ
+โโโ docker-compose.yml # Docker orchestration
+โโโ Dockerfile # Container image definition
+โโโ entrypoint.sh # Container startup script
+โโโ requirements.txt # Python dependencies
+โโโ README.md # This file
+```
+
+---
+
+## ๐ Integration Examples
+
+### Windmill.dev Workflow
+
+```typescript
+// Trigger simulation
+export async function triggerSimulation(
+ api_url: string,
+ config_path: string,
+ date_range: string[],
+ models: string[]
+) {
+ const response = await fetch(`${api_url}/simulate/trigger`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ config_path, date_range, models })
+ });
+ return response.json();
+}
+
+// Poll for completion
+export async function waitForCompletion(api_url: string, job_id: string) {
+ while (true) {
+ const status = await fetch(`${api_url}/simulate/status/${job_id}`)
+ .then(r => r.json());
+
+ if (['completed', 'failed', 'partial'].includes(status.status)) {
+ return status;
}
+
+ await new Promise(resolve => setTimeout(resolve, 10000)); // 10s poll
}
}
-```
-### ๐ File Structure
-
-```
-data/agent_data/
-โโโ claude-3.7-sonnet/
-โ โโโ position/
-โ โ โโโ position.jsonl # ๐ Position records
-โ โโโ log/
-โ โโโ 2025-01-20/
-โ โโโ log.jsonl # ๐ Trading logs
-โโโ gpt-4o/
-โ โโโ ...
-โโโ qwen3-max/
- โโโ ...
-```
-
-## ๐ Third-Party Strategy Integration
-
-AI-Trader Bench adopts a modular design, supporting easy integration of third-party strategies and custom AI agents.
-
-### ๐ ๏ธ Integration Methods
-
-#### 1. Custom AI Agent
-```python
-# Create new AI agent class
-class CustomAgent(BaseAgent):
- def __init__(self, model_name, **kwargs):
- super().__init__(model_name, **kwargs)
- # Add custom logic
-```
-
-#### 2. Register New Agent
-```python
-# Register in main.py
-AGENT_REGISTRY = {
- "BaseAgent": {
- "module": "agent.base_agent.base_agent",
- "class": "BaseAgent"
- },
- "CustomAgent": { # New addition
- "module": "agent.custom.custom_agent",
- "class": "CustomAgent"
- },
+// Get results
+export async function getResults(api_url: string, job_id: string) {
+ return fetch(`${api_url}/results?job_id=${job_id}`)
+ .then(r => r.json());
}
```
-#### 3. Configuration File Settings
+### Python Client
+
+```python
+import requests
+import time
+
+# Trigger simulation
+response = requests.post('http://localhost:8080/simulate/trigger', json={
+ 'config_path': '/app/configs/default_config.json',
+ 'date_range': ['2025-01-16', '2025-01-17'],
+ 'models': ['gpt-4', 'claude-3.7-sonnet']
+})
+job_id = response.json()['job_id']
+
+# Poll for completion
+while True:
+ status = requests.get(f'http://localhost:8080/simulate/status/{job_id}').json()
+ if status['status'] in ['completed', 'failed', 'partial']:
+ break
+ time.sleep(10)
+
+# Get results
+results = requests.get(f'http://localhost:8080/results?job_id={job_id}').json()
+print(f"Completed with {results['count']} results")
+```
+
+---
+
+## ๐ Database Schema
+
+The SQLite database (`data/jobs.db`) contains:
+
+### Tables
+
+- **jobs** - Job metadata (id, status, created_at, etc.)
+- **job_details** - Per model-day execution details
+- **positions** - Trading position records with P&L
+- **holdings** - Portfolio holdings breakdown
+- **reasoning_logs** - AI decision reasoning history
+- **tool_usage** - MCP tool usage statistics
+
+### Querying Data
+
+```bash
+# Direct database access
+docker exec -it ai-trader sqlite3 /app/data/jobs.db
+
+# Example queries
+sqlite> SELECT * FROM jobs ORDER BY created_at DESC LIMIT 5;
+sqlite> SELECT model_signature, AVG(profit_loss) FROM positions GROUP BY model_signature;
+sqlite> SELECT * FROM reasoning_logs WHERE job_id='...';
+```
+
+---
+
+## ๐ ๏ธ Development
+
+### Running Tests
+
+```bash
+# Install dependencies
+pip install -r requirements.txt
+
+# Run test suite
+pytest tests/ -v --cov=api --cov-report=term-missing
+
+# Run specific test
+pytest tests/unit/test_job_manager.py -v
+```
+
+### Adding Custom Models
+
+Edit `configs/default_config.json`:
+
```json
{
- "agent_type": "CustomAgent",
"models": [
{
- "name": "your-custom-model",
- "basemodel": "your/model/path",
- "signature": "custom-signature",
- "enabled": true
+ "name": "Custom Model",
+ "basemodel": "provider/model-name",
+ "signature": "custom-model",
+ "enabled": true,
+ "openai_base_url": "https://api.custom.com/v1",
+ "openai_api_key": "custom_key_here"
}
]
}
```
-### ๐ง Extending Toolchain
+---
-#### Adding Custom Tools
-```python
-# Create new MCP tool
-@mcp.tools()
-class CustomTool:
- def __init__(self):
- self.name = "custom_tool"
-
- def execute(self, params):
- # Implement custom tool logic
- return result
-```
+## ๐ Documentation
-## ๐ Roadmap
+- [CHANGELOG.md](CHANGELOG.md) - Release notes and version history
+- [DOCKER_API.md](DOCKER_API.md) - Detailed API deployment guide
+- [TESTING_GUIDE.md](TESTING_GUIDE.md) - Comprehensive testing procedures
+- [CLAUDE.md](CLAUDE.md) - Development guide for contributors
-### ๐ Future Plans
-- [ ] **๐จ๐ณ A-Share Support** - Extend to Chinese stock market
-- [ ] **๐ Post-Market Statistics** - Automatic profit analysis
-- [ ] **๐ Strategy Marketplace** - Add third-party strategy sharing platform
-- [ ] **๐จ Cool Frontend Interface** - Modern web dashboard
-- [ ] **โฟ Cryptocurrency** - Support digital currency trading
-- [ ] **๐ More Strategies** - Technical analysis, quantitative strategies
-- [ ] **โฐ Advanced Replay** - Support minute-level time precision and real-time replay
-- [ ] **๐ Smart Filtering** - More precise future information detection and filtering
+---
-## ๐ค Contributing Guide
+## ๐ค Contributing
-We welcome contributions of all kinds! Especially AI trading strategies and agent implementations.
+Contributions welcome! Please read [CLAUDE.md](CLAUDE.md) for development guidelines.
-### ๐ง AI Strategy Contributions
-- **๐ฏ Trading Strategies**: Contribute your AI trading strategy implementations
-- **๐ค Custom Agents**: Implement new AI agent types
-- **๐ Analysis Tools**: Add new market analysis tools
-- **๐ Data Sources**: Integrate new data sources and APIs
-
-### ๐ Issue Reporting
-- Use GitHub Issues to report bugs
-- Provide detailed reproduction steps
-- Include system environment information
-
-### ๐ก Feature Suggestions
-- Propose new feature ideas in Issues
-- Describe use cases in detail
-- Discuss implementation approaches
-
-### ๐ง Code Contributions
-1. Fork the project
-2. Create a feature branch
-3. Implement your strategy or feature
-4. Add test cases
-5. Create a Pull Request
-
-### ๐ Documentation Improvements
-- Improve README documentation
-- Add code comments
-- Write usage tutorials
-- Contribute strategy documentation
-
-### ๐ Strategy Sharing
-- **๐ Technical Analysis Strategies**: AI strategies based on technical indicators
-- **๐ Quantitative Strategies**: Multi-factor models and quantitative analysis
-- **๐ Fundamental Strategies**: Analysis strategies based on financial data
-- **๐ Macro Strategies**: Strategies based on macroeconomic data
-
-## ๐ Support & Community
-
-- **๐ฌ Discussions**: [GitHub Discussions](https://github.com/Xe138/AI-Trader/discussions)
-- **๐ Issues**: [GitHub Issues](https://github.com/Xe138/AI-Trader/issues)
+---
## ๐ License
-This project is licensed under the [MIT License](LICENSE).
+MIT License - see [LICENSE](LICENSE) for details
-## ๐ Acknowledgments
+---
-Thanks to the following open source projects and services:
-- [LangChain](https://github.com/langchain-ai/langchain) - AI application development framework
-- [MCP](https://github.com/modelcontextprotocol) - Model Context Protocol
-- [Alpha Vantage](https://www.alphavantage.co/) - Financial data API
-- [Jina AI](https://jina.ai/) - Information search service
+## ๐ Links
-## Disclaimer
-
-The materials provided by the AI-Trader project are for research purposes only and do not constitute any investment advice. Investors should seek independent professional advice before making any investment decisions. Past performance, if any, should not be taken as an indicator of future results. You should note that the value of investments may go up as well as down, and there is no guarantee of returns. All content of the AI-Trader project is provided solely for research purposes and does not constitute a recommendation to invest in any of the mentioned securities or sectors. Investing involves risks. Please seek professional advice if needed.
+- **GitHub**: https://github.com/Xe138/AI-Trader
+- **Docker Hub**: `ghcr.io/xe138/ai-trader:latest`
+- **Issues**: https://github.com/Xe138/AI-Trader/issues
---
-**๐ If this project helps you, please give us a Star!**
-
-[](https://github.com/Xe138/AI-Trader)
-[](https://github.com/Xe138/AI-Trader)
-
-**๐ค Experience AI's full potential in financial markets through complete autonomous decision-making!**
-**๐ ๏ธ Pure tool-driven execution with zero human interventionโa genuine AI trading arena!** ๐
+**Built with FastAPI, SQLite, Docker, and the MCP Protocol**
-
----
-
-## โญ Star History
-
-*Community Growth Trajectory*
-
-
-
----
-
-
- โค๏ธ Thanks for visiting โจ AI-Trader!
-
-