"""What happened after each kind of weekly / monthly close, pooled over the 10 majors (OKX, UTC candles)."""
import json, time, urllib.request, statistics as S, collections
import candles as K
MAJ=["BTC","ETH","SOL","XRP","BNB","DOGE","TRX","ADA","HYPE","LINK"]
def okx(sym,bar,pages):
    out=[]; after=None
    for _ in range(pages):
        u=f"https://www.okx.com/api/v5/market/history-candles?instId={sym}-USDT&bar={bar}&limit=100"+(f"&after={after}" if after else "")
        d=json.load(urllib.request.urlopen(urllib.request.Request(u,headers={"User-Agent":"Mozilla/5.0"}),timeout=20))["data"]
        if not d: break
        out+=d; after=d[-1][0]; time.sleep(0.15)
    rows=sorted({int(r[0]):r for r in out}.values(),key=lambda r:int(r[0]))
    return [[int(r[0])//1000,float(r[1]),float(r[2]),float(r[3]),float(r[4]),r[8]] for r in rows]
res={}
for bar,period,pages in (("1Wutc","week",5),("1Mutc","month",2)):
    agg=collections.defaultdict(list)
    for s in MAJ:
        cs=[r[:5] for r in okx(s,bar,pages) if r[5]=="1"]   # closed candles only
        for i in range(3,len(cs)-1):
            r=K.classify(cs,i,period)
            if r: agg[r["key"]].append(cs[i+1][4]/cs[i][4]-1)
        time.sleep(0.2)
    allx=[x for v in agg.values() for x in v]
    res[period]={"base":{"n":len(allx),"mean":round(S.mean(allx)*100,1),"up":round(sum(x>0 for x in allx)/len(allx)*100)}}
    for k,_,lab,_ in K.CATS:
        v=agg.get(k,[])
        if v: res[period][k]={"n":len(v),"mean":round(S.mean(v)*100,1),"med":round(S.median(v)*100,1),"up":round(sum(x>0 for x in v)/len(v)*100)}
json.dump(res,open('closes_hist.json','w'))
for p in res:
    print(p,res[p]["base"])
    for k,v in res[p].items():
        if k!="base": print("  ",k,v)
