"""The trading rules, in one place, shared by the live demo and the backtester. Same rules as pine/trend_strategy.pine: Entry: fast EMA above slow EMA, price above the fast EMA, volume above its average, trend strength (ADX) high enough, and a fresh trigger (not an old trend). Exit: fast EMA crosses back below slow EMA, or an ATR trailing stop is hit. """ from collections import deque from dataclasses import dataclass, field @dataclass(frozen=True) class Params: fast: int = 21 slow: int = 55 vol_len: int = 20 vol_mult: float = 1.2 atr_len: int = 14 atr_mult: float = 3.0 adx_len: int = 14 adx_min: float = 20 DEFAULT = Params() @dataclass class Bars: """A rolling window of candles plus the position state the rules need.""" closes: deque = field(default_factory=lambda: deque(maxlen=300)) highs: deque = field(default_factory=lambda: deque(maxlen=300)) lows: deque = field(default_factory=lambda: deque(maxlen=300)) volumes: deque = field(default_factory=lambda: deque(maxlen=300)) in_position: bool = False trail: float | None = None def add(self, high, low, close, volume): self.highs.append(high) self.lows.append(low) self.closes.append(close) self.volumes.append(volume) def ema(values, n): k, e = 2 / (n + 1), None out = [] for v in values: e = v if e is None else v * k + e * (1 - k) out.append(e) return out def atr(highs, lows, closes, n): trs = [highs[0] - lows[0]] + [max(h - l, abs(h - pc), abs(l - pc)) for h, l, pc in zip(highs[1:], lows[1:], closes[:-1])] return sum(trs[-n:]) / min(n, len(trs)) def adx(highs, lows, closes, n): """Wilder's ADX on the recent window. Good enough as a trend-strength filter.""" if len(closes) < 2 * n + 1: return 0.0 pdm, ndm, trs = [], [], [] for i in range(1, len(closes)): up, dn = highs[i] - highs[i - 1], lows[i - 1] - lows[i] pdm.append(up if up > dn and up > 0 else 0) ndm.append(dn if dn > up and dn > 0 else 0) trs.append(max(highs[i] - lows[i], abs(highs[i] - closes[i - 1]), abs(lows[i] - closes[i - 1]))) def wilder(xs): s = sum(xs[:n]); out = [s] for x in xs[n:]: s = s - s / n + x; out.append(s) return out tr_s, p_s, n_s = wilder(trs), wilder(pdm), wilder(ndm) dxs = [] for t, p, m in zip(tr_s, p_s, n_s): if t == 0: continue pdi, ndi = 100 * p / t, 100 * m / t dxs.append(100 * abs(pdi - ndi) / (pdi + ndi) if pdi + ndi else 0) return sum(dxs[-n:]) / min(n, len(dxs)) if dxs else 0.0 def signal(s, p: Params = DEFAULT) -> tuple[str, str] | None: """Look at the newest candle of `s` (anything with closes/highs/lows/volumes/in_position/trail). Returns ("buy" | "sell", reason) or None. Updates the trailing stop while a position is held. Written to do the minimum work per candle (it runs hundreds of thousands of times in a backtest): the two EMAs are computed in one pass keeping only their last two values, and the ATR only looks at its last `atr_len` candles. The numbers are identical to ema()/atr(). """ c, h, l, v = list(s.closes), list(s.highs), list(s.lows), list(s.volumes) if len(c) < p.slow + 2: return None kf, ks = 2 / (p.fast + 1), 2 / (p.slow + 1) ef = es = pf = ps = None for x in c: pf, ps = ef, es ef = x if ef is None else x * kf + ef * (1 - kf) es = x if es is None else x * ks + es * (1 - ks) trend_up = ef > es and c[-1] > ef prev_c = c[-2] trend_up_prev = pf > ps and prev_c > pf vol_ok = v[-1] > (sum(v[-p.vol_len:]) / p.vol_len) * p.vol_mult fresh = (trend_up and not trend_up_prev) or (prev_c <= pf and c[-1] > ef) n = len(c) if n > p.atr_len: a = sum(max(h[i] - l[i], abs(h[i] - c[i - 1]), abs(l[i] - c[i - 1])) for i in range(n - p.atr_len, n)) / p.atr_len else: a = atr(h, l, c, p.atr_len) if s.in_position: s.trail = max(s.trail or c[-1] - a * p.atr_mult, c[-1] - a * p.atr_mult) if pf >= ps and ef < es: return "sell", "trend_reversal" if c[-1] < s.trail: return "sell", "atr_stop" return None # ADX is the slowest indicator, so it is only worked out once everything else says "buy". if trend_up and vol_ok and fresh and adx(h[-80:], l[-80:], c[-80:], p.adx_len) >= p.adx_min: return "buy", "trend_up_volume" return None def diagnose(s, p: Params = DEFAULT) -> dict: """Why is there (not) a buy signal right now? The same five conditions signal() checks, each with its current value, for the dashboard's health panel. Does not change `s`.""" c, h, l, v = list(s.closes), list(s.highs), list(s.lows), list(s.volumes) need = p.slow + 2 if len(c) < need: return {"warming": True, "have": len(c), "need": need, "checks": [], "missing": [], "ready": False} kf, ks = 2 / (p.fast + 1), 2 / (p.slow + 1) ef = es = pf = ps = None for x in c: pf, ps = ef, es ef = x if ef is None else x * kf + ef * (1 - kf) es = x if es is None else x * ks + es * (1 - ks) avg_v = sum(v[-p.vol_len:]) / p.vol_len vol_ratio = v[-1] / avg_v if avg_v else 0.0 a = adx(h[-80:], l[-80:], c[-80:], p.adx_len) trend_up = ef > es and c[-1] > ef trend_up_prev = pf > ps and c[-2] > pf fresh = (trend_up and not trend_up_prev) or (c[-2] <= pf and c[-1] > ef) checks = [ {"key": "trend", "label": "Fast avg above slow", "ok": ef > es, "detail": f"{(ef / es - 1) * 100:+.2f}%"}, {"key": "price", "label": "Price above fast avg", "ok": c[-1] > ef, "detail": f"{(c[-1] / ef - 1) * 100:+.2f}%"}, {"key": "volume", "label": "Volume above average", "ok": vol_ratio > p.vol_mult, "detail": (f"newest candle {v[-1]:,.0f} vs average {avg_v:,.0f} = {vol_ratio:.1f}x (needs {p.vol_mult}x)" if avg_v else "the data source gives no volume for this market")}, {"key": "strength", "label": "Trend strong enough", "ok": a >= p.adx_min, "detail": f"ADX {a:.0f} (needs {p.adx_min:g})"}, {"key": "fresh", "label": "Fresh start of the trend", "ok": fresh, "detail": "just started" if fresh else "trend already running or not started"}, ] missing = [x["label"] for x in checks if not x["ok"]] return {"warming": False, "checks": checks, "missing": missing, "no_volume": not avg_v, "ready": not missing and not s.in_position, "trend_up": trend_up}