utkarshpathak48 commited on
Commit
c4eac91
·
1 Parent(s): d756a14

fix: featured card shows real PA confluence grade

Browse files
analysis/EXECUTION-SCRIPT-FOR-SONNET.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # EXECUTION SCRIPT — Signal Analysis Run
2
+ # For: Claude Sonnet (with computer control) · Written by: Fable 5 planning session · 2026-07-11
3
+ # Everything you need is in THIS folder: ~/Documents/trade-copilot-web/analysis/
4
+
5
+ ## CONTEXT (30 seconds)
6
+ Trade Copilot (utkarsh's crypto scanner, live at utkarshpathak48-trade-copilot.hf.space) sends Telegram
7
+ alerts at confidence ≥8.8. We must measure how the last ~50 alerts ACTUALLY performed under Utkarsh's
8
+ real style (market entry at alert moment → exit 100% at TP2, SL as given, no time limit) vs as-alerted
9
+ (entry price → TP1). The analysis toolkit is BUILT AND TESTED (self-test + end-to-end verified).
10
+ Only the input data is missing: the alert history, which exists ONLY in Utkarsh's Telegram chat with the bot.
11
+ Full methodology: signal-analysis-plan.md (this folder). Your job: get the data, run the pipeline, interpret.
12
+
13
+ ## STEP 1 — GET THE ALERT HISTORY (choose path A, fall back to B, then C)
14
+
15
+ ### Path A (preferred): Telegram Desktop export
16
+ The App Store "Telegram" for macOS has NO export feature. The official "Telegram Desktop" (tdesktop) does.
17
+ 1. Have Utkarsh download Telegram Desktop from https://desktop.telegram.org (or `brew install --cask telegram-desktop`).
18
+ 2. UTKARSH logs in himself (QR scan from phone). ⚠ You must NEVER type his phone number, password, or login code — he does all authentication personally.
19
+ 3. In Telegram Desktop: open the Trade Copilot bot chat → ⋮ (top right) → Export chat history →
20
+ UNTICK all media → Format: **Machine-readable JSON** → Export. Result: a folder containing `result.json`.
21
+ 4. Copy result.json into this analysis/ folder.
22
+
23
+ ### Path B (if A fails): copy-paste transcript
24
+ 1. In any Telegram client, Utkarsh selects the alert messages (or scrolls + selects all text) and copies them into a plain text file `alerts_paste.txt` in this folder. Timestamps matter: if the paste lacks dates, have him paste in chunks per day and note dates, or hover each message — TG copy usually includes "[DD.MM.YY HH:MM]" prefixes when copying multiple messages.
25
+ 2. Adapt parse_alerts.py: add a txt mode that splits the paste into messages (each alert starts with 🟢 or 🔴 followed by "SYMBOL-USDT LONG/SHORT · X.X/10") and reads the nearest preceding "[date time]" stamp. The regexes in the script already match the alert body — you only add message-splitting + date capture. Keep output CSV columns identical.
26
+
27
+ ### Path C (last resort): MTProto user-session script
28
+ Use Telethon with Utkarsh's own api_id/api_hash from my.telegram.org (HE creates them and HE enters the login code). Script: iterate messages from the bot chat, dump text+date to JSON matching Telegram-export shape, feed to parse_alerts.py unchanged. Do not store the session file afterwards; delete it.
29
+
30
+ ## STEP 2 — RUN THE PIPELINE (2 commands, this folder)
31
+ ```bash
32
+ cd ~/Documents/trade-copilot-web/analysis
33
+ python3 parse_alerts.py result.json # → alerts.csv (prints count + how many ≥8.8)
34
+ python3 replay_signals.py alerts.csv # → replay_results.csv + signal_report.md
35
+ ```
36
+ - Scripts are stdlib-only Python 3. replay fetches public BingX 1m candles (no keys), caches in ./cache/, ~1–3 min for 50 alerts. Rerun-safe.
37
+ - Sanity first: `python3 replay_signals.py --selftest` must print SELFTEST OK.
38
+ - If some alerts print NO_DATA: BingX 1m history doesn't reach that far back for that symbol — acceptable, note the count. If MANY fail, retry those with interval 5m (edit fetch interval fallback or note it).
39
+ - If alerts.csv has <20 rows, tell Utkarsh how many were found before proceeding — maybe the export missed older history.
40
+
41
+ ## STEP 3 — INTERPRET (this is the real deliverable)
42
+ Read signal_report.md + replay_results.csv and write `signal_verdict.md` answering EXACTLY these:
43
+ 1. HEADLINE: S1 vs S2 win rate, total R, and net $ outcome on a $10 all-in account at 4× and 6× leverage
44
+ (loss per losing trade ≈ leverage × SL-distance% × $10; compound sequentially in alert order; include the −0.1%×lev fee drag per trade).
45
+ 2. LATENESS VERDICT: median Lateness Index; % of alerts with LI > 0.7; win rate per LI bucket.
46
+ → Recommend the LI cutoff above which trades should be SKIPPED (this becomes automation config LI_LIMIT).
47
+ 3. TP VERDICT: median MFE vs median TP2 distance (tp2_dist_r column); heartbreak rate (came ≥75% of way to TP2 then lost).
48
+ → Recommend: keep TP2 / dynamic TP at k×median-MFE / TP1.5 midpoint — whichever maximizes total R recomputed from the MFE data.
49
+ 4. SL VERDICT: MAE distribution of WINNING trades (s2_mae on wins). If many winners saw MAE > 0.8R, SL is too tight.
50
+ → Recommend keep/widen (+ leverage compensation note).
51
+ 5. THRESHOLD: compare 8.8–9.0 vs 9.0+ cohorts (conf column) on S2 expectancy → recommend CONF_MIN.
52
+ 6. SKIP-LIST: any symbol or direction with ≥3 trades and 0 wins.
53
+ 7. CAVEATS: n, confidence interval (95% CI ≈ ±1.96×sqrt(wr×(1−wr)/n)), regime concentration (all alerts from ~1 month).
54
+ Every recommendation must cite the numbers. If data contradicts Utkarsh's beliefs, say so plainly — he wants truth, not comfort.
55
+
56
+ ## RULES
57
+ - Do NOT commit or push anything in the git repo without Utkarsh's explicit approval. Do NOT touch static/index.html, main.py, or any production file — this task lives entirely in analysis/.
58
+ - If .git/index.lock errors appear during any git command Utkarsh runs: `rm -f ~/Documents/trade-copilot-web/.git/index.lock` (known stale-lock issue).
59
+ - Never handle credentials/tokens/login codes — Utkarsh types those himself, always.
60
+ - You MAY spawn up to 3 sub-agents (per Utkarsh): sensible split = (1) data acquisition+parsing, (2) replay run+data QA, (3) interpretation+verdict writing. Only if genuinely useful — this is a linear task; agents optional.
61
+ - When finished: present signal_verdict.md + replay_results.csv + signal_report.md to Utkarsh, and tell him to give signal_verdict.md to the next planning session so the automation config (LI_LIMIT, TP policy, SL policy, CONF_MIN, skip-list = rules R1–R5) gets locked.
62
+
63
+ ## WHAT'S ALREADY DONE (do not redo)
64
+ - Toolkit written + verified: parser (handles TG JSON mixed entities, skips heartbeats, 4h dedup), replay engine (self-test green: TP/SL/same-candle-loss/expiry/fees/MFE/MAE/lateness), e2e pipeline proven with injected candles. BingX kline API shape confirmed live.
65
+ - Methodology doc: signal-analysis-plan.md (metric definitions §4-5, decision rules §6).
66
+ - Automation blueprint waiting on your verdict: the planning session's evolution-plan/automation-architecture-v2.md.
analysis/README.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Signal Analysis Toolkit — how to run (2 commands on your Mac)
2
+
3
+ ## Step 0 — Export your Telegram chat (one time, ~2 min)
4
+ 1. Open **Telegram DESKTOP** (not phone) → open the Trade Copilot bot chat
5
+ 2. ⋮ menu → **Export chat history** → format **JSON** → untick all media → Export
6
+ 3. You get a folder with `result.json`
7
+
8
+ ## Step 1 — Parse alerts
9
+ Put `parse_alerts.py`, `replay_signals.py` and `result.json` in one folder, then:
10
+ ```bash
11
+ python3 parse_alerts.py result.json
12
+ ```
13
+ → writes `alerts.csv`, prints how many alerts + how many ≥8.8 conf.
14
+
15
+ ## Step 2 — Replay against real BingX history
16
+ ```bash
17
+ python3 replay_signals.py alerts.csv
18
+ ```
19
+ - Fetches 1-minute candles from BingX public API (no keys needed; ~1-3 min for 50 alerts; candles cached in ./cache so reruns are instant)
20
+ - Writes **replay_results.csv** (per-alert: both scenarios, Lateness Index, 60m momentum, MFE/MAE, adj R/R) and **signal_report.md** (aggregates + buckets)
21
+
22
+ ## Step 3 — Send both output files back to Claude/any AI for interpretation
23
+ The report feeds decision rules R1–R5 in evolution-plan/signal-analysis-plan.md (LI cutoff, TP policy, SL policy, threshold, skip-list) → those lock the automation config.
24
+
25
+ ## Notes
26
+ - S1 "as-alerted" = limit at alert entry (12h fill window), TP1 target. S2 "your style" = market entry at alert moment (+slippage+fees), TP2 target. Both use alert SL. Same-candle TP+SL = counted as LOSS (conservative). 7-day cap.
27
+ - If very old alerts return NO_DATA, BingX 1m history ran out for that symbol — the report simply has fewer rows (noted per row).
28
+ - Both scripts are stdlib-only Python 3 — nothing to install.
29
+ - Self-test anytime: `python3 replay_signals.py --selftest`
analysis/parse_alerts.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """parse_alerts.py — extract Trade Copilot alerts from a Telegram Desktop JSON export.
3
+
4
+ Usage: python3 parse_alerts.py result.json [--out alerts.csv]
5
+ Input: Telegram Desktop > bot chat > Export chat history > JSON (result.json)
6
+ Output: alerts.csv (ts_utc, iso, symbol, direction, conf, entry, sl, tp1, tp2, tp3)
7
+
8
+ Stdlib only. Handles TG's mixed text arrays (strings + entity dicts), skips
9
+ heartbeats/tests/skip-notices, dedups same symbol+direction within 4h (keeps first).
10
+ """
11
+ import json, re, csv, sys, datetime
12
+
13
+ DEDUP_WINDOW_S = 4 * 3600
14
+
15
+ RE_HEAD = re.compile(r'(?:🟢|🔴)?\s*([A-Z0-9]{1,15}-USDT)\s+(LONG|SHORT)\s*·\s*([\d.]+)\s*/\s*10')
16
+ RE_ENTRY = re.compile(r'Entry\s+([\d.,]+)')
17
+ RE_SL = re.compile(r'\bSL\s+([\d.,]+)')
18
+ RE_TP1 = re.compile(r'TP1\s+([\d.,]+)')
19
+ RE_TP2 = re.compile(r'TP2\s+([\d.,]+)')
20
+ RE_TP3 = re.compile(r'TP3\s+([\d.,]+)')
21
+
22
+ SKIP_MARKERS = ("Trade Copilot alive", "Test Message", "Test:", "Skipped", "funds in use",
23
+ "NOT executed", "PROFIT", "LOSS", "ENTERED", "LIQUIDATED", "summary")
24
+
25
+ def flatten_text(t):
26
+ """TG export 'text' is str OR list of str/{'text':...} — flatten to one string."""
27
+ if isinstance(t, str):
28
+ return t
29
+ out = []
30
+ for part in t:
31
+ out.append(part if isinstance(part, str) else str(part.get("text", "")))
32
+ return "".join(out)
33
+
34
+ def num(s):
35
+ return float(s.replace(",", ""))
36
+
37
+ def main():
38
+ if len(sys.argv) < 2:
39
+ sys.exit("usage: python3 parse_alerts.py result.json [--out alerts.csv]")
40
+ src = sys.argv[1]
41
+ out = sys.argv[sys.argv.index("--out") + 1] if "--out" in sys.argv else "alerts.csv"
42
+
43
+ with open(src, encoding="utf-8") as f:
44
+ data = json.load(f)
45
+ messages = data.get("messages", data if isinstance(data, list) else [])
46
+
47
+ rows, skipped, last_seen = [], 0, {}
48
+ for m in messages:
49
+ if m.get("type") != "message":
50
+ continue
51
+ text = flatten_text(m.get("text", ""))
52
+ if not text or any(k in text for k in SKIP_MARKERS):
53
+ continue
54
+ h = RE_HEAD.search(text)
55
+ e, s_, t1 = RE_ENTRY.search(text), RE_SL.search(text), RE_TP1.search(text)
56
+ if not (h and e and s_ and t1):
57
+ continue
58
+ # timestamp: prefer unixtime if present
59
+ if m.get("date_unixtime"):
60
+ ts = int(m["date_unixtime"])
61
+ else:
62
+ # TG export date is local time of the exporting machine; treat as-is, note in README
63
+ ts = int(datetime.datetime.fromisoformat(m["date"]).timestamp())
64
+ sym, direction, conf = h.group(1), h.group(2), float(h.group(3))
65
+ key = f"{sym}:{direction}"
66
+ if key in last_seen and ts - last_seen[key] < DEDUP_WINDOW_S:
67
+ skipped += 1
68
+ continue
69
+ last_seen[key] = ts
70
+ t2, t3 = RE_TP2.search(text), RE_TP3.search(text)
71
+ rows.append({
72
+ "ts_utc": ts,
73
+ "iso": datetime.datetime.fromtimestamp(ts, datetime.timezone.utc).isoformat(),
74
+ "symbol": sym, "direction": direction, "conf": conf,
75
+ "entry": num(e.group(1)), "sl": num(s_.group(1)), "tp1": num(t1.group(1)),
76
+ "tp2": num(t2.group(1)) if t2 else "", "tp3": num(t3.group(1)) if t3 else "",
77
+ })
78
+
79
+ rows.sort(key=lambda r: r["ts_utc"])
80
+ with open(out, "w", newline="", encoding="utf-8") as f:
81
+ w = csv.DictWriter(f, fieldnames=list(rows[0].keys()) if rows else
82
+ ["ts_utc","iso","symbol","direction","conf","entry","sl","tp1","tp2","tp3"])
83
+ w.writeheader()
84
+ w.writerows(rows)
85
+ print(f"parsed {len(rows)} alerts (deduped {skipped}) → {out}")
86
+ if rows:
87
+ print(f"range: {rows[0]['iso']} → {rows[-1]['iso']}")
88
+ hi = [r for r in rows if r["conf"] >= 8.8]
89
+ print(f"conf ≥ 8.8: {len(hi)} alerts")
90
+
91
+ if __name__ == "__main__":
92
+ main()
analysis/replay_signals.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """replay_signals.py — replay Trade Copilot alerts against historical 1m candles.
3
+
4
+ Usage:
5
+ python3 replay_signals.py alerts.csv # full run (network: BingX public API)
6
+ python3 replay_signals.py --selftest # no network; validates outcome logic
7
+
8
+ Outputs: replay_results.csv + signal_report.md
9
+
10
+ Per alert, two scenarios:
11
+ S1 "as-alerted" : limit entry at alert price (must fill within 12h), TP=TP1, SL=SL
12
+ S2 "utkarsh-style": market entry at first candle after alert, TP=TP2, SL=SL
13
+ Conservative: TP and SL touched in same candle => LOSS. 7-day cap => EXPIRED (records final R).
14
+ Fees/slippage on S2: 0.05% taker x2 + 0.05% adverse slip. MFE/MAE measured in R (1R=|entry-SL|).
15
+ Lateness Index LI = (mkt-entry)/(tp1-entry) signed by direction.
16
+ Stdlib only; candle cache in ./cache/ so reruns are free.
17
+ """
18
+ import csv, json, math, os, sys, time, urllib.request, urllib.parse, datetime
19
+
20
+ BASE = "https://open-api.bingx.com/openApi/swap/v3/quote/klines"
21
+ CACHE = "cache"
22
+ FEE = 0.0005 # taker per side
23
+ SLIP = 0.0005 # adverse slippage on market entry
24
+ CAP_DAYS = 7
25
+ FILL_WINDOW_H = 12 # S1 limit-fill window
26
+
27
+ # ── data access ───────────────────────────────────────────────────────────
28
+ def fetch_klines(symbol, start_ms, end_ms, interval="1m"):
29
+ """Paginated forward fetch, cached per (symbol,start,end)."""
30
+ os.makedirs(CACHE, exist_ok=True)
31
+ key = f"{CACHE}/{symbol}_{interval}_{start_ms}_{end_ms}.json"
32
+ if os.path.exists(key):
33
+ return json.load(open(key))
34
+ out, cursor = [], start_ms
35
+ while cursor < end_ms:
36
+ q = urllib.parse.urlencode({"symbol": symbol, "interval": interval,
37
+ "startTime": cursor, "limit": 1000})
38
+ for attempt in range(3):
39
+ try:
40
+ with urllib.request.urlopen(f"{BASE}?{q}", timeout=15) as r:
41
+ d = json.loads(r.read())
42
+ break
43
+ except Exception as e:
44
+ if attempt == 2: raise
45
+ time.sleep(2 * (attempt + 1))
46
+ rows = d.get("data") or []
47
+ if not rows: break
48
+ rows = sorted(rows, key=lambda k: int(k["time"]))
49
+ out += [{"t": int(k["time"]), "o": float(k["open"]), "h": float(k["high"]),
50
+ "l": float(k["low"]), "c": float(k["close"])} for k in rows
51
+ if int(k["time"]) >= cursor]
52
+ new_cursor = int(rows[-1]["time"]) + 60_000
53
+ if new_cursor <= cursor: break
54
+ cursor = new_cursor
55
+ time.sleep(0.15) # rate-limit courtesy
56
+ out = [k for k in out if start_ms <= k["t"] <= end_ms]
57
+ json.dump(out, open(key, "w"))
58
+ return out
59
+
60
+ # ── outcome engine (pure — selftestable) ──────────────────────────────────
61
+ def simulate(candles, entry, tp, sl, direction, fee=FEE):
62
+ """Walk candles; return dict(outcome, exit_px, bars, mfe_r, mae_r, r_net)."""
63
+ long = direction == "LONG"
64
+ risk = abs(entry - sl)
65
+ if risk <= 0: return {"outcome": "BAD_LEVELS"}
66
+ mfe = mae = 0.0
67
+ for i, k in enumerate(candles):
68
+ hi, lo = k["h"], k["l"]
69
+ fav = (hi - entry) if long else (entry - lo)
70
+ adv = (entry - lo) if long else (hi - entry)
71
+ mfe, mae = max(mfe, fav / risk), max(mae, adv / risk)
72
+ tp_hit = (hi >= tp) if long else (lo <= tp)
73
+ sl_hit = (lo <= sl) if long else (hi >= sl)
74
+ if tp_hit and sl_hit: # same candle → conservative LOSS
75
+ return _res("LOSS", sl, entry, risk, i, mfe, mae, long, fee)
76
+ if sl_hit:
77
+ return _res("LOSS", sl, entry, risk, i, mfe, mae, long, fee)
78
+ if tp_hit:
79
+ return _res("WIN", tp, entry, risk, i, mfe, mae, long, fee)
80
+ last = candles[-1]["c"] if candles else entry
81
+ return _res("EXPIRED", last, entry, risk, len(candles), mfe, mae, long, fee)
82
+
83
+ def _res(outcome, exit_px, entry, risk, bars, mfe, mae, long, fee):
84
+ gross = (exit_px - entry) if long else (entry - exit_px)
85
+ fee_r = (entry + exit_px) * fee / risk # both sides, in R
86
+ return {"outcome": outcome, "exit_px": exit_px, "bars": bars,
87
+ "mfe_r": round(mfe, 3), "mae_r": round(mae, 3),
88
+ "r_net": round(gross / risk - fee_r, 3)}
89
+
90
+ def lateness(mkt, entry, tp1, direction):
91
+ denom = (tp1 - entry) if direction == "LONG" else (entry - tp1)
92
+ move = (mkt - entry) if direction == "LONG" else (entry - mkt)
93
+ return round(move / denom, 3) if denom > 0 else None
94
+
95
+ # ── per-alert replay ──────────────────────────────────────────────────────
96
+ def replay(alert):
97
+ ts = int(alert["ts_utc"]) * 1000
98
+ end = ts + CAP_DAYS * 86_400_000
99
+ pre = fetch_klines(alert["symbol"], ts - 3_600_000, ts) # 60m context
100
+ post = fetch_klines(alert["symbol"], ts, end)
101
+ if not post:
102
+ return {"error": "NO_DATA"}
103
+ d = alert["direction"]
104
+ entry_a, sl = float(alert["entry"]), float(alert["sl"])
105
+ tp1 = float(alert["tp1"])
106
+ tp2 = float(alert["tp2"]) if alert.get("tp2") not in ("", None) else tp1
107
+ mkt = post[0]["o"]
108
+ mkt_slipped = mkt * (1 + SLIP) if d == "LONG" else mkt * (1 - SLIP)
109
+
110
+ li = lateness(mkt, entry_a, tp1, d)
111
+ mv60 = round((mkt - pre[0]["o"]) / pre[0]["o"] * 100, 3) if pre else None
112
+
113
+ # S1: limit at alert entry — find fill within window
114
+ s1 = {"outcome": "NEVER_FILLED"}
115
+ fill_i = None
116
+ win_end = min(len(post), FILL_WINDOW_H * 60)
117
+ for i in range(win_end):
118
+ k = post[i]
119
+ if (k["l"] <= entry_a <= k["h"]):
120
+ fill_i = i; break
121
+ if (d == "LONG" and k["l"] <= entry_a) or (d == "SHORT" and k["h"] >= entry_a):
122
+ fill_i = i; break
123
+ if fill_i is not None:
124
+ s1 = simulate(post[fill_i:], entry_a, tp1, sl, d)
125
+ # S2: market entry, TP2 target
126
+ sl_ok = (sl < mkt_slipped) if d == "LONG" else (sl > mkt_slipped)
127
+ s2 = simulate(post, mkt_slipped, tp2, sl, d) if sl_ok else {"outcome": "SL_ALREADY_BREACHED"}
128
+ adj_rr = round(abs(tp2 - mkt) / abs(mkt - sl), 3) if abs(mkt - sl) > 0 else None
129
+ return {"mkt": mkt, "li": li, "move60m_pct": mv60, "adj_rr": adj_rr, "s1": s1, "s2": s2}
130
+
131
+ # ── aggregate report ──────────────────────────────────────────────────────
132
+ def bucket(rows, keyf, buckets):
133
+ out = {}
134
+ for lo, hi, name in buckets:
135
+ sel = [r for r in rows if r.get(keyf) is not None and lo <= r[keyf] < hi]
136
+ wins = [r for r in rows if r in sel and r["s2_outcome"] == "WIN"]
137
+ out[name] = (len(sel), round(len(wins)/len(sel)*100,1) if sel else None,
138
+ round(sum(r["s2_r"] for r in sel), 2) if sel else None)
139
+ return out
140
+
141
+ def write_report(rows, path="signal_report.md"):
142
+ n = len(rows)
143
+ def stats(prefix):
144
+ done = [r for r in rows if r[f"{prefix}_outcome"] in ("WIN", "LOSS")]
145
+ wins = [r for r in done if r[f"{prefix}_outcome"] == "WIN"]
146
+ tot_r = sum(r[f"{prefix}_r"] for r in rows if isinstance(r[f"{prefix}_r"], float))
147
+ return len(done), len(wins), (len(wins)/len(done)*100 if done else 0), tot_r
148
+ d1, w1, wr1, r1 = stats("s1"); d2, w2, wr2, r2 = stats("s2")
149
+ li_b = bucket(rows, "li", [(-9, .3, "LI<0.3"), (.3, .7, "0.3-0.7"), (.7, 1.0, "0.7-1.0"), (1.0, 99, ">1.0")])
150
+ mv_b = bucket(rows, "move60m_pct", [(-99, 0, "neg 60m"), (0, 1, "0-1%"), (1, 3, "1-3%"), (3, 99, ">3%")])
151
+ mfes = sorted(r["s2_mfe"] for r in rows if isinstance(r.get("s2_mfe"), float))
152
+ med_mfe = mfes[len(mfes)//2] if mfes else None
153
+ heartbreak = sum(1 for r in rows if r["s2_outcome"] == "LOSS" and isinstance(r.get("s2_mfe"), float)
154
+ and r.get("tp2_dist_r") and r["s2_mfe"] >= 0.75 * r["tp2_dist_r"])
155
+ lines = [
156
+ "# Signal Replay Report", f"_alerts analyzed: {n}_", "",
157
+ f"## S1 as-alerted (entry→TP1): resolved {d1}, wins {w1}, WR {wr1:.1f}%, total {r1:+.2f}R",
158
+ f"## S2 Utkarsh-style (market→TP2): resolved {d2}, wins {w2}, WR {wr2:.1f}%, total {r2:+.2f}R",
159
+ f"never-filled S1: {sum(1 for r in rows if r['s1_outcome']=='NEVER_FILLED')}"
160
+ f" · expired S2: {sum(1 for r in rows if r['s2_outcome']=='EXPIRED')}", "",
161
+ "## Lateness buckets (n, S2 WR%, ΣR): " + json.dumps(li_b),
162
+ "## 60m-momentum buckets: " + json.dumps(mv_b),
163
+ f"## TP quality: median MFE {med_mfe}R · heartbreak (≥75% of way to TP2 then LOSS): {heartbreak}/{n}",
164
+ f"## Shakeouts (SL hit but MFE later? see per-row mfe after loss): inspect replay_results.csv", "",
165
+ "### Rule-change inputs (R1-R5): pick LI cutoff & adj_RR from buckets above; "
166
+ "TP policy from MFE vs TP distances; SL from MAE distribution of winners.",
167
+ ]
168
+ open(path, "w").write("\n".join(lines))
169
+ print("\n".join(lines))
170
+
171
+ # ── selftest (no network) ─────────────────────────────────────────────────
172
+ def selftest():
173
+ C = lambda o,h,l,c: {"t":0,"o":o,"h":h,"l":l,"c":c}
174
+ # LONG entry100 sl95 tp110 : TP path
175
+ r = simulate([C(100,104,99,103), C(103,111,102,110)], 100, 110, 95, "LONG")
176
+ assert r["outcome"]=="WIN" and abs(r["r_net"]-(2.0-(100+110)*FEE/5))<1e-6, r
177
+ # SL path
178
+ r = simulate([C(100,101,94,95)], 100, 110, 95, "LONG"); assert r["outcome"]=="LOSS", r
179
+ # both in one candle → LOSS
180
+ r = simulate([C(100,111,94,100)], 100, 110, 95, "LONG"); assert r["outcome"]=="LOSS", r
181
+ # expired
182
+ r = simulate([C(100,101,99,100)]*3, 100, 110, 95, "LONG"); assert r["outcome"]=="EXPIRED", r
183
+ # SHORT win + MFE/MAE
184
+ r = simulate([C(100,102,88,90)], 100, 90, 105, "SHORT")
185
+ assert r["outcome"]=="WIN" and r["mae_r"]==0.4 and r["mfe_r"]>=2.0, r
186
+ # lateness: mkt105 entry100 tp1 110 → 0.5 ; short mirror
187
+ assert lateness(105,100,110,"LONG")==0.5 and lateness(95,100,90,"SHORT")==0.5
188
+ print("SELFTEST OK — outcome engine, fees, MFE/MAE, lateness all correct")
189
+
190
+ def main():
191
+ if "--selftest" in sys.argv: return selftest()
192
+ if len(sys.argv) < 2: sys.exit("usage: replay_signals.py alerts.csv | --selftest")
193
+ alerts = list(csv.DictReader(open(sys.argv[1])))
194
+ print(f"replaying {len(alerts)} alerts…")
195
+ out = []
196
+ for i, a in enumerate(alerts):
197
+ try:
198
+ r = replay(a)
199
+ except Exception as e:
200
+ r = {"error": f"{type(e).__name__}: {e}"}
201
+ row = {"iso": a["iso"], "symbol": a["symbol"], "direction": a["direction"],
202
+ "conf": a["conf"], "entry": a["entry"], "sl": a["sl"], "tp1": a["tp1"], "tp2": a["tp2"],
203
+ "mkt": r.get("mkt"), "li": r.get("li"), "move60m_pct": r.get("move60m_pct"),
204
+ "adj_rr": r.get("adj_rr"),
205
+ "s1_outcome": r.get("s1", {}).get("outcome", r.get("error", "ERR")),
206
+ "s1_r": r.get("s1", {}).get("r_net", ""),
207
+ "s2_outcome": r.get("s2", {}).get("outcome", r.get("error", "ERR")),
208
+ "s2_r": r.get("s2", {}).get("r_net", ""),
209
+ "s2_mfe": r.get("s2", {}).get("mfe_r", ""), "s2_mae": r.get("s2", {}).get("mae_r", ""),
210
+ "s2_bars": r.get("s2", {}).get("bars", "")}
211
+ try:
212
+ e2 = float(row["mkt"]); slf = float(a["sl"]); tp2 = float(a["tp2"] or a["tp1"])
213
+ row["tp2_dist_r"] = round(abs(tp2 - e2) / abs(e2 - slf), 3)
214
+ except Exception:
215
+ row["tp2_dist_r"] = ""
216
+ out.append(row)
217
+ print(f"[{i+1}/{len(alerts)}] {a['symbol']} {a['direction']} S2={row['s2_outcome']} {row['s2_r']}R LI={row['li']}")
218
+ with open("replay_results.csv", "w", newline="") as f:
219
+ w = csv.DictWriter(f, fieldnames=list(out[0].keys())); w.writeheader(); w.writerows(out)
220
+ # numeric coercion for report
221
+ for r in out:
222
+ for k in ("s1_r", "s2_r", "s2_mfe", "li", "move60m_pct", "tp2_dist_r"):
223
+ try: r[k] = float(r[k])
224
+ except Exception: r[k] = None
225
+ write_report(out)
226
+ print("\nwrote replay_results.csv + signal_report.md")
227
+
228
+ if __name__ == "__main__":
229
+ main()
analysis/signal-analysis-plan.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Workstream 1 — Signal Performance Analysis Plan
2
+ _2026-07-11 · execution-ready · provider-agnostic. Goal: measure whether the ≥8.8 alerts make money under Utkarsh's REAL trading style, quantify lateness and TP quality, and produce rule changes for the automation._
3
+
4
+ ## 1. THE THREE QUESTIONS THIS MUST ANSWER
5
+ Q1. Of the last ~50 alerts, how many would have been profitable if we entered AT MARKET the moment the alert arrived (a) targeting TP1 as given, (b) targeting TP2 as given (Utkarsh's real style)?
6
+ Q2. How often was the move "already captured" at alert time (price already run toward/past TP1)? → the LATENESS problem.
7
+ Q3. Are TPs/SLs placed correctly? (TP set where price never reaches → market reverses; SL too tight → shaken out before the move) → measured via MFE/MAE, not opinion.
8
+
9
+ ## 2. DATA ACQUISITION (blocker — needs Utkarsh, ~3 minutes)
10
+ The Space keeps NO alert history (/tmp resets on every restart/deploy). The only complete record is the Telegram chat.
11
+ - Utkarsh: Telegram DESKTOP app → open the bot chat → ⋮ → Export chat history → Format: **JSON** (machine-readable; HTML also parseable as fallback) → include messages only, no media → gives `result.json`.
12
+ - Upload the file to the working session.
13
+ Alert message shape to parse (from telegram_alert.py build_message): first line `{emoji} {SYM} {DIRECTION} · {conf}/10`; lines with `Entry`, `SL`, `TP1 … R/R`, `TP2`, `TP3`; timestamp = Telegram message `date` (ISO, convert to UTC epoch). Ignore heartbeats ("Trade Copilot alive"), test messages, skip-notices.
14
+ Parser spec: `parse_alerts.py` → CSV/JSON rows: {ts_utc, symbol, direction, conf, entry, sl, tp1, tp2, tp3}. Dedup: same symbol+direction within 4h keep first (mirrors alert dedup). Take the most recent 50 (or all, if fewer).
15
+
16
+ ## 3. MARKET DATA FOR REPLAY
17
+ - Source: BingX public klines `/openApi/swap/v3/quote/klines` — **1m interval** from alert_ts forward until outcome or +7 days cap; plus 15m for context. Pagination: 500/call with startTime (pattern already exists in backtest.py `_fetch_klines_paginated`).
18
+ - ⚠ VERIFY at build time: how far back BingX serves 1m candles (if <30 days, older alerts fall back to 5m replay; note precision loss per alert). Binance fallback klines OK from a local machine (geo-block applies to HF hosts, not Utkarsh's Mac — analysis can run locally).
19
+ - Entry price for "market entry" simulation = open of the first 1m candle AFTER alert_ts (+1 candle to model reaction delay; also compute a +60s slippage variant). Apply taker fee 0.05% side + 0.05% close + 0.05% adverse slippage.
20
+
21
+ ## 4. REPLAY ENGINE (`replay_signals.py`) — per alert, compute BOTH scenarios
22
+ S1 "as-alerted": entry=alert entry price (only if price returns to it within 12h — else mark NEVER_FILLED), TP=TP1, SL=SL.
23
+ S2 "Utkarsh-style": entry=market at alert time, TP=TP2 (unchanged from alert), SL=SL (unchanged).
24
+ Outcome rules (conservative, mirrors signal_log): walk 1m candles; TP touched first → WIN; SL touched first → LOSS; both in same candle → LOSS; neither in 7 days → EXPIRED (record final R). Record: outcome, bars_to_outcome, hours_to_outcome.
25
+ Per-alert derived metrics:
26
+ - **Lateness Index LI** = (market_price_at_alert − alert_entry) / (tp1 − alert_entry), direction-signed. LI≥1 = TP1 already gone at alert time. Also record `move_60m_before` = % change in the 60m before alert (momentum context).
27
+ - **MFE / MAE** (from S2 market entry, in R units where 1R = |entry−SL|): max favorable excursion and max adverse excursion before outcome. These are the TP/SL truth-tellers:
28
+ * If median MFE ≥ TP2 distance but win rate low → TPs fine, exits fine — look elsewhere.
29
+ * If median MFE lands between TP1 and TP2 → TP2 is structurally too far for late entries → rule change: dynamic TP (e.g., TP = min(TP2, entry + 0.8×median-MFE-multiple)).
30
+ * If MAE frequently ~0.8–1.0R on eventual winners → SL too tight → widen SL or reduce leverage.
31
+ - **adj_RR at alert** = |tp2−market| / |market−sl| (what the automation's drift gate would have seen).
32
+
33
+ ## 5. AGGREGATE REPORT (`signal_report.md` + CSV)
34
+ - Headline: S1 vs S2 win rates, avg R, total R, net $ on $10 all-in at 4× and 6× (fees+funding included), max drawdown sequence, expectancy/trade.
35
+ - Lateness: LI distribution (median, % of alerts with LI>0.5, >0.7, >1.0); win rate bucketed by LI (LI<0.3 vs 0.3-0.7 vs >0.7) → directly tests "we arrive after the move".
36
+ - Momentum: win rate bucketed by move_60m_before (did spike-chasing alerts lose?).
37
+ - TP quality: MFE distribution vs TP1/TP2 distances; % trades where price came within 0.25R of TP2 then reversed to SL ("heartbreak rate").
38
+ - SL quality: MAE distribution on winners; shakeout rate (SL hit, then price reaches TP2 within original window).
39
+ - By confidence band (8.8-9.0 vs 9.0+), by direction, by HMM state if recoverable, by symbol.
40
+ - Honest caveats section: n≈50 → binomial 95% CI is ±~14pp on win rate; no regime diversity; survivorship of a single month. NO strategy change ships on this sample alone without the paper-trading confirmation phase.
41
+
42
+ ## 6. DECISION RULES THE REPORT MUST OUTPUT (feeds automation-architecture-v2)
43
+ R1. Momentum/lateness gate calibration: the LI threshold (default 0.70) and adj_RR minimum (default 1.2) get replaced by the empirically best cutoffs from §5 buckets.
44
+ R2. TP policy: keep TP2-as-given vs dynamic-MFE-based TP vs TP1.5 (midpoint) — pick by expectancy comparison.
45
+ R3. SL policy: keep vs widen (e.g., 1.5×ATR) with leverage reduced to keep $-risk equal.
46
+ R4. Threshold: does 9.0+ outperform 8.8+ enough to justify fewer trades?
47
+ R5. Skip-list: symbols/regimes with systematically bad replay results.
48
+
49
+ ## 7. GOING FORWARD (so this analysis never needs Telegram export again)
50
+ Add `alert_ledger.py` to the Space at next deploy: every alert (and every skip) appended to a persistent ledger (Cloudflare KV via existing relay, or HF Dataset) with full card snapshot at alert time. The paper trader (Workstream 2) reads/writes the same ledger. This is a REQUIRED precursor to automation regardless of analysis outcome.
51
+
52
+ ## 8. EXECUTION CHECKLIST
53
+ [ ] Utkarsh exports Telegram chat JSON → upload
54
+ [ ] Build parse_alerts.py → alerts.csv (~50 rows)
55
+ [ ] Build replay_signals.py (klines fetch + S1/S2 + metrics) — run LOCALLY (Binance fallback allowed locally)
56
+ [ ] Generate signal_report.md + buckets + decision rules R1-R5
57
+ [ ] Review with Utkarsh → lock rule changes into automation config
58
+ [ ] Ship alert_ledger.py with next deploy
static/index.html CHANGED
@@ -1588,6 +1588,21 @@ nav {
1588
  .tag-grade.gA { color:var(--profit, var(--green)); background:var(--mints, rgba(61,220,151,0.11)); border:1px solid rgba(61,220,151,0.3); }
1589
  .tag-grade.gB { color:var(--warn, var(--amber)); background:var(--ambers, rgba(245,181,42,0.12)); border:1px solid rgba(245,181,42,0.3); }
1590
  .tag-grade.gC { color:var(--loss, var(--red)); background:var(--reds, rgba(255,107,122,0.10)); border:1px solid rgba(255,107,122,0.3); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1591
  @media (max-width:900px) {
1592
  .featured-layout { grid-template-columns:1fr; }
1593
  .featured-left { flex-direction:row; flex-wrap:wrap; justify-content:center; text-align:left; }
@@ -3737,11 +3752,28 @@ function buildCard(c, account, risk, meta) {
3737
  <span class="rs-exp">▾</span>
3738
  </div>` : '';
3739
 
3740
- // ── Featured ring + grade tag — shown only on the #1 ranked "Top Setup" card ──
 
 
 
 
 
3741
  const ringCirc = 226.2; // 2*pi*36
3742
  const gradeLetter = conf>=7 ? 'A' : conf>=5 ? 'B' : 'C';
3743
  const gradeCssCls = isVetoed ? 'gC' : gradeLetter==='A' ? 'gA' : gradeLetter==='B' ? 'gB' : 'gC';
3744
- const gradeTagLabel = isVetoed ? 'VETOED · NO TRADE' : `GRADE ${gradeLetter} · TRADEABLE`;
 
 
 
 
 
 
 
 
 
 
 
 
3745
  const featuredRingWrapHTML = featured ? `
3746
  <div class="conf-ring-wrap">
3747
  <svg viewBox="0 0 84 84">
@@ -3831,6 +3863,7 @@ function buildCard(c, account, risk, meta) {
3831
  <div class="featured-left">
3832
  ${featuredRingWrapHTML}
3833
  <span class="tag-grade ${gradeCssCls}">${gradeTagLabel}</span>
 
3834
  ${stateBadgesSimpleHTML}
3835
  <div class="panel">${evTitleHTML}</div>
3836
  </div>
 
1588
  .tag-grade.gA { color:var(--profit, var(--green)); background:var(--mints, rgba(61,220,151,0.11)); border:1px solid rgba(61,220,151,0.3); }
1589
  .tag-grade.gB { color:var(--warn, var(--amber)); background:var(--ambers, rgba(245,181,42,0.12)); border:1px solid rgba(245,181,42,0.3); }
1590
  .tag-grade.gC { color:var(--loss, var(--red)); background:var(--reds, rgba(255,107,122,0.10)); border:1px solid rgba(255,107,122,0.3); }
1591
+
1592
+ /* ── Real Price Action confluence grade chip — sits beside/below .tag-grade
1593
+ in the featured rail. Independent signal from confidence: derived from
1594
+ chart patterns + candlesticks + order blocks (confluence.py), not the
1595
+ AI confidence score. ── */
1596
+ .pa-grade-chip {
1597
+ display:inline-flex; align-items:center;
1598
+ font-family:var(--font-display); font-weight:700; font-size:11px;
1599
+ letter-spacing:0.06em; padding:5px 12px; border-radius:9px;
1600
+ }
1601
+ .pa-grade-chip.pgA { color:var(--mint); background:var(--mints); border:1px solid rgba(61,220,151,0.3); }
1602
+ .pa-grade-chip.pgB { color:var(--cyan); background:var(--cyans); border:1px solid rgba(76,201,240,0.3); }
1603
+ .pa-grade-chip.pgC { color:var(--amber); background:var(--ambers); border:1px solid rgba(245,181,42,0.3); }
1604
+ .pa-grade-chip.pgD { color:var(--red); background:var(--reds); border:1px solid rgba(255,107,122,0.3); }
1605
+ .pa-grade-chip.pgNA { color:var(--t3); background:var(--glass2); border:1px solid var(--gb); }
1606
  @media (max-width:900px) {
1607
  .featured-layout { grid-template-columns:1fr; }
1608
  .featured-left { flex-direction:row; flex-wrap:wrap; justify-content:center; text-align:left; }
 
3752
  <span class="rs-exp">▾</span>
3753
  </div>` : '';
3754
 
3755
+ // ── Featured ring + tier tag — shown only on the #1 ranked "Top Setup" card.
3756
+ // "TIER" here is derived from the AI confidence score (0–10) — it is NOT
3757
+ // a pattern-based grade. The real price-action confluence grade (from
3758
+ // chart patterns + candlesticks + order blocks, computed in confluence.py)
3759
+ // is shown separately via the "PA GRADE" chip below, sourced directly
3760
+ // from card.price_action.confluence_grade. The two can disagree. ──
3761
  const ringCirc = 226.2; // 2*pi*36
3762
  const gradeLetter = conf>=7 ? 'A' : conf>=5 ? 'B' : 'C';
3763
  const gradeCssCls = isVetoed ? 'gC' : gradeLetter==='A' ? 'gA' : gradeLetter==='B' ? 'gB' : 'gC';
3764
+ const gradeTagLabel = isVetoed ? 'VETOED · NO TRADE' : `TIER ${gradeLetter} · TRADEABLE`;
3765
+ // ── Real Price Action confluence grade (pattern-based, independent of confidence) ──
3766
+ const paGradeRaw = (c.pa_available && c.price_action?.confluence_grade) ? c.price_action.confluence_grade : null;
3767
+ const paScoreRaw = c.price_action?.confluence_score;
3768
+ const paChipCls = paGradeRaw === 'A+' || paGradeRaw === 'A' ? 'pgA'
3769
+ : paGradeRaw === 'B' ? 'pgB'
3770
+ : paGradeRaw === 'C' ? 'pgC'
3771
+ : paGradeRaw === 'D' ? 'pgD'
3772
+ : 'pgNA';
3773
+ const paChipLabel = paGradeRaw
3774
+ ? `PA GRADE ${paGradeRaw}${paScoreRaw!=null?` · ${Math.round(paScoreRaw)}`:''}`
3775
+ : 'PA · N/A';
3776
+ const paGradeChipHTML = `<span class="pa-grade-chip ${paChipCls}">${paChipLabel}</span>`;
3777
  const featuredRingWrapHTML = featured ? `
3778
  <div class="conf-ring-wrap">
3779
  <svg viewBox="0 0 84 84">
 
3863
  <div class="featured-left">
3864
  ${featuredRingWrapHTML}
3865
  <span class="tag-grade ${gradeCssCls}">${gradeTagLabel}</span>
3866
+ ${paGradeChipHTML}
3867
  ${stateBadgesSimpleHTML}
3868
  <div class="panel">${evTitleHTML}</div>
3869
  </div>