File size: 31,585 Bytes
61b1f06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01393e2
 
 
 
 
 
 
d6465e2
 
 
 
 
 
 
3afa8ba
 
 
 
61b1f06
 
3afa8ba
 
 
 
 
 
 
 
61b1f06
 
 
 
 
 
 
 
d39b2ef
61b1f06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07952e6
 
61b1f06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07952e6
 
 
 
 
 
 
 
 
61b1f06
 
 
 
 
07952e6
d6465e2
61b1f06
d6465e2
61b1f06
 
 
 
 
 
 
 
 
07952e6
61b1f06
07952e6
 
 
 
19c5a09
07952e6
 
 
 
 
 
 
 
 
 
e825323
07952e6
 
 
 
 
 
 
 
 
 
 
 
e825323
 
07952e6
 
 
19c5a09
e825323
61b1f06
3afa8ba
 
 
 
 
61b1f06
 
 
 
 
 
07952e6
61b1f06
07952e6
 
 
 
 
 
 
 
 
 
 
 
61b1f06
07952e6
61b1f06
 
 
 
 
 
07952e6
61b1f06
 
07952e6
61b1f06
 
 
 
 
07952e6
61b1f06
 
 
 
 
 
 
d6465e2
 
 
 
61b1f06
d6465e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61b1f06
d6465e2
 
61b1f06
 
 
 
 
 
 
 
 
07952e6
 
61b1f06
 
 
d6465e2
61b1f06
 
 
 
 
 
 
d6465e2
61b1f06
 
 
3afa8ba
 
07952e6
19c5a09
01393e2
d6465e2
ee7b200
d6465e2
 
 
 
 
 
 
 
 
 
 
 
 
01393e2
 
 
 
 
 
 
 
 
 
61b1f06
 
 
 
07952e6
 
 
 
200d067
 
