"""GBPUSD Bollinger-band breakout: one combined long/short source-clock baseline.
Source public C# https://www.quantconnect.com/forum/discussion/1597/london-breakout-strategy/
FIXED EST UTC-5 BAR-START clock, not DST New York or a London08:00 rule.
Dukascopy BID H1 signals, next M5 quote executions; EUR CFD research accounting.
Run: python backtest.py --data-dir data --out results
"""
from __future__ import annotations
import argparse,dataclasses,hashlib,json,math,os,tempfile
from pathlib import Path
from datetime import timezone,timedelta
os.environ.setdefault('MPLCONFIGDIR',os.path.join(tempfile.gettempdir(),'edgequant-matplotlib'))
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
START=pd.Timestamp('2016-01-01',tz='UTC');END=pd.Timestamp('2026-01-01',tz='UTC');WARMUP=pd.Timestamp('2015-01-01',tz='UTC')
SOURCE='https://www.quantconnect.com/forum/discussion/1597/london-breakout-strategy/'
CLOCK_SOURCE='https://www.quantconnect.com/forum/discussion/5365/daylight-savings-timezone-confusion/p1'
SOURCE_CLOCK=timezone(timedelta(hours=-5))
@dataclasses.dataclass(frozen=True)
class Config:
    initial_eur:float=10000.
    bb_period:int=10
    bb_width:float=2.2
    take_profit_price:float=.00080
    stop_loss_price:float=.00180
    max_held_events:int=5
    slippage_usd_per_gbp:float=.00001
    commission_usd_per_lot_side:float=3.50
    contract_gbp:float=100000.
    lot_step:float=.01
    min_lot:float=.01
    funding_annual:float=.05
    seconds_per_year:float=365*86400
    bar_seconds:int=300
    max_entry_delay_seconds:int=900
    max_entry_fx_age_seconds:int=900

def usd_eur(value,bid,ask):return value/(ask if value>=0 else bid)

def load_data(directory:Path):
    frames={};prov={}
    for symbol in ['GBPUSD','EURUSD']:
        path=directory/f'{symbol}_5m.csv.gz';mp=directory/f'{symbol}_5m.manifest.json'
        manifest=json.loads(mp.read_text());digest=hashlib.sha256(path.read_bytes()).hexdigest()
        if manifest.get('file_sha256')!=digest:raise ValueError(f'Price manifest SHA256 mismatch: {symbol}')
        df=pd.read_csv(path,parse_dates=['timestamp']);df.timestamp=pd.to_datetime(df.timestamp,utc=True)
        df=df[(df.timestamp>=WARMUP)&(df.timestamp<END)].reset_index(drop=True)
        cols=[f'{side}_{field}' for side in ['bid','ask'] for field in ['open','high','low','close']]
        v=df[cols].to_numpy(float)
        if not np.isfinite(v).all() or (v<=0).any():raise ValueError('Invalid positive quote data')
        if not df.timestamp.is_monotonic_increasing or df.timestamp.duplicated().any():raise ValueError('Duplicate/out-of-order quotes')
        if (df.ask_open<df.bid_open).any() or (df.ask_close<df.bid_close).any():raise ValueError('Crossed opening/closing quotes')
        for side in ['bid','ask']:
            if ((df[side+'_low']>df[[side+'_open',side+'_close']].min(axis=1))|(df[side+'_high']<df[[side+'_open',side+'_close']].max(axis=1))).any():raise ValueError('Invalid OHLC')
        years=df.groupby(df.timestamp.dt.year).size().to_dict()
        if set(years)!=set(range(2015,2026)) or min(years.values())<1000:raise ValueError('Require 2015 warmup and ten evaluation years')
        frames[symbol]=df;prov[symbol]={'file':path.name,'sha256':digest,'manifest':mp.name,'source':manifest.get('source'),'attribution':manifest.get('attribution'),
            'rows_with_warmup':len(df),'candles_by_year':years,'first_utc':str(df.timestamp.iloc[0]),'last_utc':str(df.timestamp.iloc[-1]),'imputed_bars':0}
    f=frames['EURUSD'][['timestamp','bid_open','ask_open','bid_close','ask_close']].rename(columns={c:'fx_'+c for c in ['bid_open','ask_open','bid_close','ask_close']})
    f['fx_timestamp']=f.timestamp
    joined=pd.merge_asof(frames['GBPUSD'],f,on='timestamp',direction='backward')
    if joined.fx_timestamp.isna().any():raise ValueError('No prior FX quote for GBPUSD timestamp')
    age=(joined.timestamp-joined.fx_timestamp).dt.total_seconds();joined['fx_quote_age_seconds']=age
    if age.max()>7*86400:raise ValueError('FX quote over a week old')
    prior=age>0
    for side in ['bid','ask']:joined.loc[prior,'fx_'+side+'_open']=joined.loc[prior,'fx_'+side+'_close']
    prov['alignment']={'fx_exact_timestamp_fraction':float((age==0).mean()),'fx_stale_max_seconds':float(age.max()),'fx_stale_rows':int(prior.sum()),
       'rule':'Backward-only quote merge. Exact FX open at matched timestamp; otherwise previously observed FX close. Entry age<=15min, exits/valuations retain and flag stale FX.'}
    return joined,prov

