-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard_script.js
More file actions
5152 lines (5134 loc) · 309 KB
/
Copy pathdashboard_script.js
File metadata and controls
5152 lines (5134 loc) · 309 KB
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const fmt = (value, fallback='-') => value === null || value === undefined ? fallback : value;
const pct = value => value === null || value === undefined ? '-' : (value * 100).toFixed(2) + '%';
const gateReasonLabel = reason => {
const map = {
invalid_side: 'keine LONG/SHORT-Richtung',
missing_price: 'Entry/SL/TP fehlt',
invalid_entry: 'Entry ungültig',
invalid_long_geometry: 'LONG-Geometrie ungültig',
invalid_short_geometry: 'SHORT-Geometrie ungültig',
invalid_risk_reward: 'Risk/Reward ungültig',
reward_too_small: 'TP-Abstand zu klein',
sl_distance_too_high: 'SL-Abstand zu gross',
rr_too_small: 'RR zu klein',
net_profit_too_small: 'Netto-Profit zu klein'
};
return map[String(reason || '')] || fmt(reason);
};
const DEFAULT_LLM_ROLE_PROMPTS = {
llm_role_market_structure_prompt_extra: 'Bewerte nur die Marktstruktur. Achte besonders auf Trendkontext, frische BOS/CHoCH Signale, HH/LL Sequenz, Range-Gefahr und ob der Kandidat nahe an relevanten Strukturzonen liegt. Bei unklarer Range oder widersprüchlicher Struktur eher WAIT statt APPROVE.',
llm_role_momentum_prompt_extra: 'Bewerte nur Momentum und technische Bestätigung. Achte auf RSI/MFI, MACD, EMA/HMA/VWAP Lage, Volumenimpuls und Divergenzen. APPROVE nur, wenn Momentum die geplante Richtung nachvollziehbar unterstützt; bei spätem oder erschöpftem Move eher WAIT.',
llm_role_risk_officer_prompt_extra: 'Bewerte Risiko strikt. Prüfe RR, SL-Distanz, Fee/R, Volatilität, offene Trades, Positionsgröße und Overtrading. Setze hard_block=true, wenn Kosten, Stop-Abstand, offene Exponierung oder Volatilität den Trade ungünstig machen.',
llm_role_skeptic_prompt_extra: 'Suche zuerst aktiv Gründe gegen den Trade. Markiere schwache Annahmen, Datenlücken, Fallback-Setups, zu wenig Live-Historie, Seitwärtsphasen und Widersprüche zwischen Signalquellen. Nur APPROVE, wenn keine wesentlichen Gegenargumente bleiben.',
llm_role_execution_prompt_extra: 'Bewerte Ausführung und Timing. Prüfe, ob Limit oder Market sinnvoll ist, ob der Entry zu spät kommt, ob der Preis dem Ziel schon zu nahe ist und ob der geplante Entry noch ein gutes Chance/Risiko-Verhältnis bietet.',
llm_role_judge_prompt_extra: 'Entscheide konservativ als CEO/Judge. Risk Officer und Skeptic Hard-Blocks haben Vorrang. Bei Rollen-Konflikt, schwacher Datenlage oder fehlender klarer Übereinstimmung WAIT. APPROVE nur, wenn Struktur, Momentum, Risiko und Ausführung zusammenpassen.'
};
const rolePromptValue = (data, key) => {
const value = String(data?.[key] || '').trim();
return value || DEFAULT_LLM_ROLE_PROMPTS[key] || '';
};
const gateNumber = value => value === null || value === undefined || value === '' ? '-' : Number(value).toFixed(6);
const gatePercent = value => value === null || value === undefined || value === '' ? '-' : (Number(value) * 100).toFixed(3) + '%';
function gateDetailText(gate) {
if (!gate) return 'wartet';
const parts = [gate.trade_allowed ? 'OK' : `BLOCKED: ${gateReasonLabel(gate.reason)}`];
if (gate.rr !== undefined) parts.push(`RR ${gateNumber(gate.rr)}`);
if (gate.min_rr !== undefined) parts.push(`min RR ${gateNumber(gate.min_rr)}`);
if (gate.risk_fraction !== undefined) parts.push(`Risk ${gatePercent(gate.risk_fraction)}`);
if (gate.reward_fraction !== undefined) parts.push(`Reward ${gatePercent(gate.reward_fraction)}`);
if (gate.net_profit_fraction !== undefined) parts.push(`Netto ${gatePercent(gate.net_profit_fraction)}`);
if (gate.min_net_profit_fraction !== undefined) parts.push(`min Netto ${gatePercent(gate.min_net_profit_fraction)}`);
if (gate.fee_to_risk_fraction !== undefined) parts.push(`Fee/R ${gatePercent(gate.fee_to_risk_fraction)}`);
if (gate.max_fee_to_risk_fraction !== undefined) parts.push(`max Fee/R ${gatePercent(gate.max_fee_to_risk_fraction)}`);
if (gate.max_sl_distance_fraction !== undefined) parts.push(`max SL ${gatePercent(gate.max_sl_distance_fraction)}`);
return parts.join(' | ');
}
function gateHtml(gate) {
const cls = gate?.trade_allowed ? 'good' : 'dangerText';
return `<span class="${cls}">${escapeHtml(gateDetailText(gate))}</span>`;
}
function lifecycleStageClass(stage) {
const value = String(stage || '').toLowerCase();
if (value === 'tp') return 'good';
if (value === 'sl' || value === 'expired') return 'bad';
if (value === 'open') return 'open';
return 'pending';
}
function tradeTime(value) {
if (!value) return '-';
const number = Number(value);
if (!Number.isFinite(number)) return '-';
const ms = number > 1000000000000 ? number : number * 1000;
return new Date(ms).toLocaleString('de-DE');
}
function renderTradeLifecycle(trade) {
const lifecycle = trade?.lifecycle || {};
const stage = lifecycle.current_stage || trade?.status || '-';
const label = lifecycle.stage_label || fmt(trade?.status);
const detail = lifecycle.stage_detail || '-';
const steps = lifecycle.steps || [];
const stepHtml = steps.map(step => {
const state = String(step.state || 'waiting').toLowerCase();
return `<span class="lifeStep ${state}" title="${escapeHtml(tradeTime(step.timestamp))}">${escapeHtml(step.label || step.key || '-')}</span>`;
}).join(' ');
return `<div class="lifeBox ${lifecycleStageClass(stage)}"><strong>${escapeHtml(label)}</strong><br><span>${escapeHtml(detail)}</span><div class="lifeSteps">${stepHtml}</div></div>`;
}
function tradeLifecycleTime(trade) {
const lifecycle = trade?.lifecycle || {};
const steps = lifecycle.steps || [];
const current = steps.slice().reverse().find(step => step.timestamp);
return tradeTime(current?.timestamp || trade?.closed_at || trade?.filled_at || trade?.created_at);
}
function tradePatternKey(trade) {
const features = trade?.setup?.features || {};
return String(features.brain_pattern_key || features.pattern_key || features.strategy || 'na');
}
function tradeResultBucket(trade) {
const status = String(trade?.status || '').toLowerCase();
const result = Number(trade?.result_r);
if (status === 'pending' || status === 'open') return 'active';
if (!Number.isFinite(result)) return status || 'unknown';
if (result > 0) return 'win';
if (result < 0) return 'loss';
return 'breakeven';
}
function tradeMatchesFilters(trade) {
const symbolOk = !selectedAsset || trade?.setup?.symbol === selectedAsset;
const status = String(trade?.status || '').toLowerCase();
const statusOk = selectedTradeStatus === '__ALL__' || status === selectedTradeStatus;
const patternOk = selectedTradePattern === '__ALL__' || tradePatternKey(trade) === selectedTradePattern;
const resultOk = selectedTradeResult === '__ALL__' || tradeResultBucket(trade) === selectedTradeResult;
return symbolOk && statusOk && patternOk && resultOk;
}
function syncTradeHistoryFilters(tradesAll) {
const statusEl = document.getElementById('tradeStatusFilter');
const patternEl = document.getElementById('tradePatternFilter');
const resultEl = document.getElementById('tradeResultFilter');
if (!statusEl || !patternEl || !resultEl) return;
const statuses = Array.from(new Set((tradesAll || []).map(t => String(t.status || '').toLowerCase()).filter(Boolean))).sort();
const patterns = Array.from(new Set((tradesAll || []).map(tradePatternKey).filter(Boolean))).sort();
const keepStatus = selectedTradeStatus;
const keepPattern = selectedTradePattern;
const keepResult = selectedTradeResult;
statusEl.innerHTML = '<option value="__ALL__">Alle Status</option>' + statuses.map(value => `<option value="${escapeHtml(value)}">${escapeHtml(value)}</option>`).join('');
patternEl.innerHTML = '<option value="__ALL__">Alle Pattern</option>' + patterns.map(value => `<option value="${escapeHtml(value)}">${escapeHtml(value)}</option>`).join('');
resultEl.innerHTML = [
'<option value="__ALL__">Alle Ergebnisse</option>',
'<option value="active">Aktiv</option>',
'<option value="win">Gewinn</option>',
'<option value="loss">Verlust</option>',
'<option value="breakeven">Break-even</option>',
'<option value="expired">Expired</option>'
].join('');
selectedTradeStatus = statuses.includes(keepStatus) ? keepStatus : '__ALL__';
selectedTradePattern = patterns.includes(keepPattern) ? keepPattern : '__ALL__';
selectedTradeResult = ['__ALL__', 'active', 'win', 'loss', 'breakeven', 'expired'].includes(keepResult) ? keepResult : '__ALL__';
statusEl.value = selectedTradeStatus;
patternEl.value = selectedTradePattern;
resultEl.value = selectedTradeResult;
}
function tradeExportRows() {
const tradesAll = latestStatusData?.paper?.trades || [];
return tradesAll.filter(tradeMatchesFilters).slice().reverse().map(trade => {
const setup = trade.setup || {};
const features = setup.features || {};
const lifecycle = trade.lifecycle || {};
const gate = features.value_gate || features.economic_gate || {};
return {
id: trade.id || '',
status: trade.status || '',
symbol: setup.symbol || '',
side: setup.side || '',
size_mode: setup.trade_size_mode || '',
planned_notional_usd: setup.planned_notional_usd ?? '',
planned_quantity_asset: setup.planned_quantity_asset ?? '',
entry: setup.entry ?? '',
stop_loss: setup.stop_loss ?? '',
take_profit: setup.take_profit ?? '',
result_r: trade.result_r ?? '',
risk_usd: trade.risk_usd ?? '',
gross_pnl_usd: trade.gross_pnl_usd ?? '',
estimated_fees_usd: trade.estimated_fees_usd ?? '',
net_pnl_usd: trade.net_pnl_usd ?? '',
confidence: setup.confidence ?? '',
agent_pattern: tradePatternKey(trade),
result_bucket: tradeResultBucket(trade),
lifecycle_stage: lifecycle.current_stage || trade.status || '',
lifecycle_detail: lifecycle.stage_detail || '',
created_at: tradeTime(trade.created_at),
filled_at: tradeTime(trade.filled_at),
closed_at: tradeTime(trade.closed_at),
gate_reason: gate.reason || '',
gate_rr: gate.rr ?? '',
gate_net_profit_fraction: gate.net_profit_fraction ?? '',
};
});
}
function downloadTextFile(filename, content, type) {
const blob = new Blob([content], { type });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
}
function csvCell(value) {
const text = String(value ?? '');
return `"${text.replace(/"/g, '""')}"`;
}
function exportTradeHistory(format) {
const rows = tradeExportRows();
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
if (format === 'json') {
downloadTextFile(`trade_history_${stamp}.json`, JSON.stringify(rows, null, 2), 'application/json;charset=utf-8');
setControlMessage(`JSON Export erstellt: ${rows.length} Trades`);
return;
}
const headers = Object.keys(rows[0] || {
id: '', status: '', symbol: '', side: '', size_mode: '', planned_notional_usd: '', planned_quantity_asset: '', entry: '', stop_loss: '', take_profit: '', result_r: '', confidence: '', agent_pattern: '', result_bucket: '', lifecycle_stage: '', lifecycle_detail: '', created_at: '', filled_at: '', closed_at: '', gate_reason: '', gate_rr: '', gate_net_profit_fraction: ''
});
const csv = [headers.map(csvCell).join(';')].concat(rows.map(row => headers.map(header => csvCell(row[header])).join(';'))).join('\\n');
downloadTextFile(`trade_history_${stamp}.csv`, csv, 'text/csv;charset=utf-8');
setControlMessage(`CSV Export erstellt: ${rows.length} Trades`);
}
const percentInputValue = value => {
const number = Number(value ?? 0);
if (!Number.isFinite(number)) return 0;
return Math.round(number * 1000000) / 10000;
};
const percentOutputValue = value => {
const number = Number(String(value ?? '0').replace(',', '.'));
if (!Number.isFinite(number)) return 0;
return Math.max(0, number) / 100;
};
const percentDisplay = value => value === null || value === undefined ? '-' : percentInputValue(value).toFixed(2) + '%';
const money = (value, currency='USDT') => value === null || value === undefined ? '-' : Number(value).toFixed(2) + ' ' + currency;
const pnlMoney = (value, currency='USDT') => value === null || value === undefined ? '-' : `${Number(value).toFixed(2)} ${currency}`;
const ALL_ASSETS_VALUE = '__ALL__';
let selectedAsset = null;
let selectedTradeStatus = '__ALL__';
let selectedTradePattern = '__ALL__';
let selectedTradeResult = '__ALL__';
let selectedAgentAsset = null;
let latestStatusData = null;
let currentView = 'dashboard';
let agentSortMode = 'score_desc';
let agentRoleFilter = 'all';
const DETAILS_STATE_PREFIX = 'phemex-details-open:';
let detailsOpenState = {};
let lastChartKey = '';
let klineChart = null;
let klineOverlayIds = [];
let marketStructureOverlaysRegistered = false;
let chartConfig = null;
let latestConfig = {};
let latestEnvSettings = {};
function applyUiTheme(theme) {
const value = theme === 'light' ? 'light' : 'dark';
document.body.dataset.theme = value;
}
let localTradeSizes = {};
let agentSettingsDirty = false;
let agentSettingsRendering = false;
let agentSettingsSaving = false;
let agentSettingsRenderRevision = 0;
let currentUiLanguage = 'de';
const UI_TEXT = {
de: {
settings: 'Einstellungen',
apiConnection: 'API-Verbindung',
tradingSettings: 'Trading-Einstellungen',
configSettings: 'Konfiguration',
chartView: 'Chart-Ansicht',
analysisView: 'Analyse-Ansicht',
strategySetup: 'Strategie Setup',
chartHeading: 'Chart-Ansicht',
analysisHeading: 'Analyse-Ansicht',
apiHeader: 'API-Verbindung',
tradingHeader: 'Trading-Einstellungen',
configHeader: 'Konfiguration',
chartSetupHeader: 'Chart-Ansicht Setup',
save: 'Speichern',
setupSave: 'Setup speichern',
noChanges: 'Keine Änderungen',
dirty: 'Nicht gespeichert',
saving: 'Speichere...',
saved: 'Gespeichert',
saveFailed: 'Speichern fehlgeschlagen',
noAnswer: 'Keine Antwort',
languageHelp: 'Schaltet die wichtigsten Bedienoberflächen zwischen Deutsch und English um.',
themeLabel: 'Oberfläche',
languageLabel: 'Sprache',
assetModeLabel: 'Asset-Beobachtungsmodus',
singleAsset: 'Einzel-Asset',
multiAsset: 'Multi-Asset',
chartHint: 'Kerzenkörper, Docht, Kennzeichnung/Rand, Grid und Hintergrund werden direkt hier in der Chart-Ansicht über das Setup-Popup eingestellt.',
agentOfflineHelp: 'Wenn aktiv, zeigt die Analyse-Ansicht auch deaktivierte Quellen oder Quellen mit ausgeschaltetem gekoppeltem Indikator. Wenn aus, werden diese Quellen in der Analyse-Ansicht ausgeblendet.',
chartSetupStatus: 'Chart-Ansicht Setup: Vorschau zeigt Körper, Docht, Rand, Grid und Hintergrund.',
},
en: {
settings: 'Settings',
apiConnection: 'API Connection',
tradingSettings: 'Trading Settings',
configSettings: 'Configuration',
chartView: 'Chart View',
analysisView: 'Analysis View',
strategySetup: 'Strategy Setup',
chartHeading: 'Chart View',
analysisHeading: 'Analysis View',
apiHeader: 'API Connection',
tradingHeader: 'Trading Settings',
configHeader: 'Configuration',
chartSetupHeader: 'Chart View Setup',
save: 'Save',
setupSave: 'Save Setup',
noChanges: 'No changes',
dirty: 'Not saved',
saving: 'Saving...',
saved: 'Saved',
saveFailed: 'Save failed',
noAnswer: 'No response',
languageHelp: 'Switches the main controls between German and English.',
themeLabel: 'Interface',
languageLabel: 'Language',
assetModeLabel: 'Asset Observer Mode',
singleAsset: 'Single Asset',
multiAsset: 'Multi Asset',
chartHint: 'Candle body, wick, marker/border, grid and background are configured directly here in Chart View through the setup popup.',
agentOfflineHelp: 'When enabled, Analysis View also shows disabled sources or sources with their linked indicator turned off. When disabled, those sources are hidden in Analysis View.',
chartSetupStatus: 'Chart View Setup: preview shows body, wick, border, grid and background.',
}
};
function uiText(key) {
return (UI_TEXT[currentUiLanguage] && UI_TEXT[currentUiLanguage][key]) || UI_TEXT.de[key] || key;
}
function setTextById(id, text) {
const el = document.getElementById(id);
if (el) el.textContent = text;
}
function setLabelText(selector, text) {
const el = document.querySelector(selector);
if (!el) return;
const button = el.querySelector('button');
const suffix = button ? button.outerHTML : '';
el.innerHTML = `${escapeHtml(text)} ${suffix}`.trim();
}
function applyUiLanguage(language) {
currentUiLanguage = language === 'en' ? 'en' : 'de';
document.documentElement.lang = currentUiLanguage;
const languageSelect = document.getElementById('cfgUiLanguage');
if (languageSelect) languageSelect.value = currentUiLanguage;
setTextById('settingsMenuButton', uiText('settings'));
setTextById('apiSettingsButton', uiText('apiConnection'));
setTextById('tradingSettingsButton', uiText('tradingSettings'));
setTextById('configSettingsButton', uiText('configSettings'));
setTextById('chartViewButton', uiText('chartView'));
setTextById('agentViewButton', uiText('analysisView'));
setTextById('agentSetupViewButton', uiText('strategySetup'));
const chartHeading = document.querySelector('#chartView h2');
if (chartHeading) chartHeading.textContent = uiText('chartHeading');
const analysisHeading = document.querySelector('#agentView h2');
if (analysisHeading) analysisHeading.textContent = uiText('analysisHeading');
const apiHeader = document.querySelector('#apiModal .modalHeader h2');
if (apiHeader) apiHeader.textContent = uiText('apiHeader');
const tradingHeader = document.querySelector('#tradingModal .modalHeader h2');
if (tradingHeader) tradingHeader.textContent = uiText('tradingHeader');
const configHeader = document.querySelector('#configModal .modalHeader h2');
if (configHeader) configHeader.textContent = uiText('configHeader');
const chartSetupHeader = document.querySelector('#chartSetupModal .modalHeader h2');
if (chartSetupHeader) chartSetupHeader.textContent = uiText('chartSetupHeader');
const chartHint = document.querySelector('.chartSetupHint');
if (chartHint) chartHint.textContent = uiText('chartHint');
setTextById('uiLanguageHelp', uiText('languageHelp'));
setTextById('agentShowOfflineHelp', uiText('agentOfflineHelp'));
setLabelText('label[for="cfgUiTheme"]', uiText('themeLabel'));
setLabelText('label[for="cfgUiLanguage"]', uiText('languageLabel'));
setLabelText('label[for="cfgAssetMode"]', uiText('assetModeLabel'));
const assetMode = document.getElementById('cfgAssetMode');
if (assetMode) {
const single = assetMode.querySelector('option[value="single"]');
const multi = assetMode.querySelector('option[value="multi"]');
if (single) single.textContent = uiText('singleAsset');
if (multi) multi.textContent = uiText('multiAsset');
}
setTextById('saveSettings', uiText('save'));
setTextById('saveConfigSettings', uiText('save'));
setTextById('saveStrategyConfigSettings', uiText('save'));
const saveAgent = document.getElementById('saveAgentSettings');
if (saveAgent && saveAgent.dataset.state !== 'saving') saveAgent.textContent = uiText('setupSave');
const feedback = document.getElementById('agentSettingsSaveFeedback');
if (feedback && feedback.dataset.state === 'idle') feedback.textContent = uiText('noChanges');
}
let activeTradeSizeSymbol = null;
let localMinProfitFractions = {};
let localMaxSlDistanceFractions = {};
let valueGatePriceCache = {};
let valueGatePreviewToken = 0;
let tradingPriceCache = {};
let tradingPriceLoading = {};
let tradingPricePreviewToken = 0;
let lastActionMessage = null;
let lastIndicatorData = null;
let lastChartRows = [];
let lastReplayPreviewData = null;
let lastReplayHistoryData = null;
let replayRequestRunning = false;
let refreshRunning = false;
let refreshFailedCount = 0;
let agentSettingsSaveResetTimer = null;
let botControlRequestRunning = false;
let dashboardReloadRequestRunning = false;
let resetConfirmRequest = null;
let tradingMarginMode = 'isolated';
function loadDetailsOpenState(key, fallback=false) {
if (!key) return !!fallback;
try {
const stored = window.localStorage?.getItem(`${DETAILS_STATE_PREFIX}${key}`);
if (stored === '1') return true;
if (stored === '0') return false;
} catch (error) {}
return Object.prototype.hasOwnProperty.call(detailsOpenState, key) ? detailsOpenState[key] : !!fallback;
}
function storeDetailsOpenState(key, open) {
if (!key) return;
detailsOpenState[key] = !!open;
try {
window.localStorage?.setItem(`${DETAILS_STATE_PREFIX}${key}`, open ? '1' : '0');
} catch (error) {}
}
window.__setDetailsOpen = storeDetailsOpenState;
function detailsAttrs(key, defaultOpen=false) {
const open = loadDetailsOpenState(key, defaultOpen);
return `data-details-key="${key}" ${open ? 'open ' : ''}ontoggle="window.__setDetailsOpen && window.__setDetailsOpen('${key}', this.open)"`;
}
function installDetailsStateHandler() {
if (document.body.dataset.detailsStateHandler === '1') return;
document.body.dataset.detailsStateHandler = '1';
document.addEventListener('toggle', event => {
const target = event.target;
if (!(target instanceof HTMLDetailsElement)) return;
storeDetailsOpenState(target.dataset.detailsKey, target.open);
}, true);
document.addEventListener('click', event => {
const target = event.target;
if (!(target instanceof Element)) return;
if (target.closest('button, a, input, select, textarea, label')) return;
const summary = target.closest('summary');
const details = summary?.closest('details[data-details-key]');
if (!details) return;
event.preventDefault();
details.open = !details.open;
storeDetailsOpenState(details.dataset.detailsKey, details.open);
}, true);
document.addEventListener('keydown', event => {
if (event.key !== 'Enter' && event.key !== ' ') return;
const target = event.target;
if (!(target instanceof Element)) return;
if (target.closest('button, a, input, select, textarea, label')) return;
const summary = target.closest('summary');
const details = summary?.closest('details[data-details-key]');
if (!details) return;
event.preventDefault();
details.open = !details.open;
storeDetailsOpenState(details.dataset.detailsKey, details.open);
}, true);
}
function mergeConfigState(update = {}) {
if (!update || typeof update !== 'object') return latestConfig || {};
latestConfig = { ...(latestConfig || {}), ...update };
return latestConfig;
}
async function refreshEnvSettings() {
try {
const response = await fetch('/api/env-settings', { cache: 'no-store' });
if (response.ok) {
latestEnvSettings = await response.json();
if (!Object.prototype.hasOwnProperty.call(latestEnvSettings, 'openai_key_present')) latestEnvSettings.openai_key_present = false;
}
} catch (error) {}
return latestEnvSettings || {};
}
function td(value) { return `<td>${value}</td>`; }
function assetViewLabel(value) {
return value ? value : 'Gesamt';
}
function selectedAssetValue() {
return selectedAsset || ALL_ASSETS_VALUE;
}
function setSelectedAssetFromDropdown(value) {
selectedAsset = value === ALL_ASSETS_VALUE ? null : value;
}
function escapeHtml(value) {
return String(value ?? '').replace(/[&<>"']/g, char => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[char]));
}
function timeframeLabel(seconds) {
const map = {60:'1m', 300:'5m', 900:'15m', 1800:'30m', 3600:'1h', 14400:'4h', 86400:'1D'};
return map[Number(seconds)] || `${seconds}s`;
}
function durationLabel(seconds, fallback='-') {
const value = Number(seconds);
if (!Number.isFinite(value) || value <= 0) return fallback;
if (value < 60) return `${value.toFixed(value < 10 ? 2 : 1)}s`;
const minutes = Math.floor(value / 60);
const rest = Math.round(value % 60);
return `${minutes}m ${rest}s`;
}
function llmErrorDurationDetail(layer, durationText) {
const provider = String(layer?.provider || latestConfig?.llm_provider || 'LLM').trim();
const label = provider ? provider.charAt(0).toUpperCase() + provider.slice(1) : 'LLM';
const text = String(layer?.risk_note || layer?.message || layer?.judge?.summary || layer?.advice || '').trim();
const httpMatch = text.match(/HTTP\s*(\d{3})/i) || text.match(/(\d{3})\s+Server Error/i) || text.match(/(\d{3})\s+Client Error/i);
let cause = 'Fehler';
if (/timeout|timed out|zeit/i.test(text)) {
cause = 'Timeout';
} else if (httpMatch) {
cause = `HTTP ${httpMatch[1]}`;
} else if (/connection|verbindung|refused|unreachable|erreichbar/i.test(text)) {
cause = 'Verbindung';
}
return `${label} ${cause} nach ${durationText}`;
}
function emaSourceLabel(source, signalTf) {
if (source === 'daily') return 'Daily EMA';
return `EMA auf ${timeframeLabel(signalTf)}`;
}
function updateEmaConfigVisibility() {
const mode = document.getElementById('cfgTrendMode')?.value || 'day_candle';
const source = document.getElementById('cfgTrendEmaSource');
const period = document.getElementById('cfgTrendEma');
const showSource = mode === 'ema';
const showCustomPeriod = showSource && source && source.value !== 'daily';
if (source) source.parentElement.style.display = showSource ? 'block' : 'none';
if (period) period.parentElement.style.display = showCustomPeriod ? 'block' : 'none';
}
function isModalOpen(id) {
const modal = document.getElementById(id);
return modal && modal.classList.contains('open');
}
function setControlMessage(message, level='ok') {
lastActionMessage = { message, level, until: Date.now() + 4500 };
renderControlMessage(message);
}
function renderControlMessage(fallback='Bereit') {
const el = document.getElementById('controlStatus');
if (!el) return;
if (lastActionMessage && Date.now() < lastActionMessage.until) {
el.textContent = lastActionMessage.message;
el.className = `controlStatus ${lastActionMessage.level}`;
return;
}
lastActionMessage = null;
el.textContent = fallback;
el.className = 'controlStatus';
}
function installBotControlHandler() {
if (document.body.dataset.botControlHandler === '1') return;
document.body.dataset.botControlHandler = '1';
document.addEventListener('click', event => {
const button = event.target.closest('#startBot, #stopBot, #reloadBot, #resetBot');
if (!button || button.disabled) return;
event.preventDefault();
event.stopPropagation();
if (botControlRequestRunning || dashboardReloadRequestRunning) {
setControlMessage('Aktion laeuft bereits...', 'warn');
return;
}
if (button.id === 'reloadBot') {
reloadDashboardData();
return;
}
const actions = {
startBot: 'start',
stopBot: 'stop',
resetBot: 'reset'
};
const action = actions[button.id];
if (action) botControl(action);
}, true);
}
function bindBotControlButtons() {
const bind = id => {
const button = document.getElementById(id);
if (!button) return;
button.dataset.botControlBound = '1';
button.type = 'button';
button.onclick = null;
button.onpointerup = null;
button.removeAttribute('onclick');
button.removeAttribute('onpointerup');
};
bind('startBot');
bind('stopBot');
bind('reloadBot');
bind('resetBot');
}
function renderBotControls(cfg) {
const running = !!cfg.observer_enabled;
const start = document.getElementById('startBot');
const stop = document.getElementById('stopBot');
const reset = document.getElementById('resetBot');
const activeSymbols = cfg.symbols || [];
const active = cfg.observer_asset_mode === 'multi'
? `${activeSymbols.length} Assets`
: (activeSymbols[0] || '-');
const resetPending = resetConfirmRequest && resetConfirmRequest.until > Date.now();
if (start) {
start.classList.toggle('available', !running);
start.classList.toggle('running', running);
start.disabled = running;
start.textContent = running ? 'Läuft' : 'Start';
start.title = running ? 'Scanner läuft bereits' : 'Scanner starten';
}
if (stop) {
stop.classList.toggle('available', running);
stop.classList.toggle('stopped', !running);
stop.disabled = !running;
stop.textContent = running ? 'Stop' : 'Gestoppt';
stop.title = running ? 'Scanner stoppen' : 'Scanner ist bereits gestoppt';
}
if (reset) {
reset.classList.toggle('confirm', !!resetPending);
reset.textContent = resetPending ? 'Reset bestaetigen' : 'Reset Speicher';
reset.title = resetPending ? 'Nochmals klicken, um den Reset auszufuehren' : 'Reset vorbereiten';
}
bindBotControlButtons();
renderControlMessage(running ? `Scanner aktiv: ${active}` : `Scanner gestoppt: ${active}`);
}
function renderDayCandleStatus(data, cfg) {
const activeSymbols = cfg.symbols || [];
const symbol = selectedAsset || activeSymbols[0] || 'BTCUSDT';
const scan = data.cycle?.symbols?.[symbol]?.scan || {};
const day = scan.day_candle || {};
const direction = String(day.direction || 'neutral').toLowerCase();
const panel = document.getElementById('dayCandlePanel');
const icon = document.getElementById('dayCandleIcon');
const detail = document.getElementById('dayCandleDetail');
if (!panel || !icon || !detail) return;
panel.className = `dayCandlePanel ${direction}`;
if (direction === 'long' || direction === 'short') {
const image = direction === 'long' ? '/files/arrow_up.png' : '/files/arrow_down.png';
icon.innerHTML = `<img src="${image}" alt="${direction}">`;
} else {
icon.innerHTML = '<span class="dayCandleFallback">-</span>';
}
const label = direction === 'long' ? 'LONG' : direction === 'short' ? 'SHORT' : 'NEUTRAL';
const open = day.open !== undefined ? `O ${fmt(day.open)}` : '';
const close = day.close !== undefined ? `C ${fmt(day.close)}` : '';
const candles = day.candles !== undefined ? `${fmt(day.candles)} Kerzen` : 'keine Day-Candle';
detail.textContent = `${label} | ${[open, close, candles].filter(Boolean).join(' | ')}`;
}
function flashButton(id) {
const btn = document.getElementById(id);
if (!btn) return;
btn.classList.add('flash');
window.setTimeout(() => btn.classList.remove('flash'), 700);
}
function syncSwitchState(inputId, stateId, activeText='Aktiv', inactiveText='Aus', boxId=null) {
const input = document.getElementById(inputId);
const state = document.getElementById(stateId);
if (!input || !state) return;
const active = !!input.checked;
state.textContent = active ? activeText : inactiveText;
state.classList.toggle('active', active);
if (boxId) {
const box = document.getElementById(boxId);
if (box) box.classList.toggle('active', active);
}
}
function syncAllSwitchStates() {
syncSwitchState('paperToggle', 'paperToggleState', 'Aktiv', 'Aus', 'paperToggleBox');
syncSwitchState('cfgCorrelationBlock', 'cfgCorrelationState');
syncSwitchState('cfgTrendFilter', 'cfgTrendState');
syncSwitchState('cfgIndicatorEnabled', 'cfgIndicatorEnabledState', 'Aktiv', 'Aus');
syncSwitchState('cfgIndicatorShowBosChoch', 'cfgIndicatorShowBosChochState', 'Aktiv', 'Aus');
syncSwitchState('cfgIndicatorShowBoxes', 'cfgIndicatorShowBoxesState', 'Aktiv', 'Aus');
syncSwitchState('cfgIndicatorShowSwingLabels', 'cfgIndicatorShowSwingLabelsState', 'Aktiv', 'Aus');
syncSwitchState('cfgIndicatorShowHma', 'cfgIndicatorShowHmaState', 'Aktiv', 'Aus');
syncSwitchState('cfgIndicatorShowSma', 'cfgIndicatorShowSmaState', 'Aktiv', 'Aus');
syncSwitchState('cfgIndicatorShowTripleEma', 'cfgIndicatorShowTripleEmaState', 'Aktiv', 'Aus');
syncSwitchState('cfgIndicatorShowMfi', 'cfgIndicatorShowMfiState', 'Aktiv', 'Aus');
syncSwitchState('cfgIndicatorShowMacd', 'cfgIndicatorShowMacdState', 'Aktiv', 'Aus');
syncSwitchState('cfgIndicatorShowSupportResistance', 'cfgIndicatorShowSupportResistanceState', 'Aktiv', 'Aus');
syncSwitchState('cfgBrainEnabled', 'cfgBrainEnabledState', 'Aktiv', 'Aus');
syncSwitchState('cfgBrainLlmLayer', 'cfgBrainLlmLayerState', 'Aktiv', 'Aus');
syncSwitchState('cfgOllamaEnabled', 'cfgOllamaEnabledState', 'Aktiv', 'Aus');
syncSwitchState('cfgOllamaBlockHint', 'cfgOllamaBlockHintState', 'Aktiv', 'Aus');
syncSwitchState('cfgLlmRoleTeamEnabled', 'cfgLlmRoleTeamState', 'Aktiv', 'Aus');
syncSwitchState('cfgOpenAiEnabled', 'cfgOpenAiEnabledState', 'Aktiv', 'Aus');
syncSwitchState('cfgLlmRoleRequired', 'cfgLlmRoleRequiredState', 'Aktiv', 'Aus');
syncSwitchState('cfgLlmRoleMarketStructure', 'cfgLlmRoleMarketStructureState', 'Aktiv', 'Aus');
syncSwitchState('cfgLlmRoleMomentum', 'cfgLlmRoleMomentumState', 'Aktiv', 'Aus');
syncSwitchState('cfgLlmRoleRiskOfficer', 'cfgLlmRoleRiskOfficerState', 'Aktiv', 'Aus');
syncSwitchState('cfgLlmRoleSkeptic', 'cfgLlmRoleSkepticState', 'Aktiv', 'Aus');
syncSwitchState('cfgLlmRoleExecution', 'cfgLlmRoleExecutionState', 'Aktiv', 'Aus');
syncSwitchState('cfgAgentShowOffline', 'cfgAgentShowOfflineState', 'Aktiv', 'Aus');
document.querySelectorAll('[data-agent-enabled]').forEach(input => syncSwitchState(input.id, `${input.id}State`, 'Aktiv', 'Aus'));
document.querySelectorAll('[data-agent-blocking]').forEach(input => syncSwitchState(input.id, `${input.id}State`, 'Block', 'Info'));
syncUtilityAgentGroupStates();
}
function syncLlmProviderVisibility() {
const provider = document.getElementById('cfgLlmProvider')?.value || 'ollama';
document.querySelectorAll('.providerOpenAi').forEach(el => el.classList.toggle('providerHidden', provider !== 'openai'));
document.querySelectorAll('.providerOllama').forEach(el => el.classList.toggle('providerHidden', provider !== 'ollama'));
const help = document.getElementById('llmProviderHelp');
if (help) {
help.textContent = provider === 'ollama'
? 'Ollama ist als lokaler Provider aktiv. OpenAI-Felder werden ausgeblendet.'
: 'OpenAI ist als Provider aktiv. Ollama-Felder werden ausgeblendet.';
}
}
async function refresh() {
if (document.querySelector('.modalBackdrop.open')) return;
if (refreshRunning) return;
refreshRunning = true;
try {
const controller = new AbortController();
const timeout = window.setTimeout(() => controller.abort(), 9000);
const response = await fetch('/api/status', { cache: 'no-store', signal: controller.signal });
window.clearTimeout(timeout);
if (!response.ok) throw new Error(`status ${response.status}`);
const data = await response.json();
refreshFailedCount = 0;
latestStatusData = data;
const perf = data.paper?.performance || {};
const cfg = mergeConfigState(data.config || {});
await refreshEnvSettings();
applyUiTheme(cfg.ui_theme);
applyUiLanguage(cfg.ui_language);
updateKlineChartStyles();
const account = data.account || {};
const currency = account.currency || cfg.account_balance_currency || 'USDT';
const activeSymbols = cfg.symbols || [];
const activeSummary = cfg.observer_asset_mode === 'multi'
? `${activeSymbols.length} Assets aktiv`
: `${activeSymbols[0] || '-'} aktiv`;
document.getElementById('subtitle').textContent = `Letztes Update: ${fmt(data.bot?.last_update_utc)} | ${activeSummary}`;
const scanner = cfg.observer_enabled ? 'Scanner läuft' : 'Scanner gestoppt';
const paperMode = cfg.paper_trading_enabled ? 'Testmodus/Paper' : 'Testmodus/Signal-only';
const assetModeLabel = cfg.observer_asset_mode === 'multi' ? 'Multi Asset' : 'Single Asset';
const statusPanel = document.getElementById('statusPanel');
const liveActive = !!data.bot?.live_trading_enabled;
const apiWarning = account.status && account.status !== 'ok';
statusPanel.className = 'statusPanel ' + (liveActive ? 'live' : apiWarning ? 'warning' : cfg.observer_enabled ? 'running' : 'stopped');
document.getElementById('statusTitle').textContent = liveActive ? 'LIVE' : paperMode.toUpperCase();
document.getElementById('statusDetail').textContent = apiWarning ? `${assetModeLabel} | ${scanner} | API prüfen` : `${assetModeLabel} | ${scanner}`;
document.getElementById('accountBalance').textContent = account.status === 'ok' ? money(account.account_balance, currency) : 'API nicht verbunden';
document.getElementById('availableBalance').textContent = account.status === 'ok' ? money(account.available_balance_estimate, currency) : fmt(account.error, '-');
document.getElementById('profit').textContent = pct(perf.profit_fraction);
document.getElementById('profit').className = 'value ' + ((perf.profit_fraction || 0) >= 0 ? 'good' : 'bad');
document.getElementById('winrate').textContent = pct(perf.win_rate);
if (!isModalOpen('tradingModal')) {
document.getElementById('paperToggle').checked = !!cfg.paper_trading_enabled;
syncSwitchState('paperToggle', 'paperToggleState', 'Aktiv', 'Aus', 'paperToggleBox');
localTradeSizes = JSON.parse(JSON.stringify(cfg.trade_sizes_by_symbol || {}));
renderTradeSizeAssetSelector(cfg);
loadTradeSizeForSelectedAsset();
updateSizeVisibility();
}
const tradesAll = data.paper?.trades || [];
const watchlist = cfg.watchlist_assets || [];
const watchSymbols = watchlist.map(item => item.symbol);
const extraSymbols = tradesAll.map(t => t.setup?.symbol).filter(Boolean).filter(symbol => !watchSymbols.includes(symbol));
const symbols = [...watchSymbols, ...Array.from(new Set(extraSymbols))];
if (selectedAsset && !symbols.includes(selectedAsset)) selectedAsset = null;
syncChartAssetOptions(cfg);
const assetFilter = document.getElementById('assetFilter');
const oldValue = assetFilter.value || selectedAssetValue();
const assetOptions = [`<option value="${ALL_ASSETS_VALUE}">Gesamt / alles anzeigen</option>`].concat(symbols.map(symbol => {
const item = watchlist.find(asset => asset.symbol === symbol);
const active = (cfg.symbols || []).includes(symbol) ? ' *' : '';
return `<option value="${symbol}">${item ? item.label : symbol}${active}</option>`;
}));
assetFilter.innerHTML = assetOptions.join('');
if (oldValue === ALL_ASSETS_VALUE || !symbols.includes(oldValue)) {
selectedAsset = null;
} else {
selectedAsset = oldValue;
}
assetFilter.value = selectedAssetValue();
renderDayCandleStatus(data, cfg);
renderBotControls(cfg);
syncAgentAssetOptions(cfg);
syncReplayAssetOptions(cfg);
renderLlmAuditSummary(data, cfg);
renderLiveAnalysisFlowSummary(data, cfg);
renderAgentViewer(data, cfg);
const viewLabel = assetViewLabel(selectedAsset);
syncTradeHistoryFilters(tradesAll);
document.getElementById('tradesTitle').textContent = `Trade-History (${viewLabel})`;
const assetStats = selectedAsset ? data.paper?.per_symbol?.[selectedAsset] : null;
// Keep this line focused on scanner control; trade stats already have their own cards/table.
const trades = tradesAll.filter(tradeMatchesFilters).slice().reverse().slice(0, 50);
const tradeFilterInfo = document.getElementById('tradeFilterInfo');
if (tradeFilterInfo) tradeFilterInfo.textContent = `${trades.length} von ${tradesAll.length} Trades sichtbar`;
document.getElementById('tradeRows').innerHTML = trades.map(t => {
const s = t.setup || {};
const size = s.trade_size_mode === 'asset'
? `${fmt(s.planned_quantity_asset)} asset`
: `${fmt(s.planned_notional_usd)} USD`;
return '<tr>' + [
td(`<span class="tradeStatus ${lifecycleStageClass(t.status)}">${escapeHtml(fmt(t.status))}</span>`),
td(fmt(s.symbol)), td(fmt(s.side)), td(size), td(fmt(s.entry)), td(fmt(s.stop_loss)),
td(fmt(s.take_profit)), td(fmt(t.result_r)), td(fmt(s.confidence)),
td(renderTradeLifecycle(t)), td(tradeLifecycleTime(t))
].join('') + '</tr>';
}).join('') || '<tr><td colspan="11">Noch keine Paper-Trades.</td></tr>';
const cycle = data.cycle || {};
const eventBySymbol = {};
(cycle.events || []).forEach(event => {
if (event.symbol && !eventBySymbol[event.symbol]) eventBySymbol[event.symbol] = event;
if (event.setup?.symbol && !eventBySymbol[event.setup.symbol]) eventBySymbol[event.setup.symbol] = event;
});
const debugSymbols = Object.entries(cycle.symbols || {}).filter(([symbol]) => !selectedAsset || symbol === selectedAsset);
document.getElementById('debugRows').innerHTML = debugSymbols.map(([symbol, info]) => {
const scan = info.scan || {};
const event = eventBySymbol[symbol] || {};
const gate = event.reason === 'value_gate'
? gateHtml(event.value_result)
: 'nicht erreicht';
const status = scan.setup_found ? '<span class="good">Setup Kandidat</span>' : '<span class="dangerText">Kein Setup</span>';
const side = scan.side ? `side ${scan.side}` : 'side -';
const zone = scan.zone_type
? `zone ${scan.zone_type} ${fmt(scan.zone_low)} - ${fmt(scan.zone_high)} score ${fmt(scan.zone_score)} retests ${fmt(scan.retests)}`
: `nearest ${fmt(scan.nearest_zone_type)} ${fmt(scan.nearest_zone_low)} - ${fmt(scan.nearest_zone_high)} dist ${fmt(scan.nearest_zone_distance)}`;
const impulse = scan.impulse_time ? `base ${fmt(scan.base_candles)} | impulse body ${fmt(scan.impulse_body_ratio)} xRange ${fmt(scan.impulse_range_multiple)}` : '';
const entry = scan.entry_method ? `entry ${scan.entry_method} | has_fvg ${fmt(scan.has_fvg)} | zone ${fmt(scan.entry_zone_low)} - ${fmt(scan.entry_zone_high)}` : '';
const confirm = scan.confirmation_candles_after_signal !== undefined ? `confirm ${scan.confirmation_candles_after_signal}` : '';
const emaInfo = scan.ema?.active ? `ema ${emaSourceLabel(scan.ema.source, cfg.signal_timeframe_seconds)} ${fmt(scan.ema.period)} | ${fmt(scan.ema.direction)} | C ${fmt(scan.ema.close)} / EMA ${fmt(scan.ema.ema)}` : '';
const confirmationDebug = scan.confirmation_debug?.closest
? `best window: touch ${fmt(scan.confirmation_debug.closest.zone_touch_ok)} / body ${fmt(scan.confirmation_debug.closest.body_ok)} / break ${fmt(scan.confirmation_debug.closest.break_ok)} / fvg ${fmt(scan.confirmation_debug.closest.fvg_ok)} / rejection ${fmt(scan.confirmation_debug.closest.rejection_ok)}<br>windows touch ${fmt(scan.confirmation_debug.zone_touch_windows, 0)} body ${fmt(scan.confirmation_debug.body_ok_windows, 0)} break ${fmt(scan.confirmation_debug.break_ok_windows, 0)} fvg ${fmt(scan.confirmation_debug.fvg_ok_windows, 0)} rejection ${fmt(scan.confirmation_debug.rejection_ok_windows, 0)}`
: '';
return '<tr>' + [
td(symbol),
td(status),
td(fmt(scan.reason || event.reason)),
td([side, zone, impulse, entry, confirm, emaInfo, confirmationDebug].filter(Boolean).join('<br>')),
td(gate)
].join('') + '</tr>';
}).join('') || '<tr><td colspan="5">Noch kein Scan-Debug vorhanden.</td></tr>';
const botRows = [
['Modus', data.bot?.mode],
['Live', data.bot?.live_trading_enabled ? 'aktiv' : 'gesperrt'],
['Scanner', cfg.observer_enabled ? 'läuft' : 'gestoppt'],
['Paper-Trading', cfg.paper_trading_enabled ? 'aktiv' : 'aus'],
['Asset Mode', cfg.observer_asset_mode === 'multi' ? 'Multi Asset' : 'Single Asset'],
['Risk Locks', `max ${cfg.max_open_trades_total} gesamt / ${cfg.max_open_trades_per_asset} je Asset`],
['Correlation Lock', cfg.block_same_direction_correlated_trades ? 'aktiv' : 'aus'],
['Stop-Loss', cfg.stop_loss_mode === 'atr' ? `ATR ${fmt(cfg.stop_loss_atr_period)} x ${fmt(cfg.stop_loss_atr_multiplier)}` : `Struktur + ${fmt(cfg.stop_loss_buffer_percent)}% Puffer`],
['Phemex Balance', account.status === 'ok' ? money(account.account_balance, currency) : fmt(account.error)],
['Positionsgröße', cfg.trade_size_mode === 'asset' ? `${cfg.trade_size_asset} Asset` : `${cfg.trade_size_usd} USD/USDT`],
['Timeframe', `${timeframeLabel(data.config?.signal_timeframe_seconds)}`],
['Trend', cfg.trend_filter_mode === 'ema' ? `${emaSourceLabel(cfg.trend_ema_source, cfg.signal_timeframe_seconds)} ${cfg.trend_ema_period}${cfg.use_trend_filter ? ' blockierend' : ' optional'}` : (cfg.trend_filter_mode === 'day_candle' ? `Day-Candle${cfg.use_trend_filter ? ' blockierend' : ' Status'}` : 'aus')],
['Abfrage', `Phemex / LLM ${fmt(cfg.phemex_poll_seconds ?? cfg.poll_seconds)}s`],
['TP/SL', `${data.config?.reward_risk}:1`],
['Value Gate', `min Netto ${percentDisplay(cfg.min_net_profit_fraction)} | max SL ${percentDisplay(cfg.max_sl_distance_fraction)} | max Fee/R ${percentDisplay(cfg.max_fee_to_risk_fraction)}`],
['LLM Rollenteam', `${llmAuditEnabled(cfg) ? 'aktiv' : 'aus'} | ${fmt((cfg.llm_provider === 'ollama' ? cfg.ollama_model : cfg.openai_model) || 'gpt-4.1-mini')}`],
['LLM Hardware', llmHardwareLabel(data.llm_hardware)],
['Paper-Trades', `${fmt(perf.closed, 0)} geschlossen / ${fmt(data.paper?.open_trades, 0)} offen / ${fmt(data.paper?.pending_trades, 0)} pending`],
];
document.getElementById('botRows').innerHTML = botRows.map(([k,v]) => `<tr><th>${k}</th><td>${fmt(v)}</td></tr>`).join('');
const buckets = data.memory?.top_buckets || [];
const memorySummary = document.getElementById('memorySummary');
if (memorySummary) {
memorySummary.textContent = `Live-/Paper-Lernspeicher: ${fmt(data.memory?.completed_trades ?? 0, 0)} abgeschlossene Trades | ${fmt(data.memory?.bucket_count ?? 0, 0)} Buckets | Quelle ${fmt(data.memory?.source || 'live_paper')}`;
}
document.getElementById('bucketRows').innerHTML = buckets.map(b => '<tr>' + [
td(`<code>${b.key}</code>`), td(b.count), td(pct(b.win_rate)), td(b.avg_r)
].join('') + '</tr>').join('') || '<tr><td colspan="4">Noch keine abgeschlossenen Trades im Lernspeicher.</td></tr>';
document.getElementById('cycle').textContent = JSON.stringify(data.cycle || {}, null, 2);
} catch (error) {
refreshFailedCount += 1;
console.error('Dashboard refresh failed', error);
renderControlMessage(`Dashboard-Refresh Fehler (${refreshFailedCount})`, 'warn');
} finally {
refreshRunning = false;
}
}
function normalizeReplaySymbol(value) {
return String(value || '').replace('.P', '').split(':', 1)[0].trim().toUpperCase();
}
function syncReplayAssetOptions(cfg) {
const replayAsset = document.getElementById('replayAsset');
if (!replayAsset) return;
const current = normalizeReplaySymbol(replayAsset.value);
const watchlist = cfg?.watchlist_assets || latestConfig?.watchlist_assets || [];
const assetList = cfg?.asset_list || latestConfig?.asset_list || [];
const activeSymbols = cfg?.symbols || latestConfig?.symbols || [];
const symbols = Array.from(new Set([
...watchlist.map(item => item?.symbol).filter(Boolean),
...assetList,
...activeSymbols,
].map(normalizeReplaySymbol).filter(Boolean)));
if (!symbols.length) symbols.push('BTCUSDT');
replayAsset.innerHTML = symbols.map(symbol => `<option value="${escapeHtml(symbol)}">${escapeHtml(symbol)}</option>`).join('');
if (symbols.includes(current)) {
replayAsset.value = current;
} else {
replayAsset.value = symbols[0];
}
}
function replayGateLabel(gate) {
if (!gate) return '-';
if (gate.trade_allowed) return `OK | RR ${fmt(gate.rr)}`;
return `BLOCK | ${fmt(gate.reason)}`;
}
function replayTradeLabel(frame) {
const events = frame?.replay_events || [];
const summary = frame?.replay_trade_summary || {};
const eventText = events.length
? events.map(event => `${fmt(event.status)}${event.result_r !== undefined && event.result_r !== null ? ' ' + fmt(event.result_r) + 'R' : ''}`).join(' / ')
: '-';
return `${eventText}<br><span class="label">P ${fmt(summary.pending, 0)} | O ${fmt(summary.open, 0)} | TP ${fmt(summary.tp, 0)} | SL ${fmt(summary.sl, 0)} | Exp ${fmt(summary.expired, 0)}</span>`;
}
function replayLlmRoleLabel(frame) {
const protocol = frame?.llm_role_protocol || {};
if (!protocol || Object.keys(protocol).length === 0) return '<span class="tradeStatus neutral">keine Rollen</span>';
const judge = protocol.judge || {};
const gate = protocol.gate || {};
const roles = Array.isArray(protocol.roles) ? protocol.roles : [];
const decision = String(protocol.decision || judge.decision || 'WAIT').toUpperCase();
const hardBlocks = roles.filter(role => role?.hard_block || String(role?.decision || '').toUpperCase() === 'BLOCK').length;
const statusClass = decision === 'APPROVE' ? 'tp' : decision === 'BLOCK' || gate.allowed === false ? 'sl' : 'pending';
const provider = protocol.provider ? `${escapeHtml(protocol.provider)} | ` : '';
const gateText = gate.allowed === false ? ` | ${escapeHtml(gate.reason || 'block')}` : '';
const roleText = roles.length ? ` | Rollen ${roles.length}` : '';
const blockText = hardBlocks ? ` | Blocks ${hardBlocks}` : '';
return `<div class="replayRoleBox"><span class="tradeStatus ${statusClass}">${provider}${escapeHtml(decision)}${gateText}</span><small>${escapeHtml(judge.summary || judge.advice || '-')}${roleText}${blockText}</small></div>`;
}
function replayDecisionValue(frame) {
return String(frame?.decision || frame?.ceo_signal || '').toUpperCase();
}
function replayFrameTradeStatuses(frame) {
return (frame?.replay_events || []).map(event => String(event.status || '').toLowerCase()).filter(Boolean);
}
function replayFrameMatchesFilters(frame) {
const decisionFilter = document.getElementById('replayFilterDecision')?.value || 'all';
const gateFilter = document.getElementById('replayFilterGate')?.value || 'all';
const resultFilter = document.getElementById('replayFilterResult')?.value || 'all';
if (decisionFilter !== 'all' && replayDecisionValue(frame) !== decisionFilter) return false;
const gate = frame?.gate || null;
if (gateFilter === 'allowed' && !gate?.trade_allowed) return false;
if (gateFilter === 'blocked' && (!gate || gate.trade_allowed)) return false;
if (gateFilter === 'missing' && gate) return false;
const statuses = replayFrameTradeStatuses(frame);
if (resultFilter === 'created' && statuses.length === 0) return false;
if (resultFilter === 'none' && statuses.length > 0) return false;
if (!['all', 'created', 'none'].includes(resultFilter) && !statuses.includes(resultFilter)) return false;
return true;
}
function filteredReplayFrames(data) {
return (data?.frames || []).filter(frame => replayFrameMatchesFilters(frame));
}
function renderReplayFilterSummary(data, shownCount, filteredCount=null, displayLimit=null) {
const el = document.getElementById('replayFilterSummary');
if (!el) return;
const returned = (data?.frames || []).length;
const fullTotal = Number(data?.summary?.frames || returned);
const filtered = filteredCount === null ? returned : filteredCount;
const limitText = displayLimit && filtered > shownCount ? ` | Anzeige max ${fmt(displayLimit, 0)}` : '';
const backendLimitText = fullTotal > returned ? ` | geladen ${fmt(returned, 0)} von ${fmt(fullTotal, 0)}` : '';
el.textContent = `Filter: ${fmt(shownCount, 0)} sichtbar / ${fmt(filtered, 0)} Treffer${backendLimitText}${limitText}`;
el.className = shownCount === filtered && fullTotal === returned ? 'controlStatus' : 'controlStatus warn';
}
function replayRuleClass(quality) {
const value = String(quality || 'WATCH').toUpperCase();
if (value === 'GOOD') return 'good';
if (value === 'BAD') return 'bad';
return 'watch';
}
function replayRuleMinCount(memory=null) {
return Math.max(3, Number(memory?.rule_min_count ?? latestConfig?.replay_rule_weight_min_count ?? 5));
}
function replayRuleAdjustment(rule, memory=null) {
const quality = String(rule?.quality || 'WATCH').toUpperCase();
const maxAbs = Math.max(0, Number(memory?.rule_max_abs_adjustment ?? latestConfig?.replay_rule_max_abs_adjustment ?? 12));
if (quality === 'GOOD') return Math.max(0, Math.min(maxAbs, Number(memory?.rule_good_bonus ?? latestConfig?.replay_rule_good_bonus ?? 6)));
if (quality === 'BAD') return Math.max(-maxAbs, Math.min(0, Number(memory?.rule_bad_penalty ?? latestConfig?.replay_rule_bad_penalty ?? -10)));
return 0;
}
function replayRuleSafetyClass(rule, memory=null) {
if (rule?.eligible) return 'safe';
const count = Number(rule?.count || 0);
return count < replayRuleMinCount(memory) ? 'warn' : 'neutral';
}
function replayRuleSafetyText(rule, memory=null) {
if (rule?.eligible) return `aktivierbar | min ${fmt(replayRuleMinCount(memory), 0)}`;
const count = Number(rule?.count || 0);
if (count < replayRuleMinCount(memory)) return `zu wenig Daten | min ${fmt(replayRuleMinCount(memory), 0)}`;
return 'nur Beobachtung';
}
function replayRuleScopeText(rule) {
const scope = String(rule?.scope || latestConfig?.replay_rule_scope || 'asset').toLowerCase();
const symbol = rule?.symbol || '-';
return scope === 'global' ? 'global' : `asset | ${symbol}`;
}
function replayActionClass(action) {
const value = String(action || '').toUpperCase();
if (value === 'PRIORITY') return 'priority';
if (value === 'AVOID') return 'avoid';
if (value === 'FEE_DRAG') return 'watch';
if (value === 'WAIT') return 'wait';
return 'watch';
}
function replayActionText(asset) {
return asset?.action_label || (asset?.action || 'beobachten');
}
function renderReplayMemoryTest(data) {
const summaryEl = document.getElementById('replayMemoryTestSummary');
const rowsEl = document.getElementById('replayMemoryRows');
const rulesSummaryEl = document.getElementById('replayPreviewRulesSummary');
const ruleRowsEl = document.getElementById('replayPreviewRuleRows');
const memory = data?.memory_test || null;
if (!summaryEl || !rowsEl) return;
if (!memory) {
summaryEl.textContent = 'Memory-Testmodus: keine Daten.';
rowsEl.innerHTML = '<tr><td colspan="5">Keine Replay-Memory-Buckets.</td></tr>';
if (rulesSummaryEl) rulesSummaryEl.textContent = 'Replay-Lernregeln: keine Daten.';
if (ruleRowsEl) ruleRowsEl.innerHTML = '<tr><td colspan="8">Keine Replay-Lernregeln.</td></tr>';
return;
}
summaryEl.innerHTML = [