07952e6
 
 
 
 
 
 
61b1f06
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
<!doctype html><html lang='en'><head><meta charset='utf-8'/>
<meta name='viewport' content='width=device-width,initial-scale=1'/>
<title>Trade History · __NAME__ v__VERSION__</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;500;600;700;800&family=JetBrains+Mono:wght@500;600&display=swap');
:root{--bg:#070b18;--panel:#0e1730;--panel2:#121d3c;--line:#21345f;--txt:#eaf1ff;--muted:#8ba6d6;--cyan:#36e2f5;--pink:#fb74bc;--green:#5ce39e;--red:#ff7a90;--amber:#ffcb52;--vio:#8e9dff;--mono:'JetBrains Mono',ui-monospace,Menlo,monospace}
*{box-sizing:border-box}
body{margin:0;color:var(--txt);font-family:'Sora',Segoe UI,Arial,sans-serif;background:#05070f;overflow-x:hidden}
body:before{content:'';position:fixed;inset:0;z-index:-2;background:radial-gradient(1100px 620px at 12% -8%,rgba(142,157,255,.16),transparent 60%),radial-gradient(900px 560px at 100% 0%,rgba(54,226,245,.14),transparent 55%),linear-gradient(180deg,#070b18,#04060d)}
.wrap{max-width:1480px;margin:0 auto;padding:16px 16px 48px}
.thead{display:flex;align-items:center;gap:14px;flex-wrap:wrap;padding:14px 16px;border:1px solid #34306f;border-radius:18px;background:linear-gradient(120deg,rgba(20,18,46,.92),rgba(18,28,62,.86));box-shadow:0 16px 44px rgba(0,0,0,.45)}
.tlogo{width:50px;height:50px;min-width:50px;border-radius:14px;border:1px solid #5b54a8;background:radial-gradient(circle at 50% 50%,#2a2666,#14123a);display:flex;align-items:center;justify-content:center}
.tlogo svg{width:34px;height:34px}
.thead .tt{display:flex;flex-direction:column;gap:2px;min-width:0}
.tt h1{margin:0;font-size:20px;font-weight:800;background:linear-gradient(90deg,#eaf4ff,#b6a8ff 70%);-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent}
.tt .ts{color:#a9b6ee;font-size:11.5px}
.back{margin-left:auto;display:inline-flex;align-items:center;gap:7px;padding:8px 14px;border-radius:999px;border:1px solid #3a5fa8;background:rgba(11,26,58,.8);color:#cfe0ff;font-size:12.5px;font-weight:600;text-decoration:none;white-space:nowrap}
.back:hover{background:#14306a;border-color:#5fe6f9}
.bar{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-top:14px}
.filters{display:flex;gap:6px;flex-wrap:wrap}
.fbtn{padding:6px 11px;border-radius:999px;border:1px solid #2c4d8c;background:rgba(11,26,58,.6);color:#bcd4f9;font-size:11.5px;font-weight:600;cursor:pointer;font-family:var(--mono)}
.fbtn:hover{background:#11295e}
.fbtn.on{background:linear-gradient(90deg,rgba(28,76,255,.2),rgba(142,157,255,.2));border-color:#8e9dff;color:#fff;box-shadow:0 0 0 1px rgba(142,157,255,.4)}
.search{margin-left:auto;display:flex;align-items:center;gap:7px;padding:6px 12px;border-radius:999px;border:1px solid #2c4d8c;background:rgba(7,15,39,.7)}
.search input{background:transparent;border:0;outline:0;color:var(--txt);font-size:12.5px;font-family:var(--mono);width:150px}
.search svg{width:14px;height:14px;opacity:.7}
.grid{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:10px;margin-top:14px}
.card{background:linear-gradient(180deg,var(--panel2),var(--panel));border:1px solid var(--line);border-radius:14px;padding:12px 13px;box-shadow:0 10px 30px rgba(0,0,0,.3)}
.m{position:relative;overflow:hidden}
.m:before{content:'';position:absolute;left:0;top:0;bottom:0;width:3px;background:var(--vio);opacity:.85}
.m.win:before{background:var(--green)} .m.loss:before{background:var(--red)} .m.be:before{background:var(--amber)} .m.cy:before{background:var(--cyan)}
.k{font-size:10px;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}
.v{font-size:22px;font-weight:800;margin-top:3px;font-family:var(--mono)}
.v.g{color:var(--green)} .v.r{color:var(--red)} .v.a{color:var(--amber)} .v.c{color:var(--cyan)} .v.vi{color:var(--vio)}
.subt{font-size:10px;color:var(--muted);margin-top:2px}
.charts{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:14px}
.chart h3,.tablecard h3{margin:0 0 10px;font-size:14px;font-weight:700;display:flex;align-items:center;gap:8px}
.chart .body{display:flex;align-items:center;justify-content:center;min-height:210px}
.legend{display:flex;flex-direction:column;gap:7px;font-size:12px;font-family:var(--mono)}
.legend .li{display:flex;align-items:center;gap:8px}
.legend .sw{width:11px;height:11px;border-radius:3px}
.donutwrap{display:flex;gap:18px;align-items:center;flex-wrap:wrap;justify-content:center}
.tablecard{margin-top:14px}
.box{border:1px solid #2a2655;border-radius:12px;background:rgba(14,12,38,.55);overflow:auto;max-height:540px}
table{width:100%;border-collapse:collapse;font-size:11.5px}
th,td{padding:7px 9px;border-bottom:1px solid #1d2a4d;text-align:left;white-space:nowrap}
td{font-family:var(--mono);color:#d6e6ff}
td:first-child,th:first-child{font-family:'Sora',sans-serif}
th{color:#c5ccff;position:sticky;top:0;background:#221d4a;font-weight:600;cursor:pointer;z-index:1}
tbody tr:hover{background:rgba(142,157,255,.06)}
.muted{color:var(--muted);font-family:'Sora',sans-serif;text-align:center;padding:22px}
a{color:#7af6ff;text-decoration:none} a:hover{text-decoration:underline}
.tag{display:inline-flex;padding:2px 8px;border-radius:999px;font-weight:700;font-size:10px;font-family:'Sora',sans-serif}
.win-t{color:#9bf5b2;background:rgba(29,185,84,.16);border:1px solid rgba(29,185,84,.45)}
.loss-t{color:#ff9cae;background:rgba(239,68,68,.16);border:1px solid rgba(239,68,68,.45)}
.be-t{color:#ffe39a;background:rgba(255,203,82,.16);border:1px solid rgba(255,203,82,.45)}
.long-t{color:#9bf5b2;background:rgba(29,185,84,.14);border:1px solid rgba(29,185,84,.4)}
.short-t{color:#ff9cae;background:rgba(239,68,68,.14);border:1px solid rgba(239,68,68,.4)}
/* v7.2 Trade Guardian conviction stamp (final post-entry verdict at close) */
.gv-strong{color:#062;background:#43e08a;border:1px solid #43e08a}
.gv-good{color:#062;background:#9be7b8;border:1px solid #9be7b8}
.gv-warn{color:#3a2a00;background:#ffce5c;border:1px solid #ffce5c}
.gv-bad{color:#3a1c00;background:#ff9d4d;border:1px solid #ff9d4d}
.gv-term{color:#fff;background:#ef4444;border:1px solid #ef4444}
.convsub{font-size:9.5px;color:#8ba6d6;font-family:var(--mono);margin-top:3px}
/* §23: Setup → Exit snapshot (entry grade → final Stage-5 verdict) */
.gpill{display:inline-flex;padding:2px 7px;border-radius:6px;font-weight:800;font-size:10px;font-family:'Sora',sans-serif}
.gp-a{color:#062;background:#43e08a;border:1px solid #43e08a}
.gp-b{color:#3a2a00;background:#ffce5c;border:1px solid #ffce5c}
.gp-c{color:#3a1c00;background:#ff9d4d;border:1px solid #ff9d4d}
.se-arrow{color:#7e8db5;margin:0 5px;font-weight:700}
.se-cell{display:inline-flex;align-items:center;flex-wrap:wrap;gap:2px;font-size:10.5px}
/* Symbol cell = dashed-underline chart link with the pair's logo (matches main page) */
.symlink{display:inline-flex;align-items:center;gap:6px;color:#d6e6ff;text-decoration:none;border-bottom:1px dashed rgba(159,200,255,.6);padding-bottom:1px}
.symlink:hover{border-bottom-color:#7af6ff;color:#bfeaff}
.symico{width:15px;height:15px;border-radius:50%;flex:none;background:#14123a;object-fit:cover}
@media(max-width:1100px){.grid{grid-template-columns:repeat(3,minmax(0,1fr))}.charts{grid-template-columns:1fr}.box{overflow-x:auto}table{min-width:760px}}
@media(max-width:560px){.grid{grid-template-columns:repeat(2,minmax(0,1fr))}.tt h1{font-size:16px}.wrap{padding:12px 10px 34px}.search{margin-left:0;width:100%}.search input{width:100%}}
/* Mobile header: keep logo + title + description as ONE compact block and drop the
   Return link onto its own full-width row so nothing overflows on small screens. */
@media(max-width:520px){
  .thead{gap:10px;padding:12px 13px}
  .tlogo{width:40px;height:40px;min-width:40px;border-radius:11px} .tlogo svg{width:27px;height:27px}
  .tt h1{font-size:15px} .tt .ts{font-size:10.5px;line-height:1.3}
  .back{margin-left:0;order:3;width:100%;justify-content:center;padding:9px 14px}
}
</style></head><body>
<div class='wrap'>
  <div class='thead'>
    <div class='tlogo'><svg viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'>
      <defs><linearGradient id='g' x1='0' y1='0' x2='1' y2='1'><stop offset='0' stop-color='#8e9dff'/><stop offset='1' stop-color='#5fe6f9'/></linearGradient></defs>
      <circle cx='50' cy='50' r='40' fill='none' stroke='url(#g)' stroke-width='3' stroke-dasharray='6 7' stroke-linecap='round'><animateTransform attributeName='transform' type='rotate' from='0 50 50' to='360 50 50' dur='14s' repeatCount='indefinite'/></circle>
      <polyline points='26,64 40,52 54,58 64,36 76,44' fill='none' stroke='#9bf5b2' stroke-width='3.4' stroke-linecap='round' stroke-linejoin='round'/>
      <circle cx='64' cy='36' r='3.6' fill='#5fe6f9'/></svg></div>
    <div class='tt'><h1>Trade History Dashboard</h1><div class='ts'>Performance Metrics And Records...</div></div>
    <a class='back' href='/'>← Return To Main Page</a>
  </div>

  <div class='bar'>
    <div class='filters' id='filters'></div>
    <div class='search'>
      <svg viewBox='0 0 24 24' fill='none' stroke='#9ec2ff' stroke-width='2'><circle cx='11' cy='11' r='7'/><path d='M21 21l-4.3-4.3' stroke-linecap='round'/></svg>
      <input id='q' placeholder='Search Pair…' autocomplete='off'/>
    </div>
  </div>

  <div class='grid'>
    <div class='card m cy'><div class='k'>Total Trades</div><div class='v c' id='m-total'>0</div><div class='subt' id='m-window'>All Time</div></div>
    <div class='card m win'><div class='k'>Win Rate</div><div class='v g' id='m-winrate'>0%</div><div class='subt' id='m-wl'>0W · 0L</div></div>
    <div class='card m'><div class='k'>Net Result (R)</div><div class='v vi' id='m-netr'>0.0R</div><div class='subt' id='m-avgr'>Avg 0.0R</div></div>
    <div class='card m cy'><div class='k'>Profit Factor</div><div class='v c' id='m-pf'>0.0</div><div class='subt'>Gross Win / Gross Loss</div></div>
    <div class='card m win'><div class='k'>TP Hits</div><div class='v g' id='m-tp'>0</div><div class='subt'>Structural Target Reached</div></div>
    <div class='card m be'><div class='k'>Break-Even</div><div class='v a' id='m-be'>0</div><div class='subt'>SL Moved To Entry</div></div>
    <div class='card m loss'><div class='k'>SL Hits</div><div class='v r' id='m-sl'>0</div><div class='subt'>Stopped Out</div></div>
    <div class='card m cy'><div class='k'>Most Traded</div><div class='v c' id='m-top' style='font-size:16px'>—</div><div class='subt' id='m-topn'>0 Trades</div></div>
    <div class='card m'><div class='k'>Long / Short</div><div class='v vi' id='m-ls' style='font-size:16px'>0 / 0</div><div class='subt' id='m-lsr'>—</div></div>
    <div class='card m win'><div class='k'>Best Trade</div><div class='v g' id='m-best'>0.0R</div><div class='subt' id='m-bestp'>—</div></div>
    <div class='card m loss'><div class='k'>Worst Trade</div><div class='v r' id='m-worst'>0.0R</div><div class='subt' id='m-worstp'>—</div></div>
    <div class='card m'><div class='k'>Avg Leverage</div><div class='v a' id='m-lev'>0x</div><div class='subt'>Across Trades</div></div>
  </div>

  <div class='charts'>
    <div class='card chart'><h3>Outcome Distribution</h3><div class='body'><div class='donutwrap'><div id='donut'></div><div class='legend' id='donut-legend'></div></div></div></div>
    <div class='card chart'><h3>Cumulative Result (R)</h3><div class='body' id='equity'></div></div>
    <div class='card chart'><h3>Long Vs Short Performance</h3><div class='body' id='ls-chart'></div></div>
    <div class='card chart'><h3>Top Pairs By Trade Count</h3><div class='body' id='pairs-chart'></div></div>
  </div>

  <div class='card tablecard' id='calib-card' style='display:none'>
    <h3>Feature Calibration <span class='tag' style='color:#cdd3ff;background:rgba(142,157,255,.16);border:1px solid rgba(142,157,255,.5)' id='calib-meta'>—</span></h3>
    <div class='ts' style='color:#8ba6d6;font-size:11px;margin:-4px 0 10px'>Per-Feature Hit Rate And Average Net R (Cost-Adjusted) — Which Reads Actually Win.</div>
    <div class='box' style='max-height:360px'><table>
      <thead><tr><th data-c='feature'>Feature</th><th data-c='trades'>Trades</th><th data-c='hit_rate'>Hit Rate</th><th data-c='avg_net_r'>Avg Net R</th></tr></thead>
      <tbody id='calib-rows'></tbody>
    </table></div>
  </div>

  <div class='card tablecard'>
    <h3>Closed Trades <span class='tag' style='color:#cdd3ff;background:rgba(142,157,255,.16);border:1px solid rgba(142,157,255,.5)' id='rowcount'>0</span></h3>
    <div class='box'><table>
      <thead><tr>
        <th data-s='closed_ts'>Closed Time</th><th data-s='symbol'>Pair</th><th data-s='direction'>Direction</th>
        <th data-s='entry'>Entry</th><th data-s='sl'>SL</th><th data-s='tp'>TP</th>
        <th data-s='leverage'>Leverage</th><th data-s='r'>Result (R)</th><th data-s='outcome'>Outcome</th><th data-s='g_drive'>Conviction</th><th data-s='grade_at_entry'>Setup → Exit</th><th>Chart</th>
      </tr></thead>
      <tbody id='rows'><tr><td colspan='12' class='muted'>Loading…</td></tr></tbody>
    </table></div>
  </div>
</div>
<script>
const WINDOWS=[['15m',900],['30m',1800],['1h',3600],['4h',14400],['12h',43200],['24h',86400],['3d',259200],['1w',604800],['1M',2592000],['3M',7776000],['1y',31536000],['All',0]];
let ALL=[],FILT=[],WIN=0,Q='',SORT='closed_ts',DIR=-1;
function esc(v){return String(v==null?'-':v).replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;');}
function num(v){const n=parseFloat(v);return isNaN(n)?null:n;}
function localTime(s){if(!s||s==='-')return '-';const d=new Date(String(s).replace(' UTC','Z').replace(' ','T'));return isNaN(d.getTime())?s:d.toLocaleString(undefined,{month:'short',day:'2-digit',hour:'2-digit',minute:'2-digit'});}
function cls(o){const t=String(o||'').toLowerCase();if(t.includes('tp'))return 'win';if(t.includes('break')||t==='be')return 'be';if(t.includes('sl')||t.includes('stop'))return 'loss';return 'na';}
function outLabel(o){let t=String(o||'-').replaceAll('_',' ');t=t.charAt(0).toUpperCase()+t.slice(1).toLowerCase();return t.replaceAll('Tp1','TP1').replaceAll('Tp2','TP2').replaceAll('Sl','SL').replaceAll('Be','BE').replaceAll('Tp','TP');}
// v7.5: replicate the engine's _pfmt magnitude fallback so Trade History shows the SAME
// truncated price precision as the main dashboard / Telegram (the /api/trades payload
// carries RAW floats, unlike /api/state which is pre-formatted server-side).
function fmtPx(v){const x=num(v);if(x===null)return esc(v==null?'-':v);const ax=Math.abs(x);let dec=ax>=100?2:ax>=1?4:ax>=0.01?6:8;let s=x.toFixed(dec);if(s.indexOf('.')>=0)s=s.replace(/0+$/,'').replace(/\.$/,'');return s||'0';}
function rOf(t){
  // v7.5 WS-8.1: prefer the cost-adjusted NET R (fees + funding + slippage) when the row
  // carries it — that is the honest result and the primary metric. Legacy rows with no
  // net_r fall through to the gross-from-levels computation below.
  if(t.net_r!==undefined&&t.net_r!==null&&t.net_r!==''){const n=num(t.net_r);if(n!==null)return n;}
  return grossOf(t);}
function grossOf(t){
  // v7.5: ONE structural TP. New rows carry `tp` (tp1/tp2 NULL); legacy rows (pre-v7.5)
  // carry the old tp1/tp2 split. Branch on which is present so old history still renders.
  if(t.gross_r!==undefined&&t.gross_r!==null&&t.gross_r!==''){const n=num(t.gross_r);if(n!==null)return n;}
  const e=num(t.entry),sl=num(t.sl),tp=num(t.tp);
  const risk=(e!==null&&sl!==null)?Math.abs(e-sl):0;
  const o=String(t.outcome||'').toLowerCase();
  if(tp!==null){
    // Single-TP: TP hit = +R (full structural target); break-even = 0R; SL = -1R.
    const r=(risk>0)?Math.abs(tp-e)/risk:0;
    if(o.includes('tp')) return r;
    if(o.includes('break')||o==='be') return 0;
    if(o.includes('sl')||o.includes('stop')) return -1;
    if(t.realized_rr!==undefined&&t.realized_rr!==null&&t.realized_rr!==''){const rr=num(t.realized_rr);if(rr!==null)return rr;}
    return null;
  }
  // Legacy 2-TP rows: TP1 was a 50% profit checkpoint (+0.5*R1), TP2 banks the runner too.
  const tp1=num(t.tp1),tp2=num(t.tp2);
  const r1=(risk>0&&tp1!==null)?Math.abs(tp1-e)/risk:0;
  const r2=(risk>0&&tp2!==null)?Math.abs(tp2-e)/risk:0;
  if(o.includes('tp2')) return 0.5*r1+0.5*r2;
  if(o.includes('break')||o.includes('tp1')) return 0.5*r1;
  if(o.includes('sl')||o.includes('stop')) return -1;
  if(t.realized_rr!==undefined&&t.realized_rr!==null&&t.realized_rr!==''){const rr=num(t.realized_rr);if(rr!==null)return rr;}
  return null;}
function normDir(d){const x=String(d||'').toUpperCase();if(x==='LONG'||x==='BULLISH')return 'LONG';if(x==='SHORT'||x==='BEARISH')return 'SHORT';return '-';}
// Pair logos (cached server-side in /data, fetched once here) + dashed chart-link cell.
window.ICONS={};
fetch('/api/icons',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(j=>{if(j&&j.icons)window.ICONS=j.icons;}).catch(()=>{});
function iconImg(sym){const base=String(sym||'').split('_')[0].toUpperCase();const u=window.ICONS[base];return u?("<img class='symico' src='"+esc(u)+"' loading='lazy' alt='' onerror=\"this.style.display='none'\"/>"):"";}
function symCell(sym,href){return "<a class='symlink' href='"+href+"' target='_blank' title='Open chart'>"+iconImg(sym)+"<b>"+esc(sym)+"</b></a>";}

function buildFilters(){const f=document.getElementById('filters');f.innerHTML=WINDOWS.map(w=>"<button class='fbtn"+(w[1]===WIN?' on':'')+"' data-sec='"+w[1]+"'>"+w[0]+"</button>").join('');f.querySelectorAll('.fbtn').forEach(b=>b.onclick=()=>{WIN=+b.dataset.sec;buildFilters();apply();});}
function applyWindow(){const now=Date.now()/1000;return ALL.filter(t=>{const ct=num(t.closed_ts)||0;const okW=WIN===0||(now-ct)<=WIN;const okQ=!Q||String(t.symbol||'').toLowerCase().includes(Q);return okW&&okQ;});}
function apply(){FILT=applyWindow();const lab=WINDOWS.find(w=>w[1]===WIN);document.getElementById('m-window').textContent=lab?(lab[1]?('Window: '+lab[0]):'All Time'):'All Time';computeMetrics();renderCharts();renderTable();}

function computeMetrics(){
  const t=FILT;let win=0,loss=0,be=0,tp=0,sl=0,grossW=0,grossL=0,netR=0,grossSum=0,rCount=0,levSum=0,levN=0,longN=0,shortN=0,longR=0,shortR=0;
  let best={r:-1e9,p:'—'},worst={r:1e9,p:'—'};const pairCount={};
  t.forEach(x=>{const o=String(x.outcome||'').toLowerCase();const isNew=num(x.tp)!==null;
    // v7.5 single-TP: TP hit = win, SL = loss, break-even = neither (0R, shown on BE card).
    // Legacy 2-TP rows: reaching TP1/TP2 (incl. TP1-then-break-even) was a win; SL = loss.
    if(isNew){
      if(o.includes('tp')){win++;tp++;}
      else if(o.includes('break')||o==='be'){be++;}
      else if(o.includes('sl')||o.includes('stop')){loss++;sl++;}
    }else{
      if(o.includes('tp1')||o.includes('tp2')||o.includes('break')){win++;tp++;}
      else if(o.includes('sl')||o.includes('stop')){loss++;sl++;}
      if(o.includes('break'))be++;
    }
    const r=rOf(x);if(r!==null){netR+=r;rCount++;if(r>=0)grossW+=r;else grossL+=Math.abs(r);if(r>best.r)best={r:r,p:x.symbol};if(r<worst.r)worst={r:r,p:x.symbol};}
    const gr=grossOf(x);if(gr!==null)grossSum+=gr;
    const lv=num(x.leverage);if(lv!==null){levSum+=lv;levN++;}
    const d=normDir(x.direction);if(d==='LONG'){longN++;if(r!==null)longR+=r;}if(d==='SHORT'){shortN++;if(r!==null)shortR+=r;}
    pairCount[x.symbol]=(pairCount[x.symbol]||0)+1;});
  const set=(id,v)=>{const e=document.getElementById(id);if(e)e.textContent=v;};
  set('m-total',t.length);
  const wr=(win+loss)>0?Math.round(win/(win+loss)*100):0;set('m-winrate',wr+'%');set('m-wl',win+'W · '+loss+'L'+(be?(' · '+be+'BE'):''));
  set('m-netr',(netR>=0?'+':'')+netR.toFixed(1)+'R');set('m-avgr','Avg '+(rCount?(netR/rCount).toFixed(2):'0.0')+'R · Gross '+(grossSum>=0?'+':'')+grossSum.toFixed(1)+'R');
  const nr=document.getElementById('m-netr');if(nr)nr.className='v '+(netR>=0?'g':'r');
  set('m-pf',grossL>0?(grossW/grossL).toFixed(2):(grossW>0?'∞':'0.0'));
  set('m-tp',tp);set('m-be',be);set('m-sl',sl);
  const top=Object.entries(pairCount).sort((a,b)=>b[1]-a[1])[0];set('m-top',top?top[0]:'—');set('m-topn',top?(top[1]+' Trades'):'0 Trades');
  set('m-ls',longN+' / '+shortN);set('m-lsr',(longR>=0?'+':'')+longR.toFixed(1)+'R / '+(shortR>=0?'+':'')+shortR.toFixed(1)+'R');
  set('m-best',(best.r>-1e9?(best.r>=0?'+':'')+best.r.toFixed(1)+'R':'0.0R'));set('m-bestp',best.p||'—');
  set('m-worst',(worst.r<1e9?(worst.r>=0?'+':'')+worst.r.toFixed(1)+'R':'0.0R'));set('m-worstp',worst.p||'—');
  set('m-lev',levN?(levSum/levN).toFixed(0)+'x':'0x');
  window._cd={tp:tp,be:be,sl:sl,longN:longN,shortN:shortN,longR:longR,shortR:shortR,pairCount:pairCount};
}

function donut(seg,size){const cx=size/2,cy=size/2,r=size/2-9,c=2*Math.PI*r;const tot=seg.reduce((a,s)=>a+s.v,0);let off=0,parts='';
  if(tot<=0){return "<svg width='"+size+"' height='"+size+"'><circle cx='"+cx+"' cy='"+cy+"' r='"+r+"' fill='none' stroke='#23335c' stroke-width='14'/></svg>";}
  seg.forEach(s=>{if(s.v<=0)return;const len=s.v/tot*c;parts+="<circle cx='"+cx+"' cy='"+cy+"' r='"+r+"' fill='none' stroke='"+s.c+"' stroke-width='14' stroke-dasharray='"+len+" "+(c-len)+"' stroke-dashoffset='"+(-off)+"' transform='rotate(-90 "+cx+" "+cy+")'/>";off+=len;});
  return "<svg width='"+size+"' height='"+size+"'>"+parts+"<text x='"+cx+"' y='"+(cy-2)+"' text-anchor='middle' fill='#eaf1ff' font-size='22' font-weight='800' font-family='monospace'>"+tot+"</text><text x='"+cx+"' y='"+(cy+16)+"' text-anchor='middle' fill='#8ba6d6' font-size='10'>Trades</text></svg>";}

// §22: cumulative-R chart. pts = [{t:<closed_ts secs>, v:<cumulative R>}]. Renders a MONOTONE
// CUBIC (Fritsch-Carlson, overshoot-clamped so it never invents an R beyond a real data point)
// against a real TIME axis with date ticks + faint gridlines. Falls back to ordinal spacing if
// timestamps are missing. Same #equity container, same colours, area fill kept.
function lineChart(pts,w,h){if(!pts.length)return "<div class='muted'>No closed trades in this window.</div>";
  const padL=30,padR=14,padT=14,padB=22,iw=w-padL-padR,ih=h-padT-padB;
  const vs=pts.map(p=>p.v);const mn=Math.min(0,...vs),mx=Math.max(0,...vs);const rng=(mx-mn)||1;
  let tmin=pts[0].t||0,tmax=pts[pts.length-1].t||0;const useTime=tmax>tmin;
  const Y=v=>padT+ih-((v-mn)/rng)*ih;
  const PX=pts.map((p,i)=>useTime?(padL+(p.t-tmin)/(tmax-tmin)*iw):(padL+(pts.length>1?i/(pts.length-1)*iw:iw/2)));
  const PY=pts.map(p=>Y(p.v));const n=PX.length;
  let d="M"+PX[0].toFixed(1)+" "+PY[0].toFixed(1);
  if(n>1){const dx=[],delta=[];for(let i=0;i<n-1;i++){const hh=(PX[i+1]-PX[i])||1e-6;dx.push(hh);delta.push((PY[i+1]-PY[i])/hh);}
    const m=new Array(n);m[0]=delta[0];m[n-1]=delta[n-2];
    for(let i=1;i<n-1;i++){m[i]=(delta[i-1]*delta[i]<=0)?0:(delta[i-1]+delta[i])/2;}
    for(let i=0;i<n-1;i++){if(delta[i]===0){m[i]=0;m[i+1]=0;}else{const a=m[i]/delta[i],b=m[i+1]/delta[i],s=a*a+b*b;if(s>9){const tau=3/Math.sqrt(s);m[i]=tau*a*delta[i];m[i+1]=tau*b*delta[i];}}}
    for(let i=0;i<n-1;i++){const hh=dx[i],c1x=PX[i]+hh/3,c1y=PY[i]+m[i]*hh/3,c2x=PX[i+1]-hh/3,c2y=PY[i+1]-m[i+1]*hh/3;
      d+=" C"+c1x.toFixed(1)+" "+c1y.toFixed(1)+" "+c2x.toFixed(1)+" "+c2y.toFixed(1)+" "+PX[i+1].toFixed(1)+" "+PY[i+1].toFixed(1);}}
  const z=Y(0),last=vs[vs.length-1],col=last>=0?'#5ce39e':'#ff7a90';
  const area=d+" L"+PX[n-1].toFixed(1)+" "+z.toFixed(1)+" L"+PX[0].toFixed(1)+" "+z.toFixed(1)+" Z";
  let ticks='';if(useTime){const NT=4;for(let i=0;i<NT;i++){const tt=tmin+(tmax-tmin)*i/(NT-1),xx=padL+iw*i/(NT-1);
    const lbl=new Date(tt*1000).toLocaleDateString(undefined,{month:'short',day:'2-digit'});const anc=i===0?'start':(i===NT-1?'end':'middle');
    ticks+="<line x1='"+xx.toFixed(1)+"' y1='"+padT+"' x2='"+xx.toFixed(1)+"' y2='"+(padT+ih).toFixed(1)+"' stroke='#1e2c4d' stroke-width='1'/>";
    ticks+="<text x='"+xx.toFixed(1)+"' y='"+(h-6)+"' fill='#7e8db5' font-size='10' font-family='Sora' text-anchor='"+anc+"'>"+esc(lbl)+"</text>";}}
  return "<svg width='100%' viewBox='0 0 "+w+" "+h+"'><defs><linearGradient id='ar' x1='0' y1='0' x2='0' y2='1'><stop offset='0' stop-color='"+col+"' stop-opacity='.28'/><stop offset='1' stop-color='"+col+"' stop-opacity='0'/></linearGradient></defs>"+
    ticks+"<line x1='"+padL+"' y1='"+z.toFixed(1)+"' x2='"+(w-padR)+"' y2='"+z.toFixed(1)+"' stroke='#33436e' stroke-dasharray='4 4'/>"+
    "<path d='"+area+"' fill='url(#ar)'/><path d='"+d+"' fill='none' stroke='"+col+"' stroke-width='2.4' stroke-linejoin='round' stroke-linecap='round'/></svg>";}

function barChart(items,w,h,fmt){if(!items.length)return "<div class='muted'>No data.</div>";
  const pad=8,bh=22,gap=10,max=Math.max(...items.map(i=>Math.abs(i.v)))||1;const H=items.length*(bh+gap)+pad;
  let s="<svg width='100%' viewBox='0 0 "+w+" "+H+"'>";items.forEach((it,i)=>{const y=pad+i*(bh+gap);const bw=Math.abs(it.v)/max*(w-150);
    s+="<text x='4' y='"+(y+15)+"' fill='#cdd9f7' font-size='11' font-family='Sora'>"+esc(it.label)+"</text>";
    s+="<rect x='95' y='"+y+"' width='"+bw.toFixed(1)+"' height='"+bh+"' rx='5' fill='"+it.c+"'/>";
    s+="<text x='"+(100+bw).toFixed(1)+"' y='"+(y+15)+"' fill='#eaf1ff' font-size='11' font-family='monospace'>"+(fmt?fmt(it.v):it.v)+"</text>";});
  return s+"</svg>";}

function renderCharts(){const cd=window._cd||{tp:0,be:0,sl:0,longN:0,shortN:0,longR:0,shortR:0,pairCount:{}};
  const seg=[{label:'TP Hit',v:cd.tp,c:'#5ce39e'},{label:'Break-Even',v:cd.be,c:'#ffcb52'},{label:'SL Hit',v:cd.sl,c:'#ff7a90'}];
  document.getElementById('donut').innerHTML=donut(seg,180);
  const tot=seg.reduce((a,s)=>a+s.v,0)||1;
  document.getElementById('donut-legend').innerHTML=seg.map(s=>"<div class='li'><span class='sw' style='background:"+s.c+"'></span>"+s.label+" — <b>"+s.v+"</b> ("+Math.round(s.v/tot*100)+"%)</div>").join('');
  const sorted=[...FILT].sort((a,b)=>(num(a.closed_ts)||0)-(num(b.closed_ts)||0));let cum=0;const curve=[];sorted.forEach(x=>{const r=rOf(x);if(r!==null){cum+=r;curve.push({t:num(x.closed_ts)||0,v:cum});}});
  document.getElementById('equity').innerHTML=lineChart(curve,560,210);
  document.getElementById('ls-chart').innerHTML=barChart([{label:'Long',v:cd.longR,c:'#5ce39e'},{label:'Short',v:cd.shortR,c:'#ff7a90'}],560,0,v=>(v>=0?'+':'')+v.toFixed(1)+'R');
  const tp=Object.entries(cd.pairCount).sort((a,b)=>b[1]-a[1]).slice(0,6).map(e=>({label:e[0].replace('_USDT',''),v:e[1],c:'#8e9dff'}));
  document.getElementById('pairs-chart').innerHTML=barChart(tp,560,0,v=>v);}

function renderTable(){const tb=document.getElementById('rows');const rows=[...FILT].sort((a,b)=>{let av,bv;if(SORT==='r'){av=rOf(a)??-999;bv=rOf(b)??-999;}else{av=num(a[SORT]);bv=num(b[SORT]);if(av===null||bv===null){av=String(a[SORT]||'');bv=String(b[SORT]||'');return DIR*av.localeCompare(bv);}}return DIR*(av-bv);});
  document.getElementById('rowcount').textContent=rows.length;
  if(!rows.length){tb.innerHTML="<tr><td colspan='12' class='muted'>No closed trades match this filter.</td></tr>";return;}
  tb.innerHTML=rows.slice(0,500).map(x=>{const d=normDir(x.direction);const c=cls(x.outcome);const r=rOf(x);const rTxt=r===null?'—':((r>=0?'+':'')+r.toFixed(2)+'R');const rCol=r===null?'#8ba6d6':(r>=0?'#9bf5b2':'#ff9cae');
    const sym=String(x.symbol||'');const tv="https://www.tradingview.com/chart/?symbol=MEXC%3A"+sym.replaceAll('_','')+".P";
    const oc=c==='win'?'win-t':c==='loss'?'loss-t':c==='be'?'be-t':'';
    const tchart="/api/trade_chart.png?symbol="+encodeURIComponent(sym)+"&opened_ts="+encodeURIComponent(x.opened_ts||0);
    return "<tr><td>"+esc(localTime(x.closed_at||x.closed_ts))+"</td><td>"+symCell(sym,tchart)+"</td><td><span class='tag "+(d==='LONG'?'long-t':d==='SHORT'?'short-t':'')+"'>"+d+"</span></td>"+
      "<td>"+fmtPx(x.entry)+"</td><td>"+fmtPx(x.sl)+"</td><td>"+fmtPx(x.tp!=null?x.tp:(x.tp2!=null?x.tp2:x.tp1))+"</td><td>"+esc(x.leverage)+"x</td>"+
      "<td style='color:"+rCol+";font-weight:700'>"+rTxt+"</td><td><span class='tag "+oc+"'"+(x.manual_reason?(" title='Reason: "+esc(x.manual_reason)+"'"):"")+">"+esc(outLabel(x.outcome))+(x.manual_reason?" \u270e":"")+"</span></td>"+
      "<td>"+convCell(x)+"</td>"+
      "<td>"+setupExitCell(x)+"</td>"+
      "<td><a href='"+tv+"' target='_blank' title='Open in TradingView'>Chart ↗</a></td></tr>";}).join('');}
// §23: "Setup → Exit" — the LATCHED entry grade (pre-move read) → the final Stage-5 verdict
// word recorded at close. Em-dash for legacy rows that predate the snapshot.
function setupExitCell(x){
  var g=String(x.grade_at_entry||x.conviction_grade||"").toUpperCase();
  var ev=x.exit_verdict||x.g_verdict||"";
  if(!g && !ev){return "<span class='muted' style='padding:0'>—</span>";}
  var gp=g?("<span class='gpill gp-"+g.toLowerCase()+"'>"+esc(g)+"</span>"):"";
  var exWord=ev?esc(String(ev).split(" — ")[0]):"—";
  var vc=String(x.g_verdict_class||"good");
  var cls={strong:"gv-strong",good:"gv-good",warn:"gv-warn",bad:"gv-bad",terminal:"gv-term"}[vc]||"gv-good";
  var ph=x.exit_phase?(" title='Phase: "+esc(x.exit_phase)+"'"):"";
  return "<span class='se-cell'"+ph+">"+gp+"<span class='se-arrow'>→</span><span class='tag "+cls+"'>"+exWord+"</span></span>";
}
// v7.2: Trade Guardian conviction stamp recorded at close (final Drive / Risk,
// verdict, peak reward). Shows an em-dash for legacy rows closed before it existed.
function convCell(x){
  if(x.g_verdict===undefined||x.g_verdict===null||x.g_verdict===""){return "<span class='muted' style='padding:0'>—</span>";}
  var vc=String(x.g_verdict_class||"good");
  var cls={strong:"gv-strong",good:"gv-good",warn:"gv-warn",bad:"gv-bad",terminal:"gv-term"}[vc]||"gv-good";
  var mfe=(x.g_mfe_r!==undefined&&x.g_mfe_r!==null)?(" · "+esc(x.g_mfe_r)+"R"):"";
  var dr="D"+esc(x.g_drive)+"/R"+esc(x.g_risk);
  return "<span class='tag "+cls+"' title='Drive "+esc(x.g_drive)+" · Risk "+esc(x.g_risk)+" · Confidence "+esc(x.g_conf)+"% · Peak "+esc(x.g_mfe_r)+"R'>"+esc(x.g_verdict)+"</span><div class='convsub'>"+dr+mfe+"</div>";
}

document.querySelectorAll('th[data-s]').forEach(th=>th.onclick=()=>{const s=th.dataset.s;if(SORT===s)DIR=-DIR;else{SORT=s;DIR=-1;}renderTable();});
document.getElementById('q').addEventListener('input',e=>{Q=e.target.value.trim().toLowerCase();apply();});

// v7.5 WS-8.2: feature-calibration panel — per-feature hit-rate + avg NET R from the engine.
async function loadCalib(){try{const r=await fetch('/api/calibration',{cache:'no-store'});const j=await r.json();
  const card=document.getElementById('calib-card'),meta=document.getElementById('calib-meta'),tb=document.getElementById('calib-rows');
  if(!j||!Array.isArray(j.features)||!j.features.length){card.style.display='none';return;}
  var gen=j.filter_generation||j.generation;var genTag=gen?('Showing: '+gen+' · '):'';
  card.style.display='';meta.textContent=genTag+(j.ready?'':'Preview · ')+j.total_trades+' Trades (Min '+j.min_trades+')';
  tb.innerHTML=j.features.map(f=>{const hr=num(f.hit_rate)||0,ar=num(f.avg_net_r)||0;
    const hc=hr>=50?'#9bf5b2':hr>=33?'#ffe39a':'#ff9cae';const ac=ar>=0?'#9bf5b2':'#ff9cae';
    return "<tr><td style='font-family:Sora'>"+esc(f.feature)+"</td><td>"+f.trades+"</td>"+
      "<td style='color:"+hc+";font-weight:700'>"+hr.toFixed(0)+"%</td>"+
      "<td style='color:"+ac+";font-weight:700'>"+(ar>=0?'+':'')+ar.toFixed(2)+"R</td></tr>";}).join('');
  }catch(e){}}
async function load(){try{const r=await fetch('/api/trades?since=0&limit=5000',{cache:'no-store'});const j=await r.json();ALL=Array.isArray(j.trades)?j.trades:[];}catch(e){ALL=[];}buildFilters();apply();loadCalib();}
load();
setInterval(load,60000);
</script>
</body></html>