def bollinger(closes:pd.Series,cfg:Config=Config()):
    mean=closes.rolling(cfg.bb_period,min_periods=cfg.bb_period).mean()
    # Population standard deviation, recomputed on each same window.
    std=closes.rolling(cfg.bb_period,min_periods=cfg.bb_period).std(ddof=0)
    return mean,std,mean+cfg.bb_width*std,mean-cfg.bb_width*std

def build_signals(all_quotes:pd.DataFrame,cfg:Config=Config()):
    q=all_quotes.set_index('timestamp').sort_index()
    h=q[['bid_close']].resample('1h',label='right',closed='left').last().dropna().rename(columns={'bid_close':'signal_bid'})
    h['bb_mean'],h['bb_population_std'],h['upper_band'],h['lower_band']=bollinger(h.signal_bid,cfg)
    h.index.name='signal_utc';h=h.reset_index();h['bar_start_utc']=h.signal_utc-pd.Timedelta(hours=1)
    local=h.bar_start_utc.dt.tz_convert(SOURCE_CLOCK)
    h['bar_start_source_clock']=local.astype(str);h['source_hour']=local.dt.hour;h['source_day']=local.dt.strftime('%Y-%m-%d')
    h['reset_observed']=h.source_hour==1;h['entry_window']=h.source_hour.between(5,10)
    h=h[(h.signal_utc>=START)&(h.signal_utc<END)].reset_index(drop=True)
    if h.upper_band.isna().any():raise ValueError('BB10 not ready in evaluation despite 2015 warmup')
    return h

def metrics(daily:pd.DataFrame,trades:pd.DataFrame,initial:float=10000.):
    eq=daily.equity_eur;ret=eq.pct_change();ret.iloc[0]=eq.iloc[0]/initial-1
    peak=np.maximum.accumulate(np.r_[initial,eq.to_numpy()])[1:];dd=eq.to_numpy()-peak;ddpct=eq.to_numpy()/peak-1
    net=float(eq.iloc[-1]-initial); years=len(eq)/365.25
    pnl=trades.net_pnl_eur.to_numpy() if len(trades) else np.array([])
    wins=float(pnl[pnl>0].sum());losses=float(-pnl[pnl<0].sum())
    return {'initial_eur':initial,'final_equity_eur':float(eq.iloc[-1]),'net_profit_eur':net,'total_return_pct':net/initial*100,
        'cagr_pct':100*((eq.iloc[-1]/initial)**(1/years)-1) if eq.iloc[-1]>0 else None,
        'max_drawdown_eur':float(-dd.min()),'max_drawdown_pct':float(-ddpct.min()*100),
        'profit_factor':wins/losses if losses>0 else None,'sharpe':float(ret.mean()/ret.std(ddof=1)*np.sqrt(365)) if ret.std(ddof=1)>0 else None,
        'recovery_factor':net/float(-dd.min()) if dd.min()<0 else None,'closed_trades':len(pnl),
        'win_rate_pct':float((pnl>0).mean()*100) if len(pnl) else None,
        'best_daily_return_pct':float(ret.max()*100),'worst_daily_return_pct':float(ret.min()*100)}

def safe_json(obj):
    if isinstance(obj,dict):return {k:safe_json(v) for k,v in obj.items()}
    if isinstance(obj,list):return [safe_json(x) for x in obj]
    if isinstance(obj,np.generic):return obj.item()
    if isinstance(obj,float) and not np.isfinite(obj):return None
    return obj

