Files
2026-10-21 20:23:51 -04:00

77 lines
2.5 KiB
Python
Executable File

"""Strategy base class and plugin registry."""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime
from typing import Any, ClassVar
import pandas as pd
_REGISTRY: dict[str, type[Strategy]] = {}
def register(name: str):
"""Class decorator that makes a strategy available as `type: <name>` in the config."""
def decorator(cls: type[Strategy]) -> type[Strategy]:
if name in _REGISTRY:
raise ValueError(f"Strategy type '{name}' is already registered")
cls.type_name = name
_REGISTRY[name] = cls
return cls
return decorator
def get_strategy_class(name: str) -> type[Strategy]:
try:
return _REGISTRY[name]
except KeyError:
raise ValueError(
f"Unknown strategy type '{name}'. Available: {sorted(_REGISTRY)}"
) from None
def available_strategies() -> list[str]:
return sorted(_REGISTRY)
@dataclass(frozen=True)
class Context:
"""Read-only snapshot handed to a strategy each time a new candle closes."""
now: datetime
candles: dict[str, pd.DataFrame] # pair -> closed OHLCV candles, oldest first
prices: dict[str, float] # pair -> last traded price
weights: dict[str, float] # pair -> current fraction of this strategy's equity
cash: float
equity: float
class Strategy(ABC):
"""Base class for all trading strategies.
Subclass it, decorate with ``@register("my_name")`` and implement ``decide``.
``decide`` returns the *target* fraction of this strategy's equity to hold in
each pair (0.0 = all cash, 1.0 = fully invested). Pairs left out of the result
keep their current allocation, so returning ``{}`` means "do nothing".
The engine turns targets into buy/sell orders, so strategies never deal with
order sizing, fees, or minimum order sizes.
"""
type_name: ClassVar[str] = ""
default_params: ClassVar[dict[str, Any]] = {}
def __init__(self, pairs: list[str], interval: int, params: dict[str, Any] | None = None):
unknown = set(params or {}) - set(self.default_params)
if unknown:
raise ValueError(f"{type(self).__name__}: unknown params {sorted(unknown)}")
self.pairs = pairs
self.interval = interval
self.params = {**self.default_params, **(params or {})}
@abstractmethod
def decide(self, ctx: Context) -> dict[str, float]: ...