"""v3cells.py (A1.19): more trades a day. Same idea at other checkpoints/bands, $100, stop 0.5x, 4 h time stop, pull = 0, one position per token.
Pick on H1 (cell's NEW coins, not in base, must be positive on H1), test once on H2 as base + passing cells."""
import collections, statistics as st, datetime
exec(open("/root/fwa1/v3exit.py").read().split("extdone = ")[0])
extdone = {r[0] for r in E.execute("SELECT DISTINCT pool FROM done")}
H = 3600; NEED = int(4.5 * H / SPB)
full = [p for p in pools if p["pool"] in extdone and meta[p["pool"]][4] + NEED <= head]
for p in full: CACHE[p["pool"]] = path12(p)
SC.clear()
src = open("/root/fwa1/v3exit.py").read()
exec(src[src.index("def run("):src.index("H = 3600")])
tokof = {r[0]: r[1] for r in D.execute("SELECT pool, token FROM meta")}
CELLS = [("base +5m 250k-1M", 300, 2.5e5, 1e6), ("+5m 1M-2M", 300, 1e6, 2e6), ("+10m 500k-2M", 600, 5e5, 2e6), ("+10m 1M-3M", 600, 1e6, 3e6),
         ("+15m 500k-2M", 900, 5e5, 2e6), ("+15m 1M-3M", 900, 1e6, 3e6)]
SIG = {}
for name, te, lo, hi in CELLS:
    out = {}
    for p in full:
        s = series_t(p, 100, te)
        if s and lo <= s[4] < hi:
            out[tokof[p["pool"]].lower()] = (p, run(s, tstop=te + 4 * H))
    SIG[name] = out
print("pools with 4.5 h data", len(full), "head", head)
alld = sorted({day(p["t"]) for p in full}); D1 = [d for d in alld if d < day(CUT)]; D2 = [d for d in alld if d >= day(CUT)]
def stats(trades, days):
    v = [x for p, x in trades]
    if not v: return "n0"
    return "n%d (%.1f/day) mean %.2fx med %.2fx $%.0f/day" % (len(v), len(v) / len(days), st.mean(v), st.median(v), sum(x - 1 for x in v) * 100 / len(days))
def worst3(trades, days):
    pn = collections.defaultdict(float)
    for p, x in trades: pn[day(p["t"])] += (x - 1) * 100
    dl = sorted(datetime.date(2026, int(d[:2]), int(d[3:])) for d in days)
    cal = [dl[0] + datetime.timedelta(k) for k in range((dl[-1] - dl[0]).days + 1)]
    vals = [pn.get(c.strftime("%m-%d"), 0.0) for c in cal]
    return min(sum(vals[i:i + 3]) for i in range(len(vals) - 2)) if len(vals) >= 3 else min(vals)
base = SIG[CELLS[0][0]]
print("\nper cell (standalone; overlap = tokens also traded by base)")
for name, te, lo, hi in CELLS:
    for h, days in (("H1", D1), ("H2", D2)):
        T = [(p, x) for t, (p, x) in SIG[name].items() if day(p["t"]) in days]
        new = [(p, x) for t, (p, x) in SIG[name].items() if day(p["t"]) in days and t not in base]
        print("  %-18s %s all: %s | overlap %d | NEW coins: %s" % (name, h, stats(T, days), len(T) - len(new), stats(new, days)))
picked = []
used = set(base)
for name, te, lo, hi in CELLS[1:]:
    new1 = [(p, x) for t, (p, x) in SIG[name].items() if day(p["t"]) in D1 and t not in used]
    if new1 and sum(x - 1 for p, x in new1) > 0:
        picked.append(name); used |= set(SIG[name])
print("\nH1 picks (new coins positive on H1, first signal wins):", picked)
def book(names, days):
    seen = {}
    for n in [CELLS[0][0]] + names:
        te = [c[1] for c in CELLS if c[0] == n][0]
        for t, (p, x) in SIG[n].items():
            if day(p["t"]) in days and (t not in seen or te < seen[t][0]): seen[t] = (te, p, x)
    return [(p, x) for te, p, x in seen.values()]
for h, days in (("H1", D1), ("H2", D2)):
    b = book([], days); c = book(picked, days)
    print("  %s base     %s worst3 $%.0f" % (h, stats(b, days), worst3(b, days)))
    print("  %s combined %s worst3 $%.0f" % (h, stats(c, days), worst3(c, days)))
b2 = book([], D2); c2 = book(picked, D2)
gain = (sum(x - 1 for p, x in c2) - sum(x - 1 for p, x in b2)) * 100 / len(D2)
ok = gain > 0 and worst3(c2, D2) >= 1.5 * min(worst3(b2, D2), -1)
print("\nH2 verdict: adds $%.0f/day, worst3 base $%.0f -> combined $%.0f => %s" % (gain, worst3(b2, D2), worst3(c2, D2), "PASS" if ok else "FAIL"))
print("\neach picked cell alone added to base on H2 (context):")
for n in picked:
    c = book([n], D2); print("  %-18s +$%.0f/day worst3 $%.0f" % (n, (sum(x - 1 for p, x in c) - sum(x - 1 for p, x in b2)) * 100 / len(D2), worst3(c, D2)))