def charts(curves,results,out):
    plt.rcParams.update({'figure.facecolor':'#101b17','axes.facecolor':'#101b17','axes.edgecolor':'#648171','text.color':'#e7eee8','axes.labelcolor':'#e7eee8','xtick.color':'#bac9bc','ytick.color':'#bac9bc','grid.color':'#34483d','font.size':10,'savefig.facecolor':'#101b17'})
    colors={'strategy':'#d4ed8d','buy_hold':'#d9a678'}
    fig,ax=plt.subplots(2,1,figsize=(12,8),sharex=True)
    for key,d in curves.items():
        ax[0].plot(d.index,d.equity_eur,label=results[key]['label'],color=colors[key],lw=1.5)
        peak=np.maximum.accumulate(np.r_[10000,d.equity_eur.to_numpy()])[1:]
        ax[1].plot(d.index,100*(d.equity_eur/peak-1),color=colors[key],lw=1.3)
    ax[0].set(ylabel='Equity (EUR)',title='GBPUSD Bollinger breakout | EUR 10,000 | 2016–2025')
    ax[1].set(ylabel='Drawdown (%)',xlabel='UTC date');ax[0].legend(facecolor='#101b17',labelcolor='#e7eee8')
    for a in ax:a.grid(alpha=.35)
    fig.text(.5,.01,'Dukascopy via EV Trading Labs | Bid/ask + slippage + commissions + assumed 5% annual funding | Historical model',ha='center',fontsize=8,color='#bac9bc')
    fig.tight_layout(rect=(0,.03,1,1));fig.savefig(out/'equity_drawdown.png',dpi=160);plt.close(fig)
    fig,axs=plt.subplots(2,3,figsize=(12,7))
    specs=[('net_profit_eur','Net profit (EUR)'),('profit_factor','Trade profit factor'),('sharpe','Annualized daily Sharpe'),('recovery_factor','Recovery factor'),('cagr_pct','CAGR (%)'),('max_drawdown_pct','Daily max drawdown (%)')]
    for ax,(field,title) in zip(axs.flat,specs):
        for i,(key,v) in enumerate(results.items()):
            val=v[field]
            if val is None:ax.text(i,0,'undefined',rotation=90,ha='center',va='bottom',fontsize=8,color='#bac9bc')
            else:
                ax.bar(i,val,color=colors[key]);display=f'{val:,.4f}' if field=='profit_factor' or field=='recovery_factor' and abs(val)<.01 else f'{val:,.2f}'
                ax.annotate(display,(i,val),ha='center',va='bottom' if val>=0 else 'top',fontsize=8)
        ax.set_xticks(range(2),['Strategy','B&H']);ax.set_title(title);ax.axhline(0,color='#648171',lw=.7);ax.grid(axis='y',alpha=.25)
    fig.suptitle('After modeled costs | one combined long/short baseline and buy-and-hold benchmark')
    fig.text(.5,.01,'Trade PF for a single buy-and-hold trade is not a meaningful cross-strategy risk comparison. Sharpe risk-free rate = 0.',ha='center',fontsize=8,color='#bac9bc')
    fig.tight_layout(rect=(0,.04,1,.96));fig.savefig(out/'performance_metrics.png',dpi=160);plt.close(fig)
    fig,ax=plt.subplots(figsize=(12,5))
    for k,d in curves.items():ax.plot(d.index,d.equity_eur-10000,label=results[k]['label'],color=colors[k],lw=1.5)
    ax.axhline(0,color='#648171',lw=.7);ax.set(ylabel='Cumulative net P&L (EUR)',xlabel='UTC date',title='GBPUSD CFD modeled profit on an EUR 10,000 account')
    ax.legend(facecolor='#101b17',labelcolor='#e7eee8');ax.grid(alpha=.25);fig.tight_layout();fig.savefig(out/'profit.png',dpi=160);plt.close(fig)
    fig,ax=plt.subplots(figsize=(12,5));xs=np.arange(10);w=.25
    for i,(k,v) in enumerate(results.items()):ax.bar(xs+(i-.5)*w,list(v['annual_returns_pct'].values()),w,label=v['label'],color=colors[k])
    ax.set_xticks(xs,range(2016,2026));ax.set_ylabel('Return (%)');ax.set_title('Calendar-year returns after modeled costs');ax.legend(facecolor='#101b17',labelcolor='#e7eee8');ax.grid(axis='y',alpha=.25);fig.tight_layout();fig.savefig(out/'annual_returns.png',dpi=160);plt.close(fig)




def strictly_above(a,b):
    # Numerical guard is seven orders smaller than a 0.00001 quote point.
    return a-b>1e-12*max(1.,abs(a),abs(b))
def strictly_below(a,b):return strictly_above(b,a)
def exit_reason(direction,bid,reference,hold_count,cfg:Config=Config()):
    if (strictly_above(bid,reference+cfg.take_profit_price) if direction==1 else strictly_below(bid,reference-cfg.take_profit_price)):return 'profit_threshold'
    if (strictly_below(bid,reference-cfg.stop_loss_price) if direction==1 else strictly_above(bid,reference+cfg.stop_loss_price)):return 'loss_threshold'
    if hold_count>cfg.max_held_events:return 'timed_exit'
    return None

