#!/usr/bin/env python3
"""Misst, ob ein Lockern der Überdehnungs-Grenze (_STRETCH_MAX) mehr Signale
mit weiterhin positivem Edge bringt. Live-Konfig M5 + M30-Filter.

Trick: _STRETCH_MAX hoch setzen (alle Trend-Signale zulassen), dann den Edge je
Abstand-zur-EMA-Band (near = stretch in Trade-Richtung) bucketen. So sieht man,
welche Trades ein höheres Limit ZUSÄTZLICH zuließe und ob sie tragen.
"""
from __future__ import annotations
import sys
import MetaTrader5 as mt5
import core.wave_rec as wr
from core.wave_rec import (WaveRecommender, _atr, _ema_last,
                           _EMA_FAST, _EMA_SLOW, _N_BARS, _HTF_DEADBAND)


class _NeutralTU:
    def snapshot(self): return {"intervals": {}}

def _ema_series(vals,p):
    k=2.0/(p+1); out=[]; e=vals[0]
    for i,v in enumerate(vals):
        e=v if i==0 else v*k+e*(1-k); out.append(e)
    return out
def _atr_series(H,L,C,p=14):
    trs=[0.0]
    for i in range(1,len(C)):
        trs.append(max(H[i]-L[i],abs(H[i]-C[i-1]),abs(L[i]-C[i-1])))
    return [(sum(trs[max(1,i-p+1):i+1])/max(1,len(trs[max(1,i-p+1):i+1]))) if i else None for i in range(len(C))]

def _rep(name, rets):
    if not rets: print(f"  {name:<18} -"); return
    n=len(rets); win=sum(1 for x in rets if x>0)
    print(f"  {name:<18} n={n:>4}  Treffer={100*win/n:>3.0f}%  Oe-Edge={sum(rets)/n:+.4f}")

def main():
    n=int(sys.argv[1]) if len(sys.argv)>1 else 8000
    K=10
    if not mt5.initialize(): print("init",mt5.last_error()); sys.exit(1)
    sym=None
    for c in ("SpotCrude","USOIL","WTI","XTIUSD"):
        if mt5.symbol_info(c): sym=c; break
    sym=sym or "SpotCrude"
    bars=mt5.copy_rates_from_pos(sym,mt5.TIMEFRAME_M5,0,n+_N_BARS+K+5)
    m30b=mt5.copy_rates_from_pos(sym,mt5.TIMEFRAME_M30,0,n//6+400)
    mt5.shutdown()
    if bars is None or m30b is None: print("Bars fehlen"); sys.exit(1)
    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 m30b]; mc=[float(b["close"]) for b in m30b]
    mh=[float(b["high"]) for b in m30b]; ml=[float(b["low"]) for b in m30b]
    mEf=_ema_series(mc,_EMA_FAST); mEs=_ema_series(mc,_EMA_SLOW); mA=_atr_series(mh,ml,mc)
    def m30s(ts):
        lo,hi,idx=0,len(mT)-1,-1
        while lo<=hi:
            md=(lo+hi)//2
            if mT[md]<=ts: idx=md; lo=md+1
            else: hi=md-1
        if idx<_EMA_SLOW or mA[idx] is None or mA[idx]<=0: return 0
        d=mEf[idx]-mEs[idx]
        return 0 if abs(d)<_HTF_DEADBAND*mA[idx] else (1 if d>0 else -1)

    wr._STRETCH_MAX = 999.0          # alle Trend-Signale zulassen
    w=WaveRecommender(_NeutralTU(),mt5.TIMEFRAME_M5)
    bands={"<2,5 (jetzt)":[], "2,5-3,0":[], "3,0-3,5":[], ">=3,5":[]}
    total_bars=0
    for i in range(_N_BARS,len(C)-K):
        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
        total_bars+=1
        ef=_ema_last(wc,_EMA_FAST); es=_ema_last(wc,_EMA_SLOW)
        rec,_=w._build(ef,es,C[i-1],atr,"M5",5,htf_trend=m30s(T[i]))
        if rec["signal"]=="WARTEN": continue
        d=1 if rec["signal"]=="LONG" else -1
        r=(C[i+K]-C[i])*d
        near=(C[i-1]-es)/atr*d
        if near<2.5: bands["<2,5 (jetzt)"].append(r)
        elif near<3.0: bands["2,5-3,0"].append(r)
        elif near<3.5: bands["3,0-3,5"].append(r)
        else: bands[">=3,5"].append(r)

    print("="*56); print(f"  Überdehnungs-Test — {sym} M5+M30  Vorlauf={K}"); print("="*56)
    print("Edge je Abstand-Band (near = ATR-Abstand in Trade-Richtung):")
    for k in ("<2,5 (jetzt)","2,5-3,0","3,0-3,5",">=3,5"): _rep(k,bands[k])
    def cum(maxv):
        rr=[]
        for k,lim in (("<2,5 (jetzt)",2.5),("2,5-3,0",3.0),("3,0-3,5",3.5),(">=3,5",99)):
            if lim<=maxv+1e-9: rr+=bands[k]
        return rr
    print("\nKumuliert je _STRETCH_MAX (Signal-Anteil aller Bars + Gesamt-Edge):")
    for label,mx in (("2,5 (jetzt)",2.5),("3,0",3.0),("3,5",3.5),("aus",99)):
        rr=cum(mx); share=100*len(rr)/total_bars
        win=sum(1 for x in rr if x>0)
        print(f"  MAX={label:<10} Signale={len(rr):>4} ({share:>4.1f}% der Bars)  "
              f"Treffer={100*win/len(rr):>3.0f}%  Oe-Edge={sum(rr)/len(rr):+.4f}")

if __name__=="__main__":
    main()
