#!/usr/bin/env python3
"""ATR-Breakout-Einstiegsfilter (= die Zwei-Konten-Idee auf EINEM Konto):
Signal kommt → Trade erst eröffnen, wenn der Kurs k×ATR in Signalrichtung gelaufen
ist (Bestätigung, 'X dynamisch'). Läuft er vorher k×ATR DAGEGEN → Trade verfällt.
Vergleich gegen Sofort-Einstieg. Exit-Modell = SL 2,0×ATR + Trailing 1,5 (live),
pessimistisch. R = Profit/ATR.

Frage: Hebt das verzögerte Einsteigen den Edge (Qualität) genug, um den k×ATR-
Mehrpreis + die verpassten Trades zu rechtfertigen?
"""
import sys, bisect
import MetaTrader5 as mt5
from core.analysis import calc_trend_angle
from core.wave_rec import (WaveRecommender, _atr, _ema_last, _EMA_FAST, _EMA_SLOW,
                           _N_BARS, _HTF_DEADBAND, _ANGLE_LR)

_MAXH=288; _ATRMIN=0.12; _CONFIRM_W=12   # max. Bars, um den Breakout zu bestätigen
def _ema_series(v,p):
    k=2.0/(p+1); o=[]; e=v[0]
    for i,x in enumerate(v): e=x if i==0 else x*k+e*(1-k); o.append(e)
    return o
def _atr_series(H,L,C,p=14):
    t=[0.0]
    for i in range(1,len(C)): t.append(max(H[i]-L[i],abs(H[i]-C[i-1]),abs(L[i]-C[i-1])))
    return [(sum(t[max(1,i-p+1):i+1])/max(1,len(t[max(1,i-p+1):i+1]))) if i else None for i in range(len(C))]
def sim(entry,d,atr,H,L,C,j0, sl_atr=2.0, trail=1.5, trail_on=0.3, be_on=1.0):
    eff=entry-d*sl_atr*atr; hw=entry
    end=min(j0+_MAXH,len(C)-1); exit_px=C[end]
    for j in range(j0,end+1):
        hi,lo=H[j],L[j]
        if (lo<=eff) if d>0 else (hi>=eff): exit_px=eff; break
        hw=max(hw,hi) if d>0 else min(hw,lo)
        prof=(C[j]-entry)*d
        if prof>=trail_on*atr:
            cand=hw-d*trail*atr
            if prof>=be_on*atr: cand=max(cand,entry) if d>0 else min(cand,entry)
            eff=max(eff,cand) if d>0 else min(eff,cand)
    return (exit_px-entry)*d/atr
def rep(name,Rs,nsig):
    if not Rs: print(f"  {name:<26} -"); return
    n=len(Rs); w=sum(1 for x in Rs if x>0)
    print(f"  {name:<26} Trades={n:>5} ({100*n/nsig:>3.0f}%) Treffer={100*w/n:>3.0f}% "
          f"ØR={sum(Rs)/n:+.3f} ΣR={sum(Rs):+.0f}")

def main():
    n=int(sys.argv[1]) if len(sys.argv)>1 else 40000
    mt5.initialize()
    sym=None
    for c in ("SpotCrude","USOIL","WTI","XTIUSD"):
        if mt5.symbol_info(c): sym=c; break
    bars=mt5.copy_rates_from_pos(sym,mt5.TIMEFRAME_M5,0,n+_N_BARS+_MAXH+5)
    m30=mt5.copy_rates_from_pos(sym,mt5.TIMEFRAME_M30,0,n//6+500)
    mt5.shutdown()
    T=[int(b["time"]) for b in bars]; H=[float(b["high"]) for b in bars]
    L=[float(b["low"]) for b in bars]; C=[float(b["close"]) for b in bars]
    mT=[int(b["time"]) for b in m30]; mc=[float(b["close"]) for b in m30]
    mh=[float(b["high"]) for b in m30]; ml=[float(b["low"]) for b in m30]
    mEf=_ema_series(mc,_EMA_FAST); mEs=_ema_series(mc,_EMA_SLOW); mA=_atr_series(mh,ml,mc)
    def m30s(ts):
        idx=bisect.bisect_right(mT,ts)-1
        if idx<_EMA_SLOW or mA[idx] is None or mA[idx]<=0: return 0
        dd=mEf[idx]-mEs[idx]
        return 0 if abs(dd)<_HTF_DEADBAND*mA[idx] else (1 if dd>0 else -1)
    class _TU:
        def snapshot(self): return {"intervals": {}}
    w=WaveRecommender(_TU(), mt5.TIMEFRAME_M5)
    sigs=[]
    for i in range(_N_BARS, len(C)-_MAXH-1):
        wc=C[i-_N_BARS:i]; wh=H[i-_N_BARS:i]; wl=L[i-_N_BARS:i]
        atr=_atr(wh,wl,wc)
        if not atr or atr<=0: continue
        ef=_ema_last(wc,_EMA_FAST); es=_ema_last(wc,_EMA_SLOW)
        a5=calc_trend_angle(C[i-_ANGLE_LR-2:i],_ANGLE_LR)
        rec,_=w._build(ef,es,C[i-1],atr,"M5",0,htf_trend=m30s(T[i]),angle=a5)
        if rec["signal"]=="WARTEN": continue
        d=1 if rec["signal"]=="LONG" else -1
        sigs.append((i,d,max(atr,_ATRMIN)))
    nsig=len(sigs)

    print("="*82)
    print(f"  ATR-Breakout-Einstieg — {sym} M5  Signale={nsig}  Bestätigungsfenster={_CONFIRM_W} Bars")
    print("="*82)
    base=[sim(C[i],d,atr,H,L,C,i+1) for (i,d,atr) in sigs]
    rep("Sofort-Einstieg (Basis)", base, nsig)
    print()
    for k in (0.3, 0.5, 1.0, 1.5):
        Rs=[]; skipped=0
        for (i,d,atr) in sigs:
            entry0=C[i]; level=entry0+d*k*atr; invalid=entry0-d*k*atr
            je=None
            for j in range(i+1, min(i+1+_CONFIRM_W, len(C)-_MAXH-1)):
                if d>0:
                    if L[j]<=invalid: break          # erst dagegen → verfällt
                    if H[j]>=level: je=j; break       # Breakout bestätigt
                else:
                    if H[j]>=invalid: break
                    if L[j]<=level: je=j; break
            if je is None: skipped+=1; continue
            Rs.append(sim(level,d,atr,H,L,C,je+1))
        rep(f"Breakout k={k}×ATR", Rs, nsig)
    print(f"\n  ØR = Edge je Trade (in ATR) · ΣR = Gesamtertrag · % = Anteil der Signale, die getradet wurden")

if __name__=="__main__":
    main()
