# ๐ AI-Trader-Server: REST API for AI Trading
[](https://python.org)
[](LICENSE)
[](https://docker.com)
[](https://fastapi.tiangolo.com)
**REST API service for autonomous AI trading competitions. Run multiple AI models in NASDAQ 100 trading simulations with zero human intervention.**
[๐ Quick Start](QUICK_START.md) โข [๐ API Reference](API_REFERENCE.md) โข [๐ Documentation](#documentation)
---
## ๐ What is AI-Trader-Server?
> **AI-Trader-Server enables multiple AI models to compete autonomously in NASDAQ 100 trading, making 100% independent decisions through a standardized tool-based architecture.**
### Key Features
- ๐ค **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 any HTTP client or workflow automation service
---
## ๐๏ธ Architecture
```
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 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 โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
```
---
## ๐ Quick Start
### Docker Deployment (5 minutes)
**1. Prerequisites**
- Docker and Docker Compose installed
- API keys: OpenAI, Alpha Vantage, Jina AI
**2. Setup**
```bash
git clone https://github.com/Xe138/AI-Trader-Server.git
cd AI-Trader-Server
# Configure environment
cp .env.example .env
# Edit .env and add your API keys
```
**3. Start Service**
```bash
docker-compose up -d
# Verify health
curl http://localhost:8080/health
```
**4. Run Simulation**
```bash
curl -X POST http://localhost:8080/simulate/trigger \
-H "Content-Type: application/json" \
-d '{
"start_date": "2025-01-16",
"models": ["gpt-4"]
}'
```
**5. Monitor Progress**
```bash
# Use job_id from trigger response
curl http://localhost:8080/simulate/status/{job_id}
```
**6. View Results**
```bash
curl "http://localhost:8080/results?job_id={job_id}"
```
๐ **Detailed guide:** [QUICK_START.md](QUICK_START.md)
---
## ๐ API Overview
### Endpoints
| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/simulate/trigger` | POST | Start simulation job |
| `/simulate/status/{job_id}` | GET | Check job progress |
| `/results` | GET | Query trading results |
| `/health` | GET | Service health check |
### Example: Trigger Simulation
**Request:**
```bash
curl -X POST http://localhost:8080/simulate/trigger \
-H "Content-Type: application/json" \
-d '{
"start_date": "2025-01-16",
"end_date": "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 with 2 trading dates"
}
```
**Parameters:**
- `start_date` (required) - Start date in YYYY-MM-DD format
- `end_date` (optional) - End date, defaults to `start_date` for single-day simulation
- `models` (optional) - Model signatures to run, defaults to all enabled models in config
๐ **Complete reference:** [API_REFERENCE.md](API_REFERENCE.md)
---
## ๐ฏ 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
- ๐ **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.**
---
## ๐ Integration Examples
### Python Client
```python
import requests
import time
class AITraderServerClient:
def __init__(self, base_url="http://localhost:8080"):
self.base_url = base_url
def trigger_simulation(self, start_date, end_date=None, models=None):
payload = {"start_date": start_date}
if end_date:
payload["end_date"] = end_date
if models:
payload["models"] = models
response = requests.post(
f"{self.base_url}/simulate/trigger",
json=payload
)
response.raise_for_status()
return response.json()
def wait_for_completion(self, job_id, poll_interval=10):
while True:
response = requests.get(
f"{self.base_url}/simulate/status/{job_id}"
)
status = response.json()
if status["status"] in ["completed", "partial", "failed"]:
return status
time.sleep(poll_interval)
# Usage
client = AITraderServerClient()
job = client.trigger_simulation("2025-01-16", models=["gpt-4"])
result = client.wait_for_completion(job["job_id"])
```
### TypeScript/JavaScript
```typescript
async function runSimulation() {
// Trigger simulation
const response = await fetch("http://localhost:8080/simulate/trigger", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
start_date: "2025-01-16",
models: ["gpt-4"]
})
});
const job = await response.json();
// Poll for completion
while (true) {
const statusResponse = await fetch(
`http://localhost:8080/simulate/status/${job.job_id}`
);
const status = await statusResponse.json();
if (["completed", "partial", "failed"].includes(status.status)) {
return status;
}
await new Promise(resolve => setTimeout(resolve, 10000));
}
}
```
### Scheduled Automation
Use any scheduler (cron, Airflow, etc.):
```bash
#!/bin/bash
# daily_simulation.sh
DATE=$(date -d "yesterday" +%Y-%m-%d)
curl -X POST http://localhost:8080/simulate/trigger \
-H "Content-Type: application/json" \
-d "{\"start_date\": \"$DATE\", \"models\": [\"gpt-4\"]}"
```
Add to crontab:
```
0 6 * * * /path/to/daily_simulation.sh
```
๐ **More examples:** [docs/user-guide/integration-examples.md](docs/user-guide/integration-examples.md)
---
## ๐ Documentation
### User Guides
- [Quick Start](QUICK_START.md) - Get running in 5 minutes
- [Configuration Guide](docs/user-guide/configuration.md) - Environment setup and model configuration
- [Using the API](docs/user-guide/using-the-api.md) - Common workflows and best practices
- [Integration Examples](docs/user-guide/integration-examples.md) - Python, TypeScript, automation
- [Troubleshooting](docs/user-guide/troubleshooting.md) - Common issues and solutions
### Developer Documentation
- [Development Setup](docs/developer/development-setup.md) - Local development without Docker
- [Testing Guide](docs/developer/testing.md) - Running tests and validation
- [Architecture](docs/developer/architecture.md) - System design and components
- [Database Schema](docs/developer/database-schema.md) - SQLite table reference
- [Adding Models](docs/developer/adding-models.md) - How to add custom AI models
### Deployment
- [Docker Deployment](docs/deployment/docker-deployment.md) - Production Docker setup
- [Production Checklist](docs/deployment/production-checklist.md) - Pre-deployment verification
- [Monitoring](docs/deployment/monitoring.md) - Health checks, logging, metrics
- [Scaling](docs/deployment/scaling.md) - Multiple instances and load balancing
### Reference
- [API Reference](API_REFERENCE.md) - Complete endpoint documentation
- [Environment Variables](docs/reference/environment-variables.md) - Configuration reference
- [MCP Tools](docs/reference/mcp-tools.md) - Trading tool documentation
- [Data Formats](docs/reference/data-formats.md) - File formats and schemas
---
## ๐ ๏ธ Configuration
### Environment Variables
```bash
# Required API Keys
OPENAI_API_KEY=sk-your-key-here
ALPHAADVANTAGE_API_KEY=your-key-here
JINA_API_KEY=your-key-here
# Optional Configuration
API_PORT=8080 # API server port
MAX_CONCURRENT_JOBS=1 # Max simultaneous simulations
MAX_SIMULATION_DAYS=30 # Max date range per job
AUTO_DOWNLOAD_PRICE_DATA=true # Auto-fetch missing data
```
### Model Configuration
Edit `configs/default_config.json`:
```json
{
"models": [
{
"name": "GPT-4",
"basemodel": "openai/gpt-4",
"signature": "gpt-4",
"enabled": true
},
{
"name": "Claude 3.7 Sonnet",
"basemodel": "anthropic/claude-3.7-sonnet",
"signature": "claude-3.7-sonnet",
"enabled": true,
"openai_base_url": "https://api.anthropic.com/v1",
"openai_api_key": "your-anthropic-key"
}
],
"agent_config": {
"max_steps": 30,
"initial_cash": 10000.0
}
}
```
๐ **Full guide:** [docs/user-guide/configuration.md](docs/user-guide/configuration.md)
---
## ๐ ๏ธ Development Mode
AI-Trader supports a development mode that mocks AI API calls for testing without costs.
### Quick Start
```bash
# Set environment variables
export DEPLOYMENT_MODE=DEV
export PRESERVE_DEV_DATA=false
# Run simulation (uses mock AI, isolated dev database)
python main.py configs/default_config.json
```
### How It Works
**DEPLOYMENT_MODE=DEV:**
- Mock AI responses (no API calls to OpenAI/Anthropic)
- Separate database: `data/trading_dev.db`
- Separate data directory: `data/dev_agent_data/`
- Dev database reset on startup (unless PRESERVE_DEV_DATA=true)
- Warnings logged if production API keys detected
**DEPLOYMENT_MODE=PROD** (default):
- Real AI API calls
- Production database: `data/trading.db`
- Production data directory: `data/agent_data/`
### Mock AI Behavior
The mock provider returns deterministic responses that rotate through stocks:
- Day 1: AAPL
- Day 2: MSFT
- Day 3: GOOGL
- Etc. (cycles through 10 stocks)
Each mock response includes:
- Price queries for selected stock
- Buy order for 5 shares
- Finish signal to end session
### Environment Variables
```bash
DEPLOYMENT_MODE=PROD # PROD or DEV (default: PROD)
PRESERVE_DEV_DATA=false # Keep dev data between runs (default: false)
```
### Use Cases
- **Orchestration testing:** Verify agent loop, position tracking, logging
- **CI/CD pipelines:** Run tests without API costs
- **Configuration validation:** Test date ranges, model configs
- **Development iteration:** Rapid testing of code changes
### Limitations
- Mock responses are static (not context-aware)
- No actual market analysis
- Fixed trading pattern
- For logic testing only, not trading strategy validation
---
## ๐ Database Schema
SQLite database at `data/jobs.db` contains:
- **jobs** - Job metadata and status
- **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
- **price_data** - Historical price data cache
- **price_coverage** - Data availability tracking
Query directly:
```bash
docker exec -it ai-trader-server sqlite3 /app/data/jobs.db
sqlite> SELECT * FROM jobs ORDER BY created_at DESC LIMIT 5;
```
๐ **Schema reference:** [docs/developer/database-schema.md](docs/developer/database-schema.md)
---
## ๐งช Testing & Validation
### Automated Validation
```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
```
### Unit Tests
```bash
# Install dependencies
pip install -r requirements.txt
# Run test suite
pytest tests/ -v --cov=api --cov-report=term-missing
```
๐ **Testing guide:** [docs/developer/testing.md](docs/developer/testing.md)
---
## ๐ Latest Updates
### v0.3.0 (Current)
**Major Architecture Upgrade - REST API Service**
- ๐ **REST API Server** - Complete FastAPI implementation
- `POST /simulate/trigger` - Start simulation jobs with date ranges
- `GET /simulate/status/{job_id}` - Monitor progress in real-time
- `GET /results` - Query results with filtering
- `GET /health` - Service health checks
- ๐พ **SQLite Database** - Complete persistence layer
- ๐ **On-Demand Price Data** - Automatic gap filling with priority-based downloads
- ๐ณ **Production-Ready Docker** - Single-command deployment
- ๐งช **Comprehensive Testing** - 175 tests with high coverage
- ๐ **Complete Documentation** - API guides and validation procedures
See [CHANGELOG.md](CHANGELOG.md) for full release notes and [ROADMAP.md](ROADMAP.md) for planned features.
---
## ๐ค Contributing
Contributions welcome! Please read [docs/developer/CONTRIBUTING.md](docs/developer/CONTRIBUTING.md) for development guidelines.
---
## ๐ Acknowledgments
This project is a fork of [HKUDS/AI-Trader](https://github.com/HKUDS/AI-Trader), re-architected as a REST API service for external orchestration and integration.
---
## ๐ License
MIT License - see [LICENSE](LICENSE) for details
---
## ๐ Links
- **GitHub**: https://github.com/Xe138/AI-Trader-Server
- **Docker Hub**: `ghcr.io/xe138/ai-trader-server:latest`
- **Issues**: https://github.com/Xe138/AI-Trader-Server/issues
- **API Docs**: http://localhost:8080/docs (when running)
---
**Built with FastAPI, SQLite, Docker, and the MCP Protocol**
[โฌ Back to top](#-ai-trader-server-rest-api-for-ai-trading)