def simulate(quotes:pd.DataFrame,signals:pd.DataFrame,case:str,cfg:Config=Config()):
    if case not in ['strategy','buy_hold']:raise ValueError('Only one combined baseline plus buyhold benchmark')
    q=quotes[(quotes.timestamp>=START)&(quotes.timestamp<END)].reset_index(drop=True)
    ts=q.timestamp.astype('int64').to_numpy()/1e9
    cols=['bid_open','ask_open','bid_close','ask_close','fx_bid_open','fx_ask_open','fx_bid_close','fx_ask_close']
    a={n:q[n].to_numpy(float) for n in cols}
    ages=q.fx_quote_age_seconds.to_numpy(float) if 'fx_quote_age_seconds' in q else np.zeros(len(q))
    fxstamps=q.fx_timestamp.astype('int64').to_numpy()/1e9 if 'fx_timestamp' in q else ts
    events={};trace=[]
    diag={'observed_hourly_events':len(signals),'observed_resets':0,'entry_window_events':0,'breakout_events_in_window':0,
        'entry_attempts_when_allowed':0,'skipped_entry_delay':0,'skipped_entry_fx_stale':0,'skipped_minimum_lot':0,
        'delayed_entry_count':0,'max_entry_delay_seconds':0.,'delayed_exit_count':0,'max_exit_delay_seconds':0.,
        'forced_window_end_exits':0,'unfilled_final_hourly_events':0,'exit_reason_counts':{},'filled_longs':0,'filled_shorts':0,
        'has_traded_policy':'Qualifying allowed breakout consumes reset-cycle allowance even if entry execution is skipped/rejected. Only an observed bar-start source-clock01 resets it.'}
    if case=='strategy':
        for ev in signals.itertuples(index=False):
            i=int(np.searchsorted(ts,ev.signal_utc.timestamp(),side='left'))
            if i>=len(ts):diag['unfilled_final_hourly_events']+=1;continue
            events.setdefault(i,[]).append(ev)
    cash=cfg.initial_eur;units=0.;direction=0;entry=reference=entry_t=entry_signal_t=entry_cash=0.;entry_bb={};entry_fx={}
    hold_count=0;has_traded=False;cycle='initial_before_first_observed_reset';entry_cycle=''
    notional=lastfund=tradefees=tradefund=totalfees=totalfund=heldseconds=turnover=slip_est=spread_est=0.
    heldage=0.;heldstale=heldold=0;entries_year={};trades=[];rows=[]
    day=None;daybalance=cfg.initial_eur;highestdaybalance=cfg.initial_eur
    prague=q.timestamp.dt.tz_convert('Europe/Prague').dt.strftime('%Y-%m-%d').to_numpy()
    first2daily=first2total=first1daily=first1trailing=None
    def charge(now,fxbid):
        nonlocal cash,lastfund,tradefund,totalfund,heldseconds
        elapsed=max(0.,now-lastfund);debit=notional*cfg.funding_annual*elapsed/cfg.seconds_per_year/fxbid
        cash-=debit;tradefund+=debit;totalfund+=debit;heldseconds+=elapsed;lastfund=now
    def enter(now,bid,ask,fxbid,fxask,fxstamp,age,chosen,signal_time,signal_bid,bb,cycle_id):
        nonlocal cash,units,direction,entry,reference,entry_t,entry_signal_t,entry_cash,entry_bb,entry_fx,entry_cycle,notional,lastfund,tradefees,tradefund,totalfees,turnover,slip_est,spread_est
        actual=(ask+cfg.slippage_usd_per_gbp) if chosen==1 else (bid-cfg.slippage_usd_per_gbp)
        raw=max(0.,cash)/(cfg.contract_gbp*actual/fxask+cfg.commission_usd_per_lot_side/fxbid)
        lots=math.floor(raw/cfg.lot_step+1e-12)*cfg.lot_step
        if lots<cfg.min_lot:diag['skipped_minimum_lot']+=1;return False
        entry_cash=cash;units=lots*cfg.contract_gbp;direction=chosen;entry=actual;reference=signal_bid;entry_t=now;entry_signal_t=signal_time
        entry_bb=bb;entry_cycle=cycle_id;entry_fx={'bid':fxbid,'ask':fxask,'timestamp':fxstamp,'age_seconds':age}
        notional=abs(units*entry);lastfund=now;tradefund=0.;tradefees=lots*cfg.commission_usd_per_lot_side/fxbid
        cash-=tradefees;totalfees+=tradefees;turnover+=notional/fxask
        slip_est+=units*cfg.slippage_usd_per_gbp/fxbid;spread_est+=units*(ask-bid)/2/fxbid
        year=pd.Timestamp(now,unit='s',tz='UTC').year;entries_year[year]=entries_year.get(year,0)+1
        diag['filled_longs' if chosen==1 else 'filled_shorts']+=1
        return True
    def close(now,bid,ask,fxbid,fxask,fxstamp,age,reason,signal_time=None,signal_bid=None):
        nonlocal cash,units,tradefees,totalfees,turnover,slip_est,spread_est
        actual=(bid-cfg.slippage_usd_per_gbp) if direction==1 else (ask+cfg.slippage_usd_per_gbp)
        pnl_usd=direction*units*(actual-entry);pnl=usd_eur(pnl_usd,fxbid,fxask)
        fee=units/cfg.contract_gbp*cfg.commission_usd_per_lot_side/fxbid
        cash+=pnl-fee;tradefees+=fee;totalfees+=fee;turnover+=abs(units*actual)/fxask
        slip_est+=units*cfg.slippage_usd_per_gbp/fxbid;spread_est+=units*(ask-bid)/2/fxbid
        delay=0. if signal_time is None else now-signal_time
        if delay>0:diag['delayed_exit_count']+=1;diag['max_exit_delay_seconds']=max(diag['max_exit_delay_seconds'],delay)
        diag['exit_reason_counts'][reason]=diag['exit_reason_counts'].get(reason,0)+1
        trades.append({'direction':'long' if direction==1 else 'short','entry_signal_utc':pd.Timestamp(entry_signal_t,unit='s',tz='UTC').isoformat(),
            'entry_utc':pd.Timestamp(entry_t,unit='s',tz='UTC').isoformat(),'entry_signal_bid':reference,
            'entry_upper_band':entry_bb.get('upper'),'entry_lower_band':entry_bb.get('lower'),'entry_bb_mean':entry_bb.get('mean'),'entry_bb_population_std':entry_bb.get('std'),
            'entry_source_bar_start_hour':entry_bb.get('source_hour'),'reset_cycle':entry_cycle,
            'entry_delay_seconds':entry_t-entry_signal_t,'exit_utc':pd.Timestamp(now,unit='s',tz='UTC').isoformat(),
            'exit_signal_utc':pd.Timestamp(signal_time,unit='s',tz='UTC').isoformat() if signal_time is not None else '',
            'exit_signal_bid':signal_bid,'exit_reason':reason,'exit_delay_seconds':delay,'held_event_count_at_exit':hold_count,
            'lots':units/cfg.contract_gbp,'base_gbp_units':units,'entry_usd_per_gbp':entry,'exit_usd_per_gbp':actual,'entry_usd_notional':notional,
            'entry_fx_bid':entry_fx['bid'],'entry_fx_ask':entry_fx['ask'],'entry_fx_timestamp':pd.Timestamp(entry_fx['timestamp'],unit='s',tz='UTC').isoformat(),
            'entry_fx_quote_age_seconds':entry_fx['age_seconds'],'exit_fx_bid':fxbid,'exit_fx_ask':fxask,
            'exit_fx_timestamp':pd.Timestamp(fxstamp,unit='s',tz='UTC').isoformat(),'exit_fx_quote_age_seconds':age,
            'price_pnl_usd':pnl_usd,'price_pnl_eur':pnl,'commission_eur':tradefees,'funding_eur':tradefund,
            'net_pnl_eur':cash-entry_cash,'balance_after_eur':cash,'holding_hours':(now-entry_t)/3600})
        units=0.
    for i,t in enumerate(ts):
        bid=a['bid_open'][i];ask=a['ask_open'][i];fxbid=a['fx_bid_open'][i];fxask=a['fx_ask_open'][i]
        if prague[i]!=day:day=prague[i];daybalance=cash;highestdaybalance=max(highestdaybalance,daybalance)
        if units:charge(t,fxbid)
        if case=='buy_hold' and i==0:
            if ages[i]>cfg.max_entry_fx_age_seconds:raise ValueError('Initial benchmark FX quote older than15min')
            enter(t,bid,ask,fxbid,fxask,fxstamps[i],ages[i],1,t,bid,{},'benchmark')
        for ev in events.get(i,[]):
            before_has=has_traded;before_units=direction*units;before_hold=hold_count;signal_t=ev.signal_utc.timestamp()
            if ev.reset_observed:has_traded=False;cycle=ev.signal_utc.isoformat();diag['observed_resets']+=1
            if ev.entry_window:diag['entry_window_events']+=1
            chosen=1 if strictly_above(ev.signal_bid,ev.upper_band) else -1 if strictly_below(ev.signal_bid,ev.lower_band) else 0
            if ev.entry_window and chosen:diag['breakout_events_in_window']+=1
            attempted=False;filled=False;failure='';reason=None
            # Source order: ENTRY before EXIT. A held position prevents entry
            # even if this event subsequently triggers its exit.
            if not units and not has_traded and ev.entry_window and chosen:
                attempted=True;has_traded=True;hold_count=0;diag['entry_attempts_when_allowed']+=1
                delay=t-signal_t
                if delay>cfg.max_entry_delay_seconds:diag['skipped_entry_delay']+=1;failure='entry_delay'
                elif ages[i]>cfg.max_entry_fx_age_seconds:diag['skipped_entry_fx_stale']+=1;failure='fx_stale'
                else:
                    bb={'upper':ev.upper_band,'lower':ev.lower_band,'mean':ev.bb_mean,'std':ev.bb_population_std,'source_hour':ev.source_hour}
                    filled=enter(t,bid,ask,fxbid,fxask,fxstamps[i],ages[i],chosen,signal_t,ev.signal_bid,bb,cycle)
                    if not filled:failure='minimum_lot'
                    elif delay>0:diag['delayed_entry_count']+=1;diag['max_entry_delay_seconds']=max(diag['max_entry_delay_seconds'],delay)
            if units:
                hold_count+=1
                reason=exit_reason(direction,ev.signal_bid,reference,hold_count,cfg)
                if reason:close(t,bid,ask,fxbid,fxask,fxstamps[i],ages[i],reason,signal_t,ev.signal_bid)
            trace.append({'signal_utc':ev.signal_utc,'bar_start_utc':ev.bar_start_utc,'bar_start_source_clock':ev.bar_start_source_clock,
                'source_hour':ev.source_hour,'source_day':ev.source_day,'signal_bid':ev.signal_bid,'bb_mean':ev.bb_mean,'bb_population_std':ev.bb_population_std,
                'upper_band':ev.upper_band,'lower_band':ev.lower_band,'entry_window':ev.entry_window,'reset_observed':ev.reset_observed,'reset_cycle':cycle,
                'has_traded_before':before_has,'has_traded_after':has_traded,'signed_units_before':before_units,'signed_units_after':direction*units,
                'held_events_before':before_hold,'held_events_after':hold_count,'breakout_direction':chosen,'entry_attempted':attempted,'entry_filled':filled,
                'entry_failure':failure,'exit_reason':reason or '', 'processing_quote_utc':pd.Timestamp(t,unit='s',tz='UTC'),'processing_delay_seconds':t-signal_t})
        if units:heldage=max(heldage,float(ages[i]));heldstale+=int(ages[i]>0);heldold+=int(ages[i]>3600)
        now=t+cfg.bar_seconds;bid=a['bid_close'][i];ask=a['ask_close'][i];fxbid=a['fx_bid_close'][i];fxask=a['fx_ask_close'][i]
        if units:charge(now,fxbid)
        liquidation=bid if direction==1 else ask
        equity=cash+usd_eur(direction*units*(liquidation-entry),fxbid,fxask) if units else cash
        if i==len(ts)-1 and units:close(now,bid,ask,fxbid,fxask,fxstamps[i],ages[i],'forced_window_end');equity=cash;diag['forced_window_end_exits']+=1
        stamp=pd.Timestamp(now,unit='s',tz='UTC').isoformat()
        if equity<daybalance-.05*cfg.initial_eur and first2daily is None:first2daily={'utc':stamp,'equity_eur':equity,'floor_eur':daybalance-.05*cfg.initial_eur}
        if equity<.9*cfg.initial_eur and first2total is None:first2total={'utc':stamp,'equity_eur':equity,'floor_eur':.9*cfg.initial_eur}
        if equity<daybalance-.03*cfg.initial_eur and first1daily is None:first1daily={'utc':stamp,'equity_eur':equity,'floor_eur':daybalance-.03*cfg.initial_eur}
        if equity<highestdaybalance-.1*cfg.initial_eur and first1trailing is None:first1trailing={'utc':stamp,'equity_eur':equity,'floor_eur':highestdaybalance-.1*cfg.initial_eur}
        rows.append((now,equity,cash,direction*units))
    curve=pd.DataFrame(rows,columns=['unix','equity_eur','balance_eur','signed_gbp_units']);curve.index=pd.to_datetime(curve.pop('unix'),unit='s',utc=True);curve.index.name='timestamp'
    daily=curve.resample('1D').last().reindex(pd.date_range(START,END-pd.Timedelta(days=1),freq='D',name='timestamp')).ffill()
    daily[['equity_eur','balance_eur']]=daily[['equity_eur','balance_eur']].fillna(cfg.initial_eur);daily.signed_gbp_units=daily.signed_gbp_units.fillna(0.)
    log=pd.DataFrame(trades)
    if log.empty:log=pd.DataFrame(columns=['entry_utc','exit_utc','net_pnl_eur','funding_eur','commission_eur'])
    net=float(log.net_pnl_eur.sum()) if len(log) else 0.;closed_daily=log.groupby(pd.to_datetime(log.exit_utc,utc=True).dt.tz_convert('Europe/Prague').dt.date).net_pnl_eur.sum() if len(log) else pd.Series(dtype=float)
    best=max(0.,float(closed_daily.max())) if len(closed_daily) else 0.
    info={'label':'Combined GBPUSD BB10 breakout' if case=='strategy' else 'Buy and hold GBPUSD CFD','commission_eur':totalfees,'funding_eur':totalfund,
        'modeled_slippage_eur_indicative':slip_est,'quoted_spread_eur_indicative':spread_est,
        'embedded_cost_estimate_note':'Half quoted spread per side and slippage valued using contemporaneous FX bid; both embedded in price P&L, not additional cash debits. Net USD conversion makes indicative attribution non-additive.',
        'turnover_multiple_of_initial':turnover/cfg.initial_eur,'exposure_time_pct':100*heldseconds/(END-START).total_seconds(),
        'held_fx_max_quote_age_seconds':heldage,'held_bars_with_stale_fx':heldstale,'held_bars_with_fx_older_than_hour':heldold,
        'entries_by_year':entries_year,'execution_diagnostics':diag,
        'screen_2step':{'classification':'static-total-loss sampled breach under model' if first2total else 'approximate daily flag; pass NOT certified' if first2daily else 'no sampled breach; pass NOT certified',
          'approximate_daily_loss_flag':first2daily,'total_loss_breach':first2total,'limits':'5% initial daily below Prague-midnight balance; static EUR9000 overall floor; targets10%/5%; four opening days per phase',
          'limitations':'Single continuous account, no target stops or phase restarts. First Prague-day quote approximates midnight. SampledM5 close equity not tick path or actual swap; no pass certification.'},
        'screen_1step':{'classification':'approximate necessary-condition screening; pass NOT certified','approximate_daily_loss_flag':first1daily,'approximate_trailing_loss_flag':first1trailing,
          'total_net_closed_profit_eur':net,'best_closed_profit_day_eur':best,'best_day_share_of_net_profit_pct':100*best/net if net>0 else None,
          'consistency_condition_at_end':bool(best<=.5*net) if net>0 else False,'profit_target_eur':1000.,'ending_closed_profit_meets_target':net>=1000.,
          'limits':'3% initial daily; highest prior Prague-midnight balance anchored at initial minus10% initial overall floor; target10%; best closed-profit day<=50% TOTAL NET CLOSED PROFIT including losing days, current orders>=12Oct2026.',
          'limitations':'Approximate first-quote midnight balance; net trade costs allocated to exit day. No complete sequential challenge replay, actual broker swap or tick-equity certification.'}}
    return daily,log,info,curve,pd.DataFrame(trace)

