Skip to content

Strategy Service

TradAI Strategy Service - Strategy configuration, MLflow model management, hyperparameter optimization, and A/B testing.

Service Info

Property Value
Version 0.1.0
Type full
Port 8003
Author TradAI Team

Quick Start

# Install dependencies
cd services/strategy-service && uv sync

# Start with auto-reload (development)
strategy-service serve --reload

# Start production mode
strategy-service serve --port 8003

# Check health
strategy-service health

API Documentation

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

API Endpoints

Health Check

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

Strategy Configuration (4 endpoints)

Method Path Description
GET /api/v1/strategies List available strategy configs
GET /api/v1/strategies/{config_name} Get specific strategy config
POST /api/v1/strategies/validate Validate strategy configuration
POST /api/v1/strategies/merge Merge base config with overrides

MLflow Integration (2 endpoints)

Method Path Description
GET /api/v1/mlflow/models/{model_name} Get model version info
GET /api/v1/mlflow/experiments/{experiment_id} Get experiment results

Model Versioning (3 endpoints)

Method Path Description
GET /api/v1/models/{model_name}/versions List all model versions
GET /api/v1/models/{model_name}/rollback-candidates List archived versions
POST /api/v1/models/{model_name}/rollback Rollback to previous version

Strategy Promotion (3 endpoints)

Method Path Description
POST /api/v1/strategies/{name}/stage Stage version for testing
POST /api/v1/strategies/{name}/promote Promote to Production
POST /api/v1/strategies/{name}/register Register after backtest

Hyperparameter Optimization (4 endpoints)

Method Path Description
POST /api/v1/hyperopt Start Optuna optimization
GET /api/v1/hyperopt List all hyperopt jobs
GET /api/v1/hyperopt/{job_id} Get job status
GET /api/v1/hyperopt/{job_id}/result Get optimization results

Available Samplers:

Sampler Description
TPESampler Tree-Parzen Estimator (default) - good for most cases
RandomSampler Random search - baseline comparison
CmaEsSampler CMA-ES - good for continuous parameters

Example Request:

{
  "strategy_name": "PascalStrategy",
  "n_trials": 100,
  "sampler": "TPESampler",
  "param_space": {
    "roi_min": {"type": "float", "low": 0.01, "high": 0.1},
    "stoploss": {"type": "float", "low": -0.15, "high": -0.03}
  }
}

Champion/Challenger A/B Testing (6 endpoints)

Method Path Description
POST /api/v1/models/{model_name}/challenges Create A/B test
GET /api/v1/models/{model_name}/challenges/active Get active challenge
GET /api/v1/challenges/{challenge_id} Get challenge by ID
POST /api/v1/challenges/{challenge_id}/trades Add trade result
GET /api/v1/challenges/{challenge_id}/evaluate Evaluate and recommend
POST /api/v1/challenges/{challenge_id}/cancel Cancel challenge

Challenge Evaluation Criteria: - Minimum 100 trades per variant (configurable via min_trades) - Statistical significance test (t-test) for profit comparison - Win rate comparison weighted by trade count - Recommendation: PROMOTE_CHALLENGER, KEEP_CHAMPION, or INCONCLUSIVE

Strategy Registration Thresholds

Default performance thresholds for POST /api/v1/strategies/{name}/register:

Metric Default Threshold Description
min_sharpe_ratio 1.0 Minimum Sharpe ratio
min_profit_factor 1.5 Minimum profit factor
max_drawdown_pct 20.0% Maximum drawdown
min_total_trades 50 Minimum total trades
min_win_rate 40% Minimum win rate

Custom thresholds can be passed in the request body:

{
  "run_id": "mlflow-run-123",
  "strategy_name": "PascalStrategy",
  "thresholds": {
    "min_sharpe_ratio": 1.5,
    "min_profit_factor": 2.0,
    "max_drawdown_pct": 15.0
  }
}

Authentication

The API supports optional JWT authentication via AWS Cognito.

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

Configuration: - STRATEGY_SERVICE_COGNITO_USER_POOL_ID: Cognito User Pool ID - STRATEGY_SERVICE_COGNITO_CLIENT_ID: Cognito App Client ID - STRATEGY_SERVICE_COGNITO_REGION: AWS region (default: us-east-1)

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"}

CLI Commands

# Health check
strategy_service health

# Show current configuration
strategy_service config

# List available strategy configs from S3
strategy_service list-strategies

# Get a specific strategy config
strategy_service get-strategy momentum-v1
strategy_service get-strategy momentum-v1 --json

# Validate a local config file
strategy_service validate config.yaml

# Get model version from MLflow
strategy_service get-model PascalStrategy
strategy_service get-model PascalStrategy --version 3

# Get experiment results from MLflow
strategy_service get-experiment exp-123

Configuration

Environment variables (prefix: STRATEGY_SERVICE_):

Variable Description Default
STRATEGY_SERVICE_HOST Server host 0.0.0.0
STRATEGY_SERVICE_PORT Server port 8003
STRATEGY_SERVICE_DEBUG Debug mode false
STRATEGY_SERVICE_LOG_LEVEL Log level INFO
STRATEGY_SERVICE_S3_CONFIG_BUCKET S3 bucket for configs (required)
STRATEGY_SERVICE_RESULTS_BUCKET S3 bucket for results (required)
STRATEGY_SERVICE_MLFLOW_TRACKING_URI MLflow server URL http://localhost:5000
STRATEGY_SERVICE_MLFLOW_USERNAME MLflow auth username (optional)
STRATEGY_SERVICE_MLFLOW_PASSWORD MLflow auth password (optional)
STRATEGY_SERVICE_MLFLOW_VERIFY_SSL Verify MLflow SSL certs true

Docker

# Build
docker build -t strategy_service:0.1.0 .

# Run
docker run -p 8003:8003 strategy_service:0.1.0

Testing

# Run all tests
uv run pytest

# Run with coverage
uv run pytest --cov=strategy_service

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

Architecture

This service follows the TradAI 3-layer architecture:

src/tradai/strategy_service/
├── api/              # Presentation layer (FastAPI routes, schemas)
│   ├── routes.py     # API endpoints
│   ├── schemas.py    # Request/response models
│   └── dependencies.py # Dependency injection
├── core/             # Business logic layer
│   ├── service.py    # Main service class
│   ├── settings.py   # Configuration
│   ├── entities.py   # Domain entities
│   └── backtest_handler.py # BacktestHandler (entrypoint mode handler)
├── infrastructure/   # External adapters (add as needed)
├── cli.py            # Typer CLI
└── main.py           # FastAPI app factory

BacktestHandler

The BacktestHandler implements the ModeHandler protocol and is registered with StrategyEntrypoint for BACKTEST mode:

from tradai.common.entrypoint.base import StrategyEntrypoint
from tradai.common.entrypoint.settings import TradingMode

@StrategyEntrypoint.register_handler(TradingMode.BACKTEST)
class BacktestHandler:
    """Handles backtest execution via FreqtradeBacktester."""

    def __init__(self, entrypoint: StrategyEntrypoint) -> None:
        self._ep = entrypoint

    def run(self) -> int:
        # Execute backtest and return exit code
        ...

The handler is automatically registered on import via the decorator. The entrypoint's __init__.py imports BacktestHandler to trigger registration.

License

Proprietary - TradAI