"""Example strategies for the BlocConnect SDK.

    python example_strategy.py                 # backtest on bundled-style data
    # forward-test live (paper account) once you have a webhook token:
    #   from blocconnect import forward
    #   forward(Donchian, hook="https://mexc.blocconnect.com/hook/YOUR-TOKEN")
"""
from blocconnect import (Strategy, backtest, Hypothesis,
                         sma, ema, rsi, atr, highest, lowest)


class Donchian(Strategy):
    """Breakout: enter on a new 50-bar high, scale out at 1.5R/3R, trail at 2R."""
    symbol = "BTCUSDT"; interval = "5m"; warmup = 60; risk_pct = 1.0

    def on_bar(self, bars):
        if len(bars) < 55:
            return
        price = bars[-1].c
        if self.position is None and price > highest(bars[:-1], 50):
            self.long(sl_price=lowest(bars[-20:], 20),
                      tp_rules=[{"r": 1.5, "pct": 50}, {"r": 3.0, "pct": 50}],
                      be_at_r=1.0, trail_r=2.0, tag="breakout")
        elif self.position == "long" and price < lowest(bars[:-1], 20):
            self.close()


class MeanRevert(Strategy):
    """Fade RSI extremes back to the mean."""
    symbol = "ETHUSDT"; interval = "15m"; warmup = 60; risk_pct = 0.75

    def on_bar(self, bars):
        c = [b.c for b in bars]
        r = rsi(c, 14)
        if r is None:
            return
        if self.position is None and r < 25:
            self.long(sl_price=bars[-1].c - 2 * (atr(bars, 14) or 0),
                      tp_rules=[{"r": 1.0, "pct": 100}], be_at_r=0.7)
        elif self.position == "long" and r > 55:
            self.close()


if __name__ == "__main__":
    import math, random
    random.seed(1)
    from blocconnect import Bar
    rows = []; t = 0; px = 30000.0
    for i in range(6000):
        px *= (1 + 0.0004 * math.sin(i / 300) + random.gauss(0, 0.0017))
        rows.append(Bar({"t": t, "o": px, "h": px * 1.0011, "l": px * 0.9989,
                         "c": px * (1 + random.gauss(0, 0.0004)), "v": 1})); t += 300
    hyp = Hypothesis(min_sharpe=0.8, max_drawdown=-0.25, min_profit_factor=1.2,
                     min_deflated_sharpe=0.6, min_trades=20, trials_considered=15)
    res = backtest(Donchian, bars=rows, venue="bybit", trials=15, hypothesis=hyp)
    res.print_summary()
    res.report("donchian_report.html")
