Skip to content

Backend Service

TradAI Backend API - Central gateway for backtest orchestration, strategy management, and model operations.

Service Info

Property Value
Version 0.1.0
Type full
Port 8000
Author TradAI Team

Quick Start

# Install dependencies
cd services/backend && uv sync

# Start with auto-reload (development)
backend serve --reload

# Start production mode
backend serve --port 8000

# Check health
backend health

API Documentation

Interactive documentation available at: - Swagger UI: http://localhost:8000/docs - ReDoc: http://localhost:8000/redoc - OpenAPI JSON: http://localhost:8000/openapi.json

API Endpoints

Health Check

Method Path Description
GET /api/v1/health Service health with dependency checks

Backtest Management (6 endpoints)

Method Path Description
POST /api/v1/backtests Submit new backtest job
GET /api/v1/backtests List backtest jobs (paginated)
GET /api/v1/backtests/{job_id} Get backtest status
POST /api/v1/backtests/{job_id}/cancel Cancel backtest job
GET /api/v1/backtests/{job_id}/equity Get equity curve data
GET /api/v1/backtests/{job_id}/report-data Get complete report data

Strategy Proxy (2 endpoints)

Method Path Description
GET /api/v1/strategies List available strategies
GET /api/v1/strategies/{config_name} Get strategy configuration

Strategy Promotion (4 endpoints)

Method Path Description
POST /api/v1/strategies/{name}/stage Stage strategy for testing
POST /api/v1/strategies/{name}/promote Promote to Production
GET /api/v1/models/{model_name}/versions List model versions
POST /api/v1/models/{model_name}/rollback Rollback to previous version

Strategy Operations (4 endpoints)

Method Path Description
POST /api/v1/strategies/{strategy_id}/run Launch strategy on ECS
GET /api/v1/strategies/{strategy_id}/instances List running instances
POST /api/v1/strategies/{strategy_id}/instances/{id}/stop Stop instance
GET /api/v1/strategies/{strategy_id}/instances/{id}/logs Get CloudWatch logs

Strategy Catalog (4 endpoints)

Method Path Description
GET /api/v1/catalog/strategies List catalog strategies
GET /api/v1/catalog/strategies/{name} Get strategy details
GET /api/v1/catalog/strategies/{name}/compare Compare versions
GET /api/v1/catalog/leaderboard Strategy leaderboard

Data Proxy (2 endpoints)

Method Path Description
GET /api/v1/data/symbols Get available symbols
GET /api/v1/data/freshness Check data freshness

WebSocket (1 endpoint)

Type Path Description
WS /ws/backtests/{job_id} Stream real-time backtest progress

WebSocket Message Format:

{
  "progress": 45.5,
  "current_date": "2024-01-15",
  "trades_executed": 23,
  "status": "running"
}

JavaScript Example:

const ws = new WebSocket('ws://localhost:8000/ws/backtests/bt-abc123');
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log(`Progress: ${data.progress}%`);
};

Rate Limiting

Backtest submission (POST /api/v1/backtests) is rate limited to 10 requests per minute per IP to prevent system overload.

Endpoint Limit Window
POST /api/v1/backtests 10 requests 1 minute

Rate limit exceeded returns HTTP 429:

{"detail": "Rate limit exceeded: 10 per 1 minute"}

Authentication

The API supports optional JWT authentication via AWS Cognito.

# Include token in Authorization header
curl -H "Authorization: Bearer <token>" http://localhost:8000/api/v1/backtests

Configuration: - BACKEND_COGNITO_USER_POOL_ID: Cognito User Pool ID (enables auth if set) - BACKEND_COGNITO_CLIENT_ID: Cognito App Client ID - BACKEND_COGNITO_REGION: AWS region (default: us-east-1)

In development, authentication is optional. In production, it's enforced.

CORS Configuration

Configure allowed origins via environment variable:

# Single origin
export BACKEND_CORS_ORIGINS="http://localhost:3000"

# Multiple origins (comma-separated)
export BACKEND_CORS_ORIGINS="http://localhost:3000,https://app.tradai.io"

Response Headers

All responses include: - X-Correlation-ID: Unique request ID for tracing/debugging

Error Responses

Status Description Response Body
400 Validation error {"detail": "error message"}
401 Authentication required {"detail": "Not authenticated"}
404 Resource not found {"detail": "Resource not found"}
503 Service unavailable {"detail": "Service unavailable"}

Configuration

Environment variables (prefix: BACKEND_):

Variable Description Default
BACKEND_HOST Server host 0.0.0.0
BACKEND_PORT Server port 8000
BACKEND_DEBUG Debug mode false
BACKEND_LOG_LEVEL Log level INFO
BACKEND_CORS_ORIGINS CORS origins []
BACKEND_STRATEGY_SERVICE_URL Strategy service URL http://localhost:8003
BACKEND_DATA_COLLECTION_URL Data service URL http://localhost:8002
BACKEND_MLFLOW_TRACKING_URI MLflow server URL http://localhost:5000
BACKEND_EXECUTOR_MODE Executor mode local
BACKEND_ECS_CLUSTER ECS cluster name (optional)

Docker

# Build
docker build -t tradai-backend:0.1.0 .

# Run
docker run -p 8000:8000 \
  -e BACKEND_CORS_ORIGINS="http://localhost:3000" \
  tradai-backend:0.1.0

Testing

# Run all tests
uv run pytest

# Run with coverage
uv run pytest --cov=tradai.backend

# Run specific test
uv run pytest tests/unit/test_service.py -v

Architecture

src/tradai/backend/
├── api/                    # Presentation layer
│   ├── routes.py          # API endpoints
│   ├── schemas.py         # Request/response models
│   └── dependencies.py    # Dependency injection
├── core/                   # Business logic
│   ├── service.py         # Main service
│   ├── entities.py        # Domain entities
│   ├── settings.py        # Configuration
│   ├── orchestration.py   # Backtest orchestration
│   ├── catalog_service.py # Strategy catalog
│   └── strategy_operations.py  # ECS operations
├── infrastructure/         # External adapters
│   ├── dynamodb_repository.py
│   └── sqs_executor.py
├── cli.py                  # Typer CLI
└── main.py                 # FastAPI app factory

TypeScript Types

Generate TypeScript types for frontend integration:

# From project root
npm run generate-types

Types are generated from OpenAPI spec at /openapi.json.

Next.js Integration

import createClient from 'openapi-fetch';
import type { paths } from './types/backend';

const client = createClient<paths>({
  baseUrl: process.env.NEXT_PUBLIC_API_URL
});

// Submit backtest
const { data, error } = await client.POST('/api/v1/backtests', {
  body: {
    config: { strategy: 'TrendFollowing', pairs: ['BTC/USDT:USDT'] },
    experiment_name: 'test-run',
    priority: 0
  }
});

// Get status
const { data: status } = await client.GET('/api/v1/backtests/{job_id}', {
  params: { path: { job_id: data.job_id } }
});

License

Proprietary - TradAI