# Initial Balance (IB) strategy backtest, PerpRoom, 2026-11. Free to use.
# Times are New York (DST-aware). Entries on 5m candle close, exits checked from the next candle (no lookahead).
# If one candle touches both stop and target, we count the stop (conservative).
import sys, json, pandas as pd, numpy as np
FEE=0.0005  # taker fee 0.05% on entry and on exit
def load(sym):
    # Binance USD-M futures 5m candles (open time, UTC), e.g. from data.binance.vision
    df=pd.read_csv(f"{sym}_5m.csv",parse_dates=["time"],index_col="time")
    if df.index.tz is None: df.index=df.index.tz_localize("UTC")
    df.index=df.index.tz_convert("America/New_York")
    return df
def run(df, tol=0.1, buf=0.05, setups=("A","B")):
    out=[]
    for day,g in df.groupby(df.index.date):
        if pd.Timestamp(day).weekday()>=5: continue
        t=g.index.strftime("%H:%M")
        ib=g[(t>="09:30")&(t<"10:30")]
        if len(ib)<12: continue
        H,L=ib.high.max(),ib.low.min(); W=H-L; M=(H+L)/2
        if W<=0: continue
        up=ib.close.iloc[-1]>ib.open.iloc[0]
        sess=g[(t>="10:30")&(t<"16:00")]
        st=sess.index.strftime("%H:%M")
        trades=[]
        # A: trend continuation (pullback to IB mid, close back in trend direction)
        if "A" in setups:
            for i,(ts,b) in enumerate(sess.iterrows()):
                if st[i]>="15:00": break
                if up and b.close<L: break
                if (not up) and b.close>H: break
                if up and b.low<=M+tol*W and b.close>M and b.close>b.open:
                    stop=min(sess.low.iloc[:i+1].min(),M)-buf*W; trades.append(("A",1,i,b.close,stop,H)); break
                if (not up) and b.high>=M-tol*W and b.close<M and b.close<b.open:
                    stop=max(sess.high.iloc[:i+1].max(),M)+buf*W; trades.append(("A",-1,i,b.close,stop,L)); break
        # B: failed auction (close outside the IB, then close back inside)
        if "B" in setups:
            out_side=0; ext=None
            for i,(ts,b) in enumerate(sess.iterrows()):
                if st[i]>="15:00": break
                if out_side==0:
                    if b.close>H: out_side=1; ext=b.high
                    elif b.close<L: out_side=-1; ext=b.low
                    continue
                if out_side==1:
                    ext=max(ext,b.high)
                    if b.close<H: trades.append(("B",-1,i,b.close,ext+buf*W,M)); break
                else:
                    ext=min(ext,b.low)
                    if b.close>L: trades.append(("B",1,i,b.close,ext-buf*W,M)); break
        losses=0
        for s,side,i,e,stop,tp in sorted(trades,key=lambda x:x[2]):
            if losses>=2: break
            risk=abs(e-stop)
            if risk<=0 or (tp-e)*side<=0: continue
            res=None
            for j in range(i+1,len(sess)):
                b=sess.iloc[j]
                hit_s = b.low<=stop if side==1 else b.high>=stop
                hit_t = b.high>=tp if side==1 else b.low<=tp
                if hit_s: res=stop; break
                if hit_t: res=tp; break
            if res is None: res=sess.close.iloc[-1]
            gross=(res-e)*side
            net=gross-FEE*(e+res)
            r=net/risk
            out.append({"day":str(day),"setup":s,"side":side,"entry":e,"exit":res,"R":r,"R_gross":gross/risk,"win":net>0,"win_gross":gross>0,"planned_R":abs(tp-e)/risk})
            if net<=0: losses+=1
    return pd.DataFrame(out)
def summ(d):
    if d.empty: return {}
    eq=(1+0.01*d.R).cumprod()
    return {"trades":len(d),"win_rate":round(d.win.mean()*100,1),"win_rate_before_fees":round(d.win_gross.mean()*100,1),
            "avg_R":round(d.R.mean(),3),"total_R":round(d.R.sum(),1),"median_planned_R":round(d.planned_R.median(),2),
            "acct_1pct_risk_pct":round((eq.iloc[-1]-1)*100,1),"max_dd_pct":round(((eq/eq.cummax())-1).min()*100,1),
            "from":d.day.min(),"to":d.day.max()}
res={}
for sym in ["BTCUSDT","ETHUSDT"]:
    df=load(sym)
    for tol,buf in [(0.1,0.05),(0.05,0.0),(0.2,0.1)]:
        d=run(df,tol,buf)
        key=f"{sym} tol{tol} buf{buf}"
        res[key]={"all":summ(d),"A":summ(d[d.setup=="A"]),"B":summ(d[d.setup=="B"])}
        if tol==0.1:
            d.to_csv(f"initial_balance_{sym}_trades.csv",index=False)
            d["year"]=d.day.str[:4]
            res[key]["by_year"]={y:summ(x) for y,x in d.groupby("year")}
print(json.dumps(res,indent=1))
