Add strategy base
Browse files- qrypto/strategies/base.py +57 -0
qrypto/strategies/base.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass, field
|
| 4 |
+
from typing import Any, Literal, Optional
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
|
| 8 |
+
Action = Literal["buy", "sell", "hold"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@dataclass
|
| 12 |
+
class Signal:
|
| 13 |
+
action: Action
|
| 14 |
+
reason: str = ""
|
| 15 |
+
fraction: float = 1.0 # fraction of the risk-allowed size to use (0..1)
|
| 16 |
+
stop: Optional[float] = None # strategy-suggested stop (risk manager may tighten)
|
| 17 |
+
meta: dict[str, Any] = field(default_factory=dict)
|
| 18 |
+
|
| 19 |
+
@staticmethod
|
| 20 |
+
def hold(reason: str = "") -> "Signal":
|
| 21 |
+
return Signal("hold", reason)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Strategy:
|
| 25 |
+
"""Base class. Subclasses implement warmup() and evaluate()."""
|
| 26 |
+
|
| 27 |
+
name: str = "base"
|
| 28 |
+
description: str = ""
|
| 29 |
+
default_params: dict[str, Any] = {}
|
| 30 |
+
min_tier: str = "free"
|
| 31 |
+
|
| 32 |
+
def __init__(self, **params: Any):
|
| 33 |
+
self.params = {**self.default_params, **params}
|
| 34 |
+
|
| 35 |
+
def warmup(self) -> int:
|
| 36 |
+
"""Number of candles required before evaluate() is meaningful."""
|
| 37 |
+
return 50
|
| 38 |
+
|
| 39 |
+
def evaluate(self, candles: pd.DataFrame, in_position: bool, entry_price: Optional[float]) -> Signal:
|
| 40 |
+
raise NotImplementedError
|
| 41 |
+
|
| 42 |
+
def describe(self) -> dict[str, Any]:
|
| 43 |
+
return {"name": self.name, "description": self.description, "params": self.params, "min_tier": self.min_tier}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
STRATEGY_REGISTRY: dict[str, type[Strategy]] = {}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def register(cls: type[Strategy]) -> type[Strategy]:
|
| 50 |
+
STRATEGY_REGISTRY[cls.name] = cls
|
| 51 |
+
return cls
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def make_strategy(name: str, **params: Any) -> Strategy:
|
| 55 |
+
if name not in STRATEGY_REGISTRY:
|
| 56 |
+
raise KeyError(f"unknown strategy {name}; available: {list(STRATEGY_REGISTRY)}")
|
| 57 |
+
return STRATEGY_REGISTRY[name](**params)
|