#!/usr/bin/env python3
"""Misst, ob offene D1-Gaps als Magnete einen handelbaren Edge liefern:
Haben Wellen-Signale, die ZUM nächsten offenen Gap zeigen, besseren Edge als die,
die davon WEG zeigen? (Gap-Status wird je Bar korrekt 'as-of' rekonstruiert —
nur Gaps, die zu dem Zeitpunkt offen waren.)
"""
import sys, bisect, datetime as dt
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)

OFF = 3 * 3600
def _d(ts): return dt.datetime.fromtimestamp(ts - OFF, tz=dt.timezone.utc).date()


class _TU:
    def snapshot(self): return {"intervals": {}}
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 _rep(name,r):
    if not r: print(f"  {name:<30} -"); return
    n=len(r); w=sum(1 for x in r if x>0)
    print(f"  {name:<30} n={n:>5} Treffer={100*w/n:>3.0f}% Ø-Edge={sum(r)/n:+.4f} Summe={sum(r):+.1f}")

def main():
    n=int(sys.argv[1]) if len(sys.argv)>1 else 50000
    K=10
    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+K+5)
    m30=mt5.copy_rates_from_pos(sym,mt5.TIMEFRAME_M30,0,n//6+500)
    d1 =mt5.copy_rates_from_pos(sym,mt5.TIMEFRAME_D1,0,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 m30sign(ts):
        idx=bisect.bisect_right(mT,ts)-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)

    # --- D1-Gaps + Fülldatum bestimmen (alle Jahre in den D1-Daten) ---
    dr=[{"date":_d(int(b["time"])),"h":float(b["high"]),"l":float(b["low"])} for b in d1]
    gaps=[]
    for i in range(1,len(dr)):
        p,cur=dr[i-1],dr[i]
        if cur["l"]>p["h"]:   gaps.append({"date":cur["date"],"dir":"up","lo":p["h"],"hi":cur["l"],"fill":p["h"],"i":i})
        elif cur["h"]<p["l"]: gaps.append({"date":cur["date"],"dir":"down","lo":cur["h"],"hi":p["l"],"fill":p["l"],"i":i})
    for g in gaps:
        fd=None
        for j in range(g["i"]+1,len(dr)):
            if (g["dir"]=="up" and dr[j]["l"]<=g["lo"]) or (g["dir"]=="down" and dr[j]["h"]>=g["hi"]):
                fd=dr[j]["date"]; break
        g["fill_date"]=fd
    print(f"D1-Gaps gesamt: {len(gaps)}")

    def open_gaps_asof(d):
        return [g for g in gaps if g["date"]<=d and (g["fill_date"] is None or g["fill_date"]>d)]

    w=WaveRecommender(_TU(), mt5.TIMEFRAME_M5)
    toward=[]; away=[]; nogap=[]
    toward_r=[]; away_r=[]    # nur Gaps "in Reichweite" (≤2% vom Kurs)
    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
        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=m30sign(T[i]),angle=a5)
        if rec["signal"]=="WARTEN": continue
        d=1 if rec["signal"]=="LONG" else -1
        fwd=(C[i+K]-C[i])*d
        px=C[i]; og=open_gaps_asof(_d(T[i]))
        if not og:
            nogap.append(fwd); continue
        nearest=min(og, key=lambda g: abs(g["fill"]-px))
        side=1 if nearest["fill"]>px else -1      # +1 Gap oben, -1 Gap unten
        (toward if d==side else away).append(fwd)
        if abs(nearest["fill"]-px)/px <= 0.02:    # in Reichweite
            (toward_r if d==side else away_r).append(fwd)

    print("="*72)
    print(f"  Gap-Magnet-Test — {sym} M5  Vorlauf={K}  (Signal zum nächsten offenen Gap?)")
    print("="*72)
    _rep("Signal ZUM Gap (toward)", toward)
    _rep("Signal WEG vom Gap (away)", away)
    _rep("kein offenes Gap", nogap)
    print("\n  Nur Gaps in Reichweite (≤2% vom Kurs):")
    _rep("  toward (≤2%)", toward_r)
    _rep("  away   (≤2%)", away_r)

if __name__=="__main__":
    main()
