Initial commit: Gold Trading Simulator with AI-powered analysis
This commit is contained in:
@@ -0,0 +1,300 @@
|
||||
# Setup Notes & Architecture
|
||||
|
||||
## Environment Variables Reference
|
||||
|
||||
### Backend (.env)
|
||||
```bash
|
||||
# Required
|
||||
ALPHA_VANTAGE_API_KEY=your_key # Get from alphavantage.co
|
||||
OPENROUTER_API_KEY=your_key # Get from openrouter.ai
|
||||
|
||||
# Database
|
||||
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/gold_trading_db
|
||||
|
||||
# Optional - defaults work fine
|
||||
APP_ENV=development
|
||||
DEBUG=True
|
||||
CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
|
||||
HOST=0.0.0.0
|
||||
PORT=8000
|
||||
```
|
||||
|
||||
### Frontend (.env)
|
||||
```bash
|
||||
# Required - points to backend API
|
||||
VITE_API_URL=http://localhost:8000/api
|
||||
|
||||
# Optional - only if you want direct frontend calls (not recommended)
|
||||
VITE_ALPHA_VANTAGE_API_KEY=your_key
|
||||
```
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Browser (Port 3000) │
|
||||
│ ┌────────────┐ ┌─────────────┐ ┌──────────────────────┐ │
|
||||
│ │ Chart │ │ Trade Panel │ │ Portfolio Tracker │ │
|
||||
│ │ Component │ │ Component │ │ Component │ │
|
||||
│ └────────────┘ └─────────────┘ └──────────────────────┘ │
|
||||
│ │ │ │ │
|
||||
│ └────────────────┴────────────────────┘ │
|
||||
│ │ │
|
||||
│ API Service │
|
||||
│ │ │
|
||||
└──────────────────────────┼───────────────────────────────────┘
|
||||
│ HTTP/REST
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ FastAPI Backend (Port 8000) │
|
||||
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────┐ │
|
||||
│ │ /api/market│ │ /api/trading │ │ /api/ai │ │
|
||||
│ │ endpoints │ │ endpoints │ │ endpoints │ │
|
||||
│ └─────────────┘ └──────────────┘ └──────────────────┘ │
|
||||
│ │ │ │ │
|
||||
│ ▼ ▼ ▼ │
|
||||
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────┐ │
|
||||
│ │ Alpha │ │ In-memory │ │ OpenRouter │ │
|
||||
│ │ Vantage │ │ Trading │ │ Service │ │
|
||||
│ │ Service │ │ State (MVP) │ │ (Claude 3.5) │ │
|
||||
│ └─────────────┘ └──────────────┘ └──────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
│ │
|
||||
▼ ▼
|
||||
┌──────────────────┐ ┌────────────────────────┐
|
||||
│ Alpha Vantage │ │ OpenRouter API │
|
||||
│ API │ │ (Claude 3.5 Sonnet) │
|
||||
│ (Market Data) │ │ (AI Analysis) │
|
||||
└──────────────────┘ └────────────────────────┘
|
||||
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────────┐
|
||||
│ PostgreSQL Database │
|
||||
│ (Port 5432 - Docker) │
|
||||
│ ┌──────────────────────────────┐│
|
||||
│ │ Tables (for Phase 2): ││
|
||||
│ │ - simulations ││
|
||||
│ │ - trades ││
|
||||
│ │ - positions ││
|
||||
│ │ - ai_analysis_logs ││
|
||||
│ └──────────────────────────────┘│
|
||||
└──────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Data Flow
|
||||
|
||||
### 1. Loading Historical Data
|
||||
```
|
||||
Browser → GET /api/market/gold/history
|
||||
↓
|
||||
FastAPI → Alpha Vantage Service
|
||||
↓
|
||||
Alpha Vantage API (XAU/USD daily data)
|
||||
↓
|
||||
Transform to PriceData[]
|
||||
↓
|
||||
Calculate SMA(50) in frontend
|
||||
↓
|
||||
Render with Lightweight Charts
|
||||
```
|
||||
|
||||
### 2. Executing Trade
|
||||
```
|
||||
User clicks "Buy" → POST to local state (MVP)
|
||||
↓
|
||||
Update portfolio state
|
||||
↓
|
||||
Recalculate P&L
|
||||
↓
|
||||
Update UI components
|
||||
```
|
||||
|
||||
### 3. AI Analysis
|
||||
```
|
||||
User clicks "AI Analysis" → Gather context:
|
||||
- Last 50 price points
|
||||
- Current indicators
|
||||
- Current price
|
||||
↓
|
||||
POST /api/ai/analyze
|
||||
↓
|
||||
OpenRouter Service → Claude 3.5 Sonnet
|
||||
↓
|
||||
Parse JSON response
|
||||
↓
|
||||
Return AIAnalysisResponse
|
||||
↓
|
||||
Display in AIAnalysisPanel
|
||||
```
|
||||
|
||||
## Technology Choices Explained
|
||||
|
||||
### Why Lightweight Charts?
|
||||
- **Optimized for trading:** Built by TradingView specifically for financial data
|
||||
- **Performance:** Can handle 10,000+ candles smoothly
|
||||
- **Size:** Only 35KB gzipped
|
||||
- **Free:** Apache 2.0 license, no restrictions
|
||||
|
||||
### Why Alpha Vantage?
|
||||
- **Free tier:** 500 calls/day is plenty for development
|
||||
- **Forex data:** Includes XAU/USD (gold) out of the box
|
||||
- **Reliability:** Industry-standard data provider
|
||||
- **No credit card:** Instant API key
|
||||
|
||||
### Why OpenRouter + Claude?
|
||||
- **Best reasoning:** Claude 3.5 Sonnet > GPT-4o for complex analysis
|
||||
- **Pay-per-use:** No monthly subscription
|
||||
- **Unified API:** Access 400+ models through one endpoint
|
||||
- **OpenAI-compatible:** Easy migration if needed
|
||||
|
||||
### Why FastAPI?
|
||||
- **Speed:** 3x faster than Flask for async operations
|
||||
- **Type safety:** Pydantic schemas ensure data validation
|
||||
- **Auto docs:** Swagger UI at /docs
|
||||
- **Modern:** Async/await throughout
|
||||
|
||||
### Why PostgreSQL?
|
||||
- **Reliability:** Production-grade ACID compliance
|
||||
- **Time-series:** Works well with TimescaleDB extension (future)
|
||||
- **JSON support:** Flexible for evolving schemas
|
||||
- **Free:** Open source forever
|
||||
|
||||
## MVP vs. Future Phases
|
||||
|
||||
### MVP (Current) - In-Memory State
|
||||
```python
|
||||
# backend/app/api/trading.py
|
||||
simulation_state = {
|
||||
"cash": 100000.0,
|
||||
"position": None,
|
||||
"trades": []
|
||||
}
|
||||
```
|
||||
|
||||
**Pros:**
|
||||
- Fast to implement
|
||||
- No database setup issues
|
||||
- Perfect for testing
|
||||
|
||||
**Cons:**
|
||||
- Resets on server restart
|
||||
- Single user only
|
||||
- No historical analysis
|
||||
|
||||
### Phase 2 - Database Persistence
|
||||
```python
|
||||
# Future implementation
|
||||
@router.post("/execute")
|
||||
async def execute_trade(trade: TradeCreate, db: Session = Depends(get_db)):
|
||||
# Save to PostgreSQL
|
||||
db_trade = Trade(**trade.dict())
|
||||
db.add(db_trade)
|
||||
db.commit()
|
||||
return db_trade
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- Persistent across restarts
|
||||
- Multi-user support
|
||||
- Historical backtesting
|
||||
- Advanced analytics
|
||||
|
||||
## API Rate Limits
|
||||
|
||||
### Alpha Vantage Free Tier
|
||||
- **5 calls/minute**
|
||||
- **500 calls/day**
|
||||
- **Strategy:** Cache aggressively, use `compact` output for development
|
||||
|
||||
### OpenRouter (Pay-per-use)
|
||||
- **No rate limit** (reasonable use)
|
||||
- **Cost per analysis:** ~$0.01-0.05
|
||||
- **Strategy:** User-initiated only, no auto-refresh
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Current (Development)
|
||||
- API keys in `.env` files
|
||||
- CORS restricted to localhost
|
||||
- No authentication
|
||||
|
||||
### Production Requirements
|
||||
- **Environment variables** from secrets manager (AWS Secrets Manager, etc.)
|
||||
- **HTTPS** for all connections
|
||||
- **JWT authentication** for users
|
||||
- **Rate limiting** per IP/user
|
||||
- **API key rotation** policy
|
||||
- **Input validation** on all endpoints
|
||||
|
||||
## Performance Metrics
|
||||
|
||||
### Expected Response Times
|
||||
- Market data endpoint: 200-500ms (Alpha Vantage)
|
||||
- Trading execute: <10ms (in-memory)
|
||||
- AI analysis: 3-10 seconds (Claude API)
|
||||
|
||||
### Optimization Opportunities
|
||||
1. **Redis caching** for market data (reduce API calls)
|
||||
2. **WebSocket** for real-time updates (future)
|
||||
3. **CDN** for frontend static assets
|
||||
4. **Database indexes** on frequently queried fields
|
||||
5. **Connection pooling** for PostgreSQL
|
||||
|
||||
## Monitoring & Debugging
|
||||
|
||||
### Backend Logs
|
||||
```bash
|
||||
# Watch backend logs
|
||||
cd backend
|
||||
source venv/bin/activate
|
||||
python -m app.main
|
||||
|
||||
# Look for:
|
||||
# - API call patterns
|
||||
# - Error traces
|
||||
# - Response times
|
||||
```
|
||||
|
||||
### Frontend Console
|
||||
```javascript
|
||||
// Browser console (F12)
|
||||
// Network tab shows API calls
|
||||
// Console shows React errors
|
||||
```
|
||||
|
||||
### Database Queries
|
||||
```bash
|
||||
# Connect to PostgreSQL
|
||||
docker exec -it gold_trading_db psql -U postgres -d gold_trading_db
|
||||
|
||||
# Useful commands:
|
||||
\dt # List tables
|
||||
\d simulations # Describe table
|
||||
SELECT COUNT(*) FROM trades;
|
||||
```
|
||||
|
||||
## Common Development Workflows
|
||||
|
||||
### Adding a New Indicator
|
||||
1. Create calculation function in `frontend/src/utils/indicators.ts`
|
||||
2. Add to chart component state
|
||||
3. Create line series in chart
|
||||
4. Add toggle in UI
|
||||
|
||||
### Adding a New API Endpoint
|
||||
1. Define schema in `backend/app/schemas/schemas.py`
|
||||
2. Create route in appropriate `backend/app/api/*.py`
|
||||
3. Add service method if needed
|
||||
4. Update frontend API service
|
||||
5. Create React hook for data fetching
|
||||
|
||||
### Database Schema Changes
|
||||
1. Update model in `backend/app/models/models.py`
|
||||
2. Create Alembic migration (future)
|
||||
3. Run migration
|
||||
4. Update schemas and routes
|
||||
|
||||
---
|
||||
|
||||
This completes the comprehensive setup and architecture documentation!
|
||||
Reference in New Issue
Block a user