summaryrefslogtreecommitdiff
path: root/services/api/src/trading_api/routers/strategies.py
blob: 5db7320a40ebc5344de2fcc8cdc43975edc4890c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""Strategy endpoints."""

import logging
import os
import sys
from pathlib import Path

from fastapi import APIRouter, HTTPException

# Resolve strategies directory from env or relative paths
_STRATEGIES_DIR = Path(
    os.environ.get(
        "STRATEGIES_DIR",
        str(Path(__file__).resolve().parents[5] / "services" / "strategy-engine" / "strategies"),
    )
)
# Add parent so `from strategies.base import BaseStrategy` works
if str(_STRATEGIES_DIR.parent) not in sys.path:
    sys.path.insert(0, str(_STRATEGIES_DIR.parent))
# Add strategy-engine src for plugin_loader
_SE_SRC = Path(__file__).resolve().parents[5] / "services" / "strategy-engine" / "src"
if str(_SE_SRC) not in sys.path:
    sys.path.insert(0, str(_SE_SRC))

logger = logging.getLogger(__name__)

router = APIRouter()


@router.get("/")
async def list_strategies():
    """List available strategies."""
    try:
        from strategy_engine.plugin_loader import load_strategies

        strategies = load_strategies(_STRATEGIES_DIR)
        return [
            {
                "name": s.name,
                "warmup_period": s.warmup_period,
                "class": type(s).__name__,
            }
            for s in strategies
        ]
    except (ImportError, FileNotFoundError) as exc:
        logger.error("Strategy loading error: %s", exc)
        raise HTTPException(status_code=503, detail="Strategy engine unavailable")
    except Exception as exc:
        logger.error("Failed to list strategies: %s", exc, exc_info=True)
        raise HTTPException(status_code=500, detail="Failed to list strategies")