10 KiB
10 KiB
Setup Notes & Architecture
Environment Variables Reference
Backend (.env)
# 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)
# 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
# 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
# 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
compactoutput 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
.envfiles - 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
- Redis caching for market data (reduce API calls)
- WebSocket for real-time updates (future)
- CDN for frontend static assets
- Database indexes on frequently queried fields
- Connection pooling for PostgreSQL
Monitoring & Debugging
Backend Logs
# Watch backend logs
cd backend
source venv/bin/activate
python -m app.main
# Look for:
# - API call patterns
# - Error traces
# - Response times
Frontend Console
// Browser console (F12)
// Network tab shows API calls
// Console shows React errors
Database Queries
# 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
- Create calculation function in
frontend/src/utils/indicators.ts - Add to chart component state
- Create line series in chart
- Add toggle in UI
Adding a New API Endpoint
- Define schema in
backend/app/schemas/schemas.py - Create route in appropriate
backend/app/api/*.py - Add service method if needed
- Update frontend API service
- Create React hook for data fetching
Database Schema Changes
- Update model in
backend/app/models/models.py - Create Alembic migration (future)
- Run migration
- Update schemas and routes
This completes the comprehensive setup and architecture documentation!