def run(directory:Path,out:Path):
    all_quotes,prov=load_data(directory);cfg=Config();signals=build_signals(all_quotes,cfg);out.mkdir(parents=True,exist_ok=True)
    signals.to_csv(out/'hourly_signals.csv.gz',index=False,float_format='%.10f')
    results={};curves={}
    for case in ['strategy','buy_hold']:
        daily,trades,info,sampled,trace=simulate(all_quotes,signals,case,cfg)
        daily.to_csv(out/f'{case}_daily_equity.csv',float_format='%.8f');trades.to_csv(out/f'{case}_trades.csv',index=False,float_format='%.10f')
        if case=='strategy':trace.to_csv(out/'strategy_event_trace.csv.gz',index=False,float_format='%.10f')
        row={**metrics(daily,trades),**info};peak=np.maximum.accumulate(np.r_[cfg.initial_eur,sampled.equity_eur.to_numpy()])[1:]
        row['sampled_max_drawdown_pct']=float((1-sampled.equity_eur/peak).max()*100);row['sampled_max_drawdown_eur']=float(-(sampled.equity_eur-peak).min())
        row['diagnostic_splits']={}
        for first,last in [('2016','2020'),('2021','2025')]:
            sub=daily.loc[first:last];before=daily[daily.index<sub.index[0]];initial=float(before.equity_eur.iloc[-1]) if len(before) else cfg.initial_eur
            en=pd.to_datetime(trades.entry_utc,utc=True);ex=pd.to_datetime(trades.exit_utc,utc=True)
            closed=trades[(en>=sub.index[0])&(ex<sub.index[-1]+pd.Timedelta(days=1))]
            m=metrics(sub,closed,initial);m['trade_metric_scope']='Trades fully contained in split; cross-boundary trades excluded from split PF/win rate while equity remains continuous.'
            row['diagnostic_splits'][first+'-'+last]=m
        annual=daily.equity_eur.resample('YE').last();ret=annual.pct_change();ret.iloc[0]=annual.iloc[0]/cfg.initial_eur-1
        row['annual_returns_pct']={str(t.year):float(v*100) for t,v in ret.items()}
        if abs(trades.net_pnl_eur.sum()-(row['final_equity_eur']-cfg.initial_eur))>1e-5:raise AssertionError('Trade net P&L does not reconcile')
        if abs(trades.funding_eur.sum()-info['funding_eur'])>1e-5 or abs(trades.commission_eur.sum()-info['commission_eur'])>1e-5:raise AssertionError('Trade costs do not reconcile')
        results[case]=row;curves[case]=daily
    report={'status':'completed retrospective GBPUSD combined-baseline research model','period':'2016-01-01 through2025-12-31 UTC;2015 warmup',
        'source_rule':SOURCE,'clock_source':CLOCK_SOURCE,'source_published':'2017, updated2020','cases':'One combined long/short BB10 baseline plus a long buy-and-hold benchmark; no clock or parameter variants tested.',
        'config':dataclasses.asdict(cfg),'data':prov,'signal_diagnostics':{'observed_hourly_events':len(signals),'entry_window_events':int(signals.entry_window.sum()),
            'observed_reset_events':int(signals.reset_observed.sum()),'clock':'Source FXCM BAR-START fixed EST UTC−5, no DST. Entry starts05..10EST =10..15UTC, decisions11..16UTC; observed start01EST reset =decision07UTC.',
            'indicator':'BB10 uses last10 CLOSED observed H1 BID closes including current, simple mean and POPULATION standard deviation ±2.2. Empty hours omitted;2015 warmup.',
            'ordering':'Observed reset first; entry before exit; entry event increments held count to1, timed exit when count>5 on sixth held observed event. No same-event reentry.'},
        'results':results,'limitations':['One frozen combined long/short baseline, not separate directional cases. Source title is not evidence of a London08:00 entry: actual C# uses bar.Time.Hour; primary QC clarification identifies FXCM bar clock as fixed UTC−5.',
            'Dukascopy BID candles and first subsequent M5 bid/ask executions are a transparent adaptation of historical LEAN/FXCM feed and execution, not exact reproduction of original backtest.',
            'H1 bars are [t−1h,t), last observed M5 BID close known at t. BB includes current close. Missing hours emit no event and do not advance hold counter; missing source01 reset does not reset allowance automatically.',
            'Entry before exit, once per observed01 reset cycle. A qualifying attempted order consumes allowance even if skipped for delay, stale FX or lot minimum. Entry firstM5 opening quote>=decision, delay<=15min and FXage<=15min.',
            'Signal exit strict8pip profit or18pip loss from entry SIGNAL BID, not fill price. Only observed H1 close checks, not intrabar stop/limit orders. Hold counter includes entry event and exits when>5. Delayed exits retained until first subsequent quote; no same-event reentry.',
            'EUR CFD cash account; GBP exposure initially<=1x via contemporaneous EURUSD conversion with fee reserve and0.01lot floor. PositiveUSDpnl/FXask, losses/fees/funding/FXbid. Fixed initial units buyhold is a CFD benchmark, not physical currency deposit return.',
            'Historical bid/ask plus0.1pip adverse slippage per side, USD3.50/lot/side. Both directions charged ASSUMED5% annually on absolute entryUSD notional for actual elapsed calendar time; not historical swap/carry. Cash interest0.',
            'Dukascopy data via EV Trading Labs, not independently reconciled direct bank ticks or FTMO broker quotes. Missing FX uses prior observed close, entryage bounded15min, exit/valuation staleness disclosed.',
            'Frozen2016–2020 /2021–2025 retrospective diagnostics, not pristine prospective OOS; source2017 overlaps firstperiod. No parameter optimization or alternative clocks selected by outcomes.',
            'PF/win rate net closed trades including all costs. Equity/drawdown calendar daily closes plus sampledM5, not tick path. AnnualizedSharpe sqrt365/riskfree0. Allremainingpositionsforcedclosedatlastavailable2025barclose with costs.',
            'FTMO continuous necessary-condition screen only: approximate Prague-midnight balance using first daily quote, no full phase/target/restart replay, no actual broker swap or tick-equity certification.']}
    (out/'summary.json').write_text(json.dumps(safe_json(report),indent=2)+'\n')
    pd.DataFrame({k:{key:v for key,v in r.items() if isinstance(v,(str,int,float)) or v is None} for k,r in results.items()}).T.to_csv(out/'summary.csv',index_label='case')
    charts(curves,results,out)
    print(json.dumps({k:{key:v[key] for key in ['final_equity_eur','net_profit_eur','profit_factor','sharpe','max_drawdown_pct','closed_trades','execution_diagnostics']} for k,v in results.items()},indent=2))

if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--data-dir',type=Path,default=Path(__file__).parent/'data');p.add_argument('--out',type=Path,default=Path(__file__).parent/'results');args=p.parse_args();run(args.data_dir,args.out)
