Skip to content

Styles

CSS stylesheets and JavaScript for the dashboard UI.

This module contains embedded CSS and JavaScript as Python string constants. The styles implement a dark-themed interface with a fixed sidebar navigation and responsive content areas.

Constants

BASE_CSS: Global styles for layout, sidebar, cards, forms, and common elements. BACKTEST_CSS: Styles specific to the backtest configuration page. BACKTEST_JS: JavaScript for backtest page interactivity including: - Strategy and parameter loading - Publisher/dataset/symbol cascading selection - Symbol preset management - Date range validation - Backtest execution and run history display

BASE_CSS = '\n* { margin: 0; padding: 0; box-sizing: border-box; }\nbody {\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n background: #0d1117;\n color: #e6edf3;\n min-height: 100vh;\n display: flex;\n}\n.sidebar {\n width: 220px;\n background: #161b22;\n border-right: 1px solid #30363d;\n min-height: 100vh;\n position: fixed;\n left: 0;\n top: 0;\n display: flex;\n flex-direction: column;\n}\n.sidebar-header {\n padding: 20px 16px;\n border-bottom: 1px solid #30363d;\n}\n.sidebar-header h1 {\n font-size: 16px;\n font-weight: 600;\n color: #e6edf3;\n}\n.sidebar-nav {\n padding: 12px 8px;\n flex: 1;\n}\n.sidebar-nav a {\n display: flex;\n align-items: center;\n gap: 10px;\n padding: 10px 12px;\n color: #8b949e;\n text-decoration: none;\n font-size: 14px;\n border-radius: 6px;\n margin-bottom: 2px;\n}\n.sidebar-nav a:hover {\n background: #21262d;\n color: #e6edf3;\n}\n.sidebar-nav a.active {\n background: #21262d;\n color: #e6edf3;\n}\n.sidebar-nav svg {\n width: 16px;\n height: 16px;\n flex-shrink: 0;\n}\n.main-content {\n margin-left: 220px;\n flex: 1;\n min-height: 100vh;\n}\n.container {\n max-width: 1200px;\n margin: 0 auto;\n padding: 32px 24px;\n}\n.card {\n background: #161b22;\n border: 1px solid #30363d;\n border-radius: 8px;\n padding: 24px;\n margin-bottom: 16px;\n}\n.card h2 {\n font-size: 16px;\n font-weight: 600;\n margin-bottom: 16px;\n color: #e6edf3;\n}\n.empty-state {\n text-align: center;\n padding: 48px;\n color: #8b949e;\n}\n.empty-state p {\n margin-top: 8px;\n font-size: 14px;\n}\n' module-attribute

BACKTEST_CSS = '\n.container { max-width: none; height: 100vh; padding: 24px; display: flex; flex-direction: column; box-sizing: border-box; }\n.backtest-layout { display: flex; gap: 24px; flex: 1; min-height: 0; }\n.backtest-left { flex: 1; min-width: 0; display: flex; flex-direction: column; }\n.backtest-right { flex: 1; min-width: 0; display: flex; flex-direction: column; }\n.backtest-left .card, .backtest-right .card { flex: 1; display: flex; flex-direction: column; margin-bottom: 0; overflow: hidden; }\n.backtest-right .runs-list { flex: 1; overflow-y: auto; }\n.form-group { margin-bottom: 16px; }\n.form-group label { display: block; margin-bottom: 6px; font-size: 14px; color: #8b949e; }\n.form-group select, .form-group input {\n width: 100%; padding: 8px 12px; background: #0d1117; border: 1px solid #30363d;\n border-radius: 6px; color: #e6edf3; font-size: 14px;\n}\n.form-group select:focus, .form-group input:focus { outline: none; border-color: #58a6ff; }\n.params-container { margin-top: 12px; padding: 12px; background: #0d1117; border-radius: 6px; }\n.param-row { display: flex; gap: 12px; margin-bottom: 8px; align-items: center; }\n.param-row label { min-width: 120px; font-size: 13px; }\n.param-row input, .param-row select { flex: 1; }\n.btn { padding: 10px 20px; background: #238636; border: none; border-radius: 6px;\n color: #fff; font-size: 14px; cursor: pointer; width: 100%; }\n.btn:hover { background: #2ea043; }\n.btn:disabled { background: #30363d; cursor: not-allowed; }\n.date-row { display: flex; gap: 12px; }\n.date-row .form-group { flex: 1; margin-bottom: 0; }\n.symbol-section { background: #0d1117; border-radius: 6px; padding: 12px; }\n.publisher-row { display: flex; gap: 8px; margin-bottom: 12px; }\n.publisher-row select { flex: 1; }\n.preset-row { display: flex; gap: 8px; margin-bottom: 12px; align-items: center; }\n.preset-row select { flex: 1; }\n.preset-row input { flex: 1; }\n.preset-row .btn-sm { padding: 6px 12px; font-size: 12px; width: auto; cursor: not-allowed; }\n.preset-row .btn-secondary { background: #30363d; }\n.preset-row .btn-secondary.active { background: #238636; cursor: pointer; }\n.preset-row .btn-secondary.active:hover { background: #2ea043; }\n.preset-row .btn-danger { background: #30363d; }\n.preset-row .btn-danger.active { background: #da3633; cursor: pointer; }\n.preset-row .btn-danger.active:hover { background: #f85149; }\n.search-row { display: flex; gap: 8px; margin-bottom: 8px; }\n.search-row input { flex: 1; }\n.search-results { max-height: 150px; overflow-y: auto; border: 1px solid #30363d; border-radius: 4px; margin-bottom: 12px; }\n.search-results:empty { display: none; }\n.search-result { display: flex; justify-content: space-between; align-items: center; padding: 6px 10px; border-bottom: 1px solid #21262d; cursor: pointer; }\n.search-result:last-child { border-bottom: none; }\n.search-result:hover { background: #161b22; }\n.search-result .symbol { font-family: monospace; }\n.selected-symbols { display: flex; flex-wrap: wrap; gap: 6px; min-height: 32px; max-height: 150px; overflow-y: auto; }\n.selected-tag { display: inline-flex; align-items: center; gap: 4px; background: #238636; color: #fff; padding: 4px 8px; border-radius: 4px; font-size: 12px; font-family: monospace; }\n.selected-tag .remove { cursor: pointer; opacity: 0.7; }\n.selected-tag .remove:hover { opacity: 1; }\n.selected-label { font-size: 13px; color: #8b949e; margin-bottom: 6px; }\n.section-header { font-size: 14px; color: #8b949e; margin-bottom: 6px; margin-top: 8px; }\n.runs-list { display: flex; flex-direction: column; gap: 12px; }\n.run-item { background: #0d1117; border: 1px solid #30363d; border-radius: 6px; padding: 12px; display: flex; gap: 12px; align-items: flex-start; }\n.run-item.selected { border-color: #58a6ff; }\n.run-checkbox { flex-shrink: 0; margin-top: 2px; width: 16px; height: 16px; accent-color: #58a6ff; cursor: pointer; }\n.run-content { flex: 1; min-width: 0; }\n.run-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }\n.run-name { font-family: monospace; font-size: 13px; color: #e6edf3; }\n.run-id { color: #8b949e; font-size: 11px; margin-left: 6px; }\n.run-status { font-size: 12px; font-weight: 500; padding: 2px 8px; border-radius: 10px; }\n.run-status.running { background: #9e6a03; color: #fff; }\n.run-status.completed { background: #238636; color: #fff; }\n.run-status.failed { background: #da3633; color: #fff; }\n.run-status.cancelled { background: #30363d; color: #8b949e; }\n.run-status.error { background: #da3633; color: #fff; }\n.run-meta { font-size: 12px; color: #8b949e; }\n.run-meta.with-progress { margin-bottom: 8px; }\n.progress-bar { height: 6px; background: #30363d; border-radius: 3px; overflow: hidden; }\n.progress-fill { height: 100%; background: #58a6ff; transition: width 0.3s ease; }\n.progress-fill.completed { background: #238636; }\n.progress-fill.error { background: #da3633; }\n.empty-runs { text-align: center; padding: 48px 24px; color: #8b949e; }\n.empty-runs p { font-size: 14px; }\n.runs-toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; padding-bottom: 12px; border-bottom: 1px solid #30363d; }\n.runs-toolbar .select-all-label { display: flex; align-items: center; gap: 8px; font-size: 13px; color: #8b949e; cursor: pointer; }\n.runs-toolbar .select-all-label input { width: 16px; height: 16px; accent-color: #58a6ff; cursor: pointer; }\n.btn-delete { padding: 6px 12px; background: #da3633; border: none; border-radius: 6px; color: #fff; font-size: 13px; cursor: pointer; }\n.btn-delete:hover { background: #f85149; }\n.btn-delete:disabled { background: #30363d; cursor: not-allowed; color: #8b949e; }\n' module-attribute

BACKTEST_JS = '\nlet strategyParams = [];\nlet coverageData = [];\nlet availableRtypes = [];\nlet symbolsForRtype = {};\nlet symbolCoverageForRtype = {};\nlet selectedSymbols = [];\nlet presets = [];\nlet globalMinDate = null;\nlet globalMaxDate = null;\nlet dbRuns = [];\nlet activeRuns = {};\nlet selectedRunIds = new Set();\nlet publishers = [];\nlet datasets = [];\nlet selectedPublisherId = null;\n\nconst RTYPE_LABELS = {32: \'Second\', 33: \'Minute\', 34: \'Hour\', 35: \'Day\'};\n\nfunction capitalize(str) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\nasync function loadPublishers() {\n const rtype = getSelectedRtype();\n const url = rtype ? `/api/secmaster/publishers?rtype=${rtype}` : \'/api/secmaster/publishers\';\n const res = await fetch(url);\n const data = await res.json();\n publishers = data.publishers || [];\n const sel = document.getElementById(\'publisher-name\');\n sel.innerHTML = \'<option value="">-- Select Publisher --</option>\';\n publishers.forEach(p => sel.innerHTML += `<option value="${p}">${capitalize(p)}</option>`);\n}\n\nasync function onPublisherChange() {\n const name = document.getElementById(\'publisher-name\').value;\n const rtype = getSelectedRtype();\n const datasetSel = document.getElementById(\'publisher-dataset\');\n datasetSel.innerHTML = \'<option value="">-- Select Dataset --</option>\';\n datasets = [];\n selectedPublisherId = null;\n document.getElementById(\'symbol-selection\').style.display = \'none\';\n selectedSymbols = [];\n renderSelectedSymbols();\n updateDateRange();\n if (!name) return;\n const url = rtype\n ? `/api/secmaster/publishers/${encodeURIComponent(name)}/datasets?rtype=${rtype}`\n : `/api/secmaster/publishers/${encodeURIComponent(name)}/datasets`;\n const res = await fetch(url);\n const data = await res.json();\n datasets = data.datasets || [];\n datasets.forEach(d => datasetSel.innerHTML += `<option value="${d.publisher_id}">${d.dataset}</option>`);\n}\n\nasync function onDatasetChange() {\n const pubId = document.getElementById(\'publisher-dataset\').value;\n selectedPublisherId = pubId ? parseInt(pubId) : null;\n selectedSymbols = [];\n renderSelectedSymbols();\n updateDateRange();\n document.getElementById(\'symbol-search\').value = \'\';\n document.getElementById(\'search-results\').innerHTML = \'\';\n if (selectedPublisherId) {\n await loadCoverageForPublisher(selectedPublisherId);\n document.getElementById(\'symbol-selection\').style.display = \'block\';\n await loadPresets();\n } else {\n document.getElementById(\'symbol-selection\').style.display = \'none\';\n }\n}\n\nasync function loadCoverageForPublisher(publisherId) {\n const rtype = getSelectedRtype();\n const url = `/api/secmaster/symbols_coverage?publisher_id=${publisherId}&rtype=${rtype}`;\n const res = await fetch(url);\n const data = await res.json();\n coverageData = data.symbols || [];\n symbolsForRtype = {};\n symbolCoverageForRtype = {};\n coverageData.forEach(row => {\n if (!symbolsForRtype[row.rtype]) {\n symbolsForRtype[row.rtype] = [];\n symbolCoverageForRtype[row.rtype] = {};\n }\n symbolsForRtype[row.rtype].push(row.symbol);\n symbolCoverageForRtype[row.rtype][row.symbol] = {min_ts: row.min_ts, max_ts: row.max_ts};\n });\n}\n\nasync function loadPresets() {\n const res = await fetch(\'/api/presets\');\n const data = await res.json();\n presets = data.presets || [];\n await filterAndRenderPresets();\n}\n\nasync function filterAndRenderPresets() {\n const sel = document.getElementById(\'preset-select\');\n sel.innerHTML = \'<option value="">-- Select Preset --</option>\';\n const rtype = getSelectedRtype();\n const availableSymbols = symbolsForRtype[rtype] || [];\n for (const p of presets) {\n const res = await fetch(`/api/presets/${encodeURIComponent(p)}`);\n const data = await res.json();\n const hasAvailable = (data.symbols || []).some(s => availableSymbols.includes(s));\n if (hasAvailable) {\n sel.innerHTML += `<option value="${p}">${p}</option>`;\n }\n }\n updateButtonStates();\n}\n\nasync function loadPreset() {\n const name = document.getElementById(\'preset-select\').value;\n updateButtonStates();\n if (!name) {\n selectedSymbols = [];\n renderSelectedSymbols();\n updateDateRange();\n return;\n }\n const rtype = getSelectedRtype();\n const symbols = symbolsForRtype[rtype] || [];\n const res = await fetch(`/api/presets/${encodeURIComponent(name)}`);\n const data = await res.json();\n if (data.symbols) {\n selectedSymbols = data.symbols.filter(s => symbols.includes(s));\n renderSelectedSymbolsKeepPreset();\n updateDateRange();\n }\n}\n\nasync function savePreset() {\n const nameInput = document.getElementById(\'preset-name\');\n const name = nameInput.value.trim();\n if (!name) { alert(\'Enter a preset name\'); return; }\n if (selectedSymbols.length === 0) { alert(\'Select at least one symbol\'); return; }\n const exists = presets.includes(name);\n const method = exists ? \'PUT\' : \'POST\';\n const url = exists ? `/api/presets/${encodeURIComponent(name)}` : \'/api/presets\';\n await fetch(url, {\n method, headers: {\'Content-Type\': \'application/json\'},\n body: JSON.stringify({name, symbols: selectedSymbols})\n });\n nameInput.value = \'\';\n await loadPresets();\n document.getElementById(\'preset-select\').value = name;\n}\n\nasync function deletePreset() {\n const name = document.getElementById(\'preset-select\').value;\n if (!name) { alert(\'Select a preset to delete\'); return; }\n if (!confirm(`Delete preset "${name}"?`)) return;\n await fetch(`/api/presets/${encodeURIComponent(name)}`, {method: \'DELETE\'});\n await loadPresets();\n selectedSymbols = [];\n renderSelectedSymbols();\n updateDateRange();\n}\n\nfunction updateButtonStates() {\n const runBtn = document.getElementById(\'run-btn\');\n const saveBtn = document.getElementById(\'preset-save-btn\');\n const deleteBtn = document.getElementById(\'preset-delete-btn\');\n const presetSelect = document.getElementById(\'preset-select\');\n const presetNameInput = document.getElementById(\'preset-name\');\n const strategyEl = document.getElementById(\'strategy\');\n const barPeriodEl = document.getElementById(\'bar-period\');\n if (!runBtn) return;\n const rtype = barPeriodEl ? parseInt(barPeriodEl.value) || null : null;\n const strategy = strategyEl ? strategyEl.value : \'\';\n const canRun = strategy && rtype && selectedPublisherId && selectedSymbols.length > 0;\n runBtn.disabled = !canRun;\n const hasPresetSelected = !!(presetSelect && presetSelect.value);\n const hasPresetName = !!(presetNameInput && presetNameInput.value.trim().length > 0);\n const canSave = hasPresetName && selectedSymbols.length > 0;\n if (saveBtn) {\n saveBtn.classList.toggle(\'active\', canSave);\n }\n if (deleteBtn) {\n deleteBtn.classList.toggle(\'active\', hasPresetSelected);\n }\n}\n\nasync function loadStrategies() {\n const res = await fetch(\'/api/strategies\');\n const data = await res.json();\n const sel = document.getElementById(\'strategy\');\n data.strategies.forEach(s => sel.innerHTML += `<option value="${s.id}">${s.name}</option>`);\n if (data.strategies.length > 0) {\n sel.value = data.strategies[0].id;\n loadStrategyParams();\n }\n}\n\nasync function loadStrategyParams() {\n const name = document.getElementById(\'strategy\').value;\n if (!name) return;\n const res = await fetch(`/api/strategies/${name}`);\n const data = await res.json();\n strategyParams = data.parameters || [];\n renderParams();\n}\n\nfunction formatParamName(name) {\n let result = name.replace(/_/g, \' \');\n result = result.replace(/([A-Z]+)([A-Z][a-z])/g, \'$1 $2\');\n result = result.replace(/([a-z])([A-Z])/g, \'$1 $2\');\n return result.split(\' \').map(word => {\n if (word === word.toUpperCase() && word.length > 1) return word;\n return word.charAt(0).toUpperCase() + word.slice(1);\n }).join(\' \');\n}\n\nfunction renderParams() {\n const container = document.getElementById(\'strategy-params\');\n const filtered = strategyParams.filter(p => p.name !== \'bar_period\');\n if (filtered.length === 0) {\n container.innerHTML = \'<div style="color: #8b949e; font-size: 13px;">No parameters</div>\';\n return;\n }\n container.innerHTML = filtered.map(p => {\n const label = formatParamName(p.name);\n if (p.choices && p.choices.length > 0) {\n const opts = p.choices.map(c => `<option value="${c}" ${c === p.default ? \'selected\' : \'\'}>${c}</option>`).join(\'\');\n return `<div class="param-row"><label>${label}</label><select id="sp_${p.name}">${opts}</select></div>`;\n }\n const inputType = p.type === \'bool\' ? \'checkbox\' : (p.type === \'float\' || p.type === \'int\' ? \'number\' : \'text\');\n const step = p.step || (p.type === \'float\' ? \'0.01\' : \'1\');\n const checked = p.type === \'bool\' && p.default ? \'checked\' : \'\';\n return `<div class="param-row"><label>${label}</label><input type="${inputType}" id="sp_${p.name}" value="${p.default}" step="${step}" ${p.min !== undefined ? `min="${p.min}"` : \'\'} ${p.max !== undefined ? `max="${p.max}"` : \'\'} ${checked}></div>`;\n }).join(\'\');\n}\n\nfunction tsToDate(ts) {\n const ms = Math.floor(ts / 1000000);\n const d = new Date(ms);\n return d.toISOString().split(\'T\')[0];\n}\n\nasync function loadCoverage() {\n const res = await fetch(\'/api/secmaster/symbols_coverage\');\n const data = await res.json();\n coverageData = data.symbols || [];\n const rtypeSet = new Set();\n coverageData.forEach(row => rtypeSet.add(row.rtype));\n availableRtypes = Array.from(rtypeSet).sort((a, b) => a - b);\n populateBarPeriodDropdown();\n}\n\nfunction populateBarPeriodDropdown() {\n const sel = document.getElementById(\'bar-period\');\n sel.innerHTML = \'<option value="">-- Select bar period --</option>\';\n availableRtypes.forEach(rt => {\n const label = RTYPE_LABELS[rt] || `rtype ${rt}`;\n sel.innerHTML += `<option value="${rt}">${label}</option>`;\n });\n}\n\nfunction onBarPeriodChange() {\n selectedSymbols = [];\n selectedPublisherId = null;\n symbolsForRtype = {};\n symbolCoverageForRtype = {};\n renderSelectedSymbols();\n updateDateRange();\n const rtype = document.getElementById(\'bar-period\').value;\n const section = document.getElementById(\'symbols-section\');\n const symbolSelection = document.getElementById(\'symbol-selection\');\n document.getElementById(\'publisher-name\').value = \'\';\n document.getElementById(\'publisher-dataset\').innerHTML = \'<option value="">-- Select Dataset --</option>\';\n if (rtype) {\n section.style.display = \'block\';\n loadPublishers();\n } else {\n section.style.display = \'none\';\n }\n symbolSelection.style.display = \'none\';\n document.getElementById(\'symbol-search\').value = \'\';\n document.getElementById(\'search-results\').innerHTML = \'\';\n}\n\nfunction getSelectedRtype() {\n return parseInt(document.getElementById(\'bar-period\').value) || null;\n}\n\nfunction searchSymbols() {\n const query = document.getElementById(\'symbol-search\').value.toLowerCase();\n const container = document.getElementById(\'search-results\');\n const rtype = getSelectedRtype();\n if (!query || !rtype) {\n container.innerHTML = \'\';\n return;\n }\n const symbols = symbolsForRtype[rtype] || [];\n const matches = symbols.filter(s => s.toLowerCase().includes(query) && !selectedSymbols.includes(s)).slice(0, 20);\n container.innerHTML = matches.map(s =>\n `<div class="search-result" onclick="addSymbol(\'${s}\')"><span class="symbol">${s}</span></div>`\n ).join(\'\');\n}\n\nfunction addSymbol(symbol) {\n if (!selectedSymbols.includes(symbol)) {\n selectedSymbols.push(symbol);\n document.getElementById(\'preset-select\').value = \'\';\n renderSelectedSymbols();\n updateDateRange();\n }\n document.getElementById(\'symbol-search\').value = \'\';\n document.getElementById(\'search-results\').innerHTML = \'\';\n}\n\nfunction removeSymbol(symbol) {\n selectedSymbols = selectedSymbols.filter(s => s !== symbol);\n document.getElementById(\'preset-select\').value = \'\';\n renderSelectedSymbols();\n updateDateRange();\n}\n\nfunction renderSelectedSymbols() {\n const container = document.getElementById(\'selected-symbols\');\n document.getElementById(\'selected-label\').textContent = `Selected (${selectedSymbols.length}):`;\n container.innerHTML = selectedSymbols.map(s =>\n `<span class="selected-tag">${s}<span class="remove" onclick="removeSymbol(\'${s}\')">&times;</span></span>`\n ).join(\'\');\n updateButtonStates();\n}\n\nfunction renderSelectedSymbolsKeepPreset() {\n const container = document.getElementById(\'selected-symbols\');\n document.getElementById(\'selected-label\').textContent = `Selected (${selectedSymbols.length}):`;\n container.innerHTML = selectedSymbols.map(s =>\n `<span class="selected-tag">${s}<span class="remove" onclick="removeSymbol(\'${s}\')">&times;</span></span>`\n ).join(\'\');\n updateButtonStates();\n}\n\nfunction updateDateRange() {\n const startInput = document.getElementById(\'start-date\');\n const endInput = document.getElementById(\'end-date\');\n const rtype = getSelectedRtype();\n if (selectedSymbols.length === 0 || !rtype) {\n globalMinDate = null;\n globalMaxDate = null;\n startInput.value = \'\';\n endInput.value = \'\';\n startInput.removeAttribute(\'min\');\n startInput.removeAttribute(\'max\');\n endInput.removeAttribute(\'min\');\n endInput.removeAttribute(\'max\');\n return;\n }\n const coverage = symbolCoverageForRtype[rtype] || {};\n let minTs = null, maxTs = null;\n selectedSymbols.forEach(s => {\n const cov = coverage[s];\n if (cov) {\n if (minTs === null || cov.min_ts < minTs) minTs = cov.min_ts;\n if (maxTs === null || cov.max_ts > maxTs) maxTs = cov.max_ts;\n }\n });\n if (minTs === null) return;\n globalMinDate = tsToDate(minTs);\n globalMaxDate = tsToDate(maxTs);\n startInput.min = globalMinDate;\n startInput.max = globalMaxDate;\n startInput.value = globalMinDate;\n endInput.min = globalMinDate;\n endInput.max = globalMaxDate;\n endInput.value = globalMaxDate;\n}\n\nfunction clampDate(inputId) {\n if (!globalMinDate || !globalMaxDate) return;\n const input = document.getElementById(inputId);\n if (input.value < globalMinDate) input.value = globalMinDate;\n if (input.value > globalMaxDate) input.value = globalMaxDate;\n}\n\nfunction collectParams() {\n const result = {};\n strategyParams.forEach(p => {\n const el = document.getElementById(`sp_${p.name}`);\n if (!el) return;\n if (p.type === \'bool\') result[p.name] = el.checked;\n else if (p.type === \'int\') result[p.name] = parseInt(el.value);\n else if (p.type === \'float\') result[p.name] = parseFloat(el.value);\n else result[p.name] = el.value;\n });\n return result;\n}\n\nasync function loadDbRuns() {\n const res = await fetch(\'/api/runs\');\n const data = await res.json();\n dbRuns = data.runs || [];\n renderRuns();\n}\n\nfunction toggleRunSelection(runId) {\n if (selectedRunIds.has(runId)) {\n selectedRunIds.delete(runId);\n } else {\n selectedRunIds.add(runId);\n }\n renderRuns();\n}\n\nfunction toggleSelectAll() {\n const allDbRunIds = dbRuns.map(r => r.run_id);\n if (selectedRunIds.size === allDbRunIds.length && allDbRunIds.length > 0) {\n selectedRunIds.clear();\n } else {\n allDbRunIds.forEach(id => selectedRunIds.add(id));\n }\n renderRuns();\n}\n\nasync function deleteSelectedRuns() {\n if (selectedRunIds.size === 0) return;\n if (!confirm(`Delete ${selectedRunIds.size} run(s)? This cannot be undone.`)) return;\n const res = await fetch(\'/api/runs\', {\n method: \'DELETE\',\n headers: {\'Content-Type\': \'application/json\'},\n body: JSON.stringify({run_ids: Array.from(selectedRunIds)})\n });\n if (res.ok) {\n selectedRunIds.clear();\n await loadDbRuns();\n } else {\n alert(\'Failed to delete runs\');\n }\n}\n\nfunction renderRuns() {\n const container = document.getElementById(\'runs-list\');\n const activeRunIds = Object.keys(activeRuns).filter(id => activeRuns[id].status === \'running\');\n const allDbRunIds = dbRuns.map(r => r.run_id);\n const allSelected = allDbRunIds.length > 0 && selectedRunIds.size === allDbRunIds.length;\n\n let html = \'\';\n if (dbRuns.length > 0 || activeRunIds.length > 0) {\n html += `<div class="runs-toolbar">\n <label class="select-all-label">\n <input type="checkbox" ${allSelected ? \'checked\' : \'\'} onchange="toggleSelectAll()">\n Select all\n </label>\n <button class="btn-delete" ${selectedRunIds.size === 0 ? \'disabled\' : \'\'} onclick="deleteSelectedRuns()">\n Delete (${selectedRunIds.size})\n </button>\n </div>`;\n }\n\n activeRunIds.forEach(id => {\n const run = activeRuns[id];\n const progress = run.progress;\n html += `<div class="run-item">\n <div class="run-content">\n <div class="run-header">\n <span class="run-name">${run.strategy}</span>\n <span class="run-status running">running</span>\n </div>\n <div class="run-meta with-progress">${run.symbols.length} symbol${run.symbols.length !== 1 ? \'s\' : \'\'} · ${run.startDate || \'all\'} to ${run.endDate || \'all\'}</div>\n <div class="progress-bar"><div class="progress-fill" style="width: ${progress}%"></div></div>\n </div>\n </div>`;\n });\n\n dbRuns.forEach(r => {\n const config = r.config || {};\n const strategies = config.strategies ? config.strategies.join(\', \') : r.name;\n const symbols = config.symbols || [];\n const symbolCount = symbols.length;\n const startDate = config.start_date || \'-\';\n const endDate = config.end_date || \'-\';\n const timePart = r.run_id.slice(11, 19).replace(/-/g, \':\');\n const isSelected = selectedRunIds.has(r.run_id);\n const statusClass = r.status;\n html += `<div class="run-item ${isSelected ? \'selected\' : \'\'}">\n <input type="checkbox" class="run-checkbox" ${isSelected ? \'checked\' : \'\'} onchange="toggleRunSelection(\'${r.run_id}\')">\n <div class="run-content">\n <div class="run-header">\n <span class="run-name">${strategies} <span class="run-id">${timePart}</span></span>\n <span class="run-status ${statusClass}">${r.status}</span>\n </div>\n <div class="run-meta">${symbolCount} symbol${symbolCount !== 1 ? \'s\' : \'\'} · ${startDate} to ${endDate}</div>\n </div>\n </div>`;\n });\n\n if (html === \'\') {\n html = \'<div class="empty-runs"><p>No runs yet</p><p>Configure settings and click Run Backtest</p></div>\';\n }\n container.innerHTML = html;\n}\n\nasync function runBacktest() {\n const btn = document.getElementById(\'run-btn\');\n const rtype = getSelectedRtype();\n if (!rtype) {\n alert(\'Please select a bar period\');\n return;\n }\n if (!selectedPublisherId) {\n alert(\'Please select a publisher and dataset\');\n return;\n }\n if (selectedSymbols.length === 0) {\n alert(\'Please select at least one symbol\');\n return;\n }\n btn.disabled = true;\n\n const strategy = document.getElementById(\'strategy\').value;\n const startDate = document.getElementById(\'start-date\').value || null;\n const endDate = document.getElementById(\'end-date\').value || null;\n const barPeriod = RTYPE_LABELS[rtype] || \'Unknown\';\n\n const payload = {\n strategy: strategy,\n strategy_params: collectParams(),\n symbols: selectedSymbols,\n rtype: rtype,\n publisher_id: selectedPublisherId,\n start_date: startDate,\n end_date: endDate\n };\n\n try {\n const res = await fetch(\'/api/backtest/run\', {\n method: \'POST\', headers: {\'Content-Type\': \'application/json\'}, body: JSON.stringify(payload)\n });\n const data = await res.json();\n if (!res.ok) throw new Error(data.detail || \'Failed to start backtest\');\n const runId = data.run_id;\n\n activeRuns[runId] = {\n strategy: strategy,\n symbols: [...selectedSymbols],\n barPeriod: barPeriod,\n startDate: startDate,\n endDate: endDate,\n status: \'running\',\n progress: 10\n };\n renderRuns();\n btn.disabled = false;\n\n let progress = 10;\n const poll = setInterval(async () => {\n const r = await fetch(`/api/backtest/status/${runId}`);\n const d = await r.json();\n if (d.status === \'completed\') {\n clearInterval(poll);\n delete activeRuns[runId];\n await loadDbRuns();\n } else if (d.status.startsWith(\'error\')) {\n clearInterval(poll);\n delete activeRuns[runId];\n await loadDbRuns();\n } else {\n progress = Math.min(progress + 5, 90);\n activeRuns[runId].progress = progress;\n renderRuns();\n }\n }, 1000);\n } catch (e) {\n alert(`Error: ${e.message}`);\n btn.disabled = false;\n }\n}\n\ndocument.addEventListener(\'DOMContentLoaded\', () => {\n loadStrategies();\n loadCoverage();\n loadDbRuns();\n});\n' module-attribute

Source code in styles.py
  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
"""
CSS stylesheets and JavaScript for the dashboard UI.

This module contains embedded CSS and JavaScript as Python string constants. The styles
implement a dark-themed interface with a fixed sidebar navigation and responsive content
areas.

Constants:
    BASE_CSS: Global styles for layout, sidebar, cards, forms, and common elements.
    BACKTEST_CSS: Styles specific to the backtest configuration page.
    BACKTEST_JS: JavaScript for backtest page interactivity including:
        - Strategy and parameter loading
        - Publisher/dataset/symbol cascading selection
        - Symbol preset management
        - Date range validation
        - Backtest execution and run history display
"""

BASE_CSS = """
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    background: #0d1117;
    color: #e6edf3;
    min-height: 100vh;
    display: flex;
}
.sidebar {
    width: 220px;
    background: #161b22;
    border-right: 1px solid #30363d;
    min-height: 100vh;
    position: fixed;
    left: 0;
    top: 0;
    display: flex;
    flex-direction: column;
}
.sidebar-header {
    padding: 20px 16px;
    border-bottom: 1px solid #30363d;
}
.sidebar-header h1 {
    font-size: 16px;
    font-weight: 600;
    color: #e6edf3;
}
.sidebar-nav {
    padding: 12px 8px;
    flex: 1;
}
.sidebar-nav a {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 12px;
    color: #8b949e;
    text-decoration: none;
    font-size: 14px;
    border-radius: 6px;
    margin-bottom: 2px;
}
.sidebar-nav a:hover {
    background: #21262d;
    color: #e6edf3;
}
.sidebar-nav a.active {
    background: #21262d;
    color: #e6edf3;
}
.sidebar-nav svg {
    width: 16px;
    height: 16px;
    flex-shrink: 0;
}
.main-content {
    margin-left: 220px;
    flex: 1;
    min-height: 100vh;
}
.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 32px 24px;
}
.card {
    background: #161b22;
    border: 1px solid #30363d;
    border-radius: 8px;
    padding: 24px;
    margin-bottom: 16px;
}
.card h2 {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
    color: #e6edf3;
}
.empty-state {
    text-align: center;
    padding: 48px;
    color: #8b949e;
}
.empty-state p {
    margin-top: 8px;
    font-size: 14px;
}
"""

BACKTEST_CSS = """
.container { max-width: none; height: 100vh; padding: 24px; display: flex; flex-direction: column; box-sizing: border-box; }
.backtest-layout { display: flex; gap: 24px; flex: 1; min-height: 0; }
.backtest-left { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.backtest-right { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.backtest-left .card, .backtest-right .card { flex: 1; display: flex; flex-direction: column; margin-bottom: 0; overflow: hidden; }
.backtest-right .runs-list { flex: 1; overflow-y: auto; }
.form-group { margin-bottom: 16px; }
.form-group label { display: block; margin-bottom: 6px; font-size: 14px; color: #8b949e; }
.form-group select, .form-group input {
    width: 100%; padding: 8px 12px; background: #0d1117; border: 1px solid #30363d;
    border-radius: 6px; color: #e6edf3; font-size: 14px;
}
.form-group select:focus, .form-group input:focus { outline: none; border-color: #58a6ff; }
.params-container { margin-top: 12px; padding: 12px; background: #0d1117; border-radius: 6px; }
.param-row { display: flex; gap: 12px; margin-bottom: 8px; align-items: center; }
.param-row label { min-width: 120px; font-size: 13px; }
.param-row input, .param-row select { flex: 1; }
.btn { padding: 10px 20px; background: #238636; border: none; border-radius: 6px;
    color: #fff; font-size: 14px; cursor: pointer; width: 100%; }
.btn:hover { background: #2ea043; }
.btn:disabled { background: #30363d; cursor: not-allowed; }
.date-row { display: flex; gap: 12px; }
.date-row .form-group { flex: 1; margin-bottom: 0; }
.symbol-section { background: #0d1117; border-radius: 6px; padding: 12px; }
.publisher-row { display: flex; gap: 8px; margin-bottom: 12px; }
.publisher-row select { flex: 1; }
.preset-row { display: flex; gap: 8px; margin-bottom: 12px; align-items: center; }
.preset-row select { flex: 1; }
.preset-row input { flex: 1; }
.preset-row .btn-sm { padding: 6px 12px; font-size: 12px; width: auto; cursor: not-allowed; }
.preset-row .btn-secondary { background: #30363d; }
.preset-row .btn-secondary.active { background: #238636; cursor: pointer; }
.preset-row .btn-secondary.active:hover { background: #2ea043; }
.preset-row .btn-danger { background: #30363d; }
.preset-row .btn-danger.active { background: #da3633; cursor: pointer; }
.preset-row .btn-danger.active:hover { background: #f85149; }
.search-row { display: flex; gap: 8px; margin-bottom: 8px; }
.search-row input { flex: 1; }
.search-results { max-height: 150px; overflow-y: auto; border: 1px solid #30363d; border-radius: 4px; margin-bottom: 12px; }
.search-results:empty { display: none; }
.search-result { display: flex; justify-content: space-between; align-items: center; padding: 6px 10px; border-bottom: 1px solid #21262d; cursor: pointer; }
.search-result:last-child { border-bottom: none; }
.search-result:hover { background: #161b22; }
.search-result .symbol { font-family: monospace; }
.selected-symbols { display: flex; flex-wrap: wrap; gap: 6px; min-height: 32px; max-height: 150px; overflow-y: auto; }
.selected-tag { display: inline-flex; align-items: center; gap: 4px; background: #238636; color: #fff; padding: 4px 8px; border-radius: 4px; font-size: 12px; font-family: monospace; }
.selected-tag .remove { cursor: pointer; opacity: 0.7; }
.selected-tag .remove:hover { opacity: 1; }
.selected-label { font-size: 13px; color: #8b949e; margin-bottom: 6px; }
.section-header { font-size: 14px; color: #8b949e; margin-bottom: 6px; margin-top: 8px; }
.runs-list { display: flex; flex-direction: column; gap: 12px; }
.run-item { background: #0d1117; border: 1px solid #30363d; border-radius: 6px; padding: 12px; display: flex; gap: 12px; align-items: flex-start; }
.run-item.selected { border-color: #58a6ff; }
.run-checkbox { flex-shrink: 0; margin-top: 2px; width: 16px; height: 16px; accent-color: #58a6ff; cursor: pointer; }
.run-content { flex: 1; min-width: 0; }
.run-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
.run-name { font-family: monospace; font-size: 13px; color: #e6edf3; }
.run-id { color: #8b949e; font-size: 11px; margin-left: 6px; }
.run-status { font-size: 12px; font-weight: 500; padding: 2px 8px; border-radius: 10px; }
.run-status.running { background: #9e6a03; color: #fff; }
.run-status.completed { background: #238636; color: #fff; }
.run-status.failed { background: #da3633; color: #fff; }
.run-status.cancelled { background: #30363d; color: #8b949e; }
.run-status.error { background: #da3633; color: #fff; }
.run-meta { font-size: 12px; color: #8b949e; }
.run-meta.with-progress { margin-bottom: 8px; }
.progress-bar { height: 6px; background: #30363d; border-radius: 3px; overflow: hidden; }
.progress-fill { height: 100%; background: #58a6ff; transition: width 0.3s ease; }
.progress-fill.completed { background: #238636; }
.progress-fill.error { background: #da3633; }
.empty-runs { text-align: center; padding: 48px 24px; color: #8b949e; }
.empty-runs p { font-size: 14px; }
.runs-toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; padding-bottom: 12px; border-bottom: 1px solid #30363d; }
.runs-toolbar .select-all-label { display: flex; align-items: center; gap: 8px; font-size: 13px; color: #8b949e; cursor: pointer; }
.runs-toolbar .select-all-label input { width: 16px; height: 16px; accent-color: #58a6ff; cursor: pointer; }
.btn-delete { padding: 6px 12px; background: #da3633; border: none; border-radius: 6px; color: #fff; font-size: 13px; cursor: pointer; }
.btn-delete:hover { background: #f85149; }
.btn-delete:disabled { background: #30363d; cursor: not-allowed; color: #8b949e; }
"""

BACKTEST_JS = """
let strategyParams = [];
let coverageData = [];
let availableRtypes = [];
let symbolsForRtype = {};
let symbolCoverageForRtype = {};
let selectedSymbols = [];
let presets = [];
let globalMinDate = null;
let globalMaxDate = null;
let dbRuns = [];
let activeRuns = {};
let selectedRunIds = new Set();
let publishers = [];
let datasets = [];
let selectedPublisherId = null;

const RTYPE_LABELS = {32: 'Second', 33: 'Minute', 34: 'Hour', 35: 'Day'};

function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

async function loadPublishers() {
    const rtype = getSelectedRtype();
    const url = rtype ? `/api/secmaster/publishers?rtype=${rtype}` : '/api/secmaster/publishers';
    const res = await fetch(url);
    const data = await res.json();
    publishers = data.publishers || [];
    const sel = document.getElementById('publisher-name');
    sel.innerHTML = '<option value="">-- Select Publisher --</option>';
    publishers.forEach(p => sel.innerHTML += `<option value="${p}">${capitalize(p)}</option>`);
}

async function onPublisherChange() {
    const name = document.getElementById('publisher-name').value;
    const rtype = getSelectedRtype();
    const datasetSel = document.getElementById('publisher-dataset');
    datasetSel.innerHTML = '<option value="">-- Select Dataset --</option>';
    datasets = [];
    selectedPublisherId = null;
    document.getElementById('symbol-selection').style.display = 'none';
    selectedSymbols = [];
    renderSelectedSymbols();
    updateDateRange();
    if (!name) return;
    const url = rtype
        ? `/api/secmaster/publishers/${encodeURIComponent(name)}/datasets?rtype=${rtype}`
        : `/api/secmaster/publishers/${encodeURIComponent(name)}/datasets`;
    const res = await fetch(url);
    const data = await res.json();
    datasets = data.datasets || [];
    datasets.forEach(d => datasetSel.innerHTML += `<option value="${d.publisher_id}">${d.dataset}</option>`);
}

async function onDatasetChange() {
    const pubId = document.getElementById('publisher-dataset').value;
    selectedPublisherId = pubId ? parseInt(pubId) : null;
    selectedSymbols = [];
    renderSelectedSymbols();
    updateDateRange();
    document.getElementById('symbol-search').value = '';
    document.getElementById('search-results').innerHTML = '';
    if (selectedPublisherId) {
        await loadCoverageForPublisher(selectedPublisherId);
        document.getElementById('symbol-selection').style.display = 'block';
        await loadPresets();
    } else {
        document.getElementById('symbol-selection').style.display = 'none';
    }
}

async function loadCoverageForPublisher(publisherId) {
    const rtype = getSelectedRtype();
    const url = `/api/secmaster/symbols_coverage?publisher_id=${publisherId}&rtype=${rtype}`;
    const res = await fetch(url);
    const data = await res.json();
    coverageData = data.symbols || [];
    symbolsForRtype = {};
    symbolCoverageForRtype = {};
    coverageData.forEach(row => {
        if (!symbolsForRtype[row.rtype]) {
            symbolsForRtype[row.rtype] = [];
            symbolCoverageForRtype[row.rtype] = {};
        }
        symbolsForRtype[row.rtype].push(row.symbol);
        symbolCoverageForRtype[row.rtype][row.symbol] = {min_ts: row.min_ts, max_ts: row.max_ts};
    });
}

async function loadPresets() {
    const res = await fetch('/api/presets');
    const data = await res.json();
    presets = data.presets || [];
    await filterAndRenderPresets();
}

async function filterAndRenderPresets() {
    const sel = document.getElementById('preset-select');
    sel.innerHTML = '<option value="">-- Select Preset --</option>';
    const rtype = getSelectedRtype();
    const availableSymbols = symbolsForRtype[rtype] || [];
    for (const p of presets) {
        const res = await fetch(`/api/presets/${encodeURIComponent(p)}`);
        const data = await res.json();
        const hasAvailable = (data.symbols || []).some(s => availableSymbols.includes(s));
        if (hasAvailable) {
            sel.innerHTML += `<option value="${p}">${p}</option>`;
        }
    }
    updateButtonStates();
}

async function loadPreset() {
    const name = document.getElementById('preset-select').value;
    updateButtonStates();
    if (!name) {
        selectedSymbols = [];
        renderSelectedSymbols();
        updateDateRange();
        return;
    }
    const rtype = getSelectedRtype();
    const symbols = symbolsForRtype[rtype] || [];
    const res = await fetch(`/api/presets/${encodeURIComponent(name)}`);
    const data = await res.json();
    if (data.symbols) {
        selectedSymbols = data.symbols.filter(s => symbols.includes(s));
        renderSelectedSymbolsKeepPreset();
        updateDateRange();
    }
}

async function savePreset() {
    const nameInput = document.getElementById('preset-name');
    const name = nameInput.value.trim();
    if (!name) { alert('Enter a preset name'); return; }
    if (selectedSymbols.length === 0) { alert('Select at least one symbol'); return; }
    const exists = presets.includes(name);
    const method = exists ? 'PUT' : 'POST';
    const url = exists ? `/api/presets/${encodeURIComponent(name)}` : '/api/presets';
    await fetch(url, {
        method, headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({name, symbols: selectedSymbols})
    });
    nameInput.value = '';
    await loadPresets();
    document.getElementById('preset-select').value = name;
}

async function deletePreset() {
    const name = document.getElementById('preset-select').value;
    if (!name) { alert('Select a preset to delete'); return; }
    if (!confirm(`Delete preset "${name}"?`)) return;
    await fetch(`/api/presets/${encodeURIComponent(name)}`, {method: 'DELETE'});
    await loadPresets();
    selectedSymbols = [];
    renderSelectedSymbols();
    updateDateRange();
}

function updateButtonStates() {
    const runBtn = document.getElementById('run-btn');
    const saveBtn = document.getElementById('preset-save-btn');
    const deleteBtn = document.getElementById('preset-delete-btn');
    const presetSelect = document.getElementById('preset-select');
    const presetNameInput = document.getElementById('preset-name');
    const strategyEl = document.getElementById('strategy');
    const barPeriodEl = document.getElementById('bar-period');
    if (!runBtn) return;
    const rtype = barPeriodEl ? parseInt(barPeriodEl.value) || null : null;
    const strategy = strategyEl ? strategyEl.value : '';
    const canRun = strategy && rtype && selectedPublisherId && selectedSymbols.length > 0;
    runBtn.disabled = !canRun;
    const hasPresetSelected = !!(presetSelect && presetSelect.value);
    const hasPresetName = !!(presetNameInput && presetNameInput.value.trim().length > 0);
    const canSave = hasPresetName && selectedSymbols.length > 0;
    if (saveBtn) {
        saveBtn.classList.toggle('active', canSave);
    }
    if (deleteBtn) {
        deleteBtn.classList.toggle('active', hasPresetSelected);
    }
}

async function loadStrategies() {
    const res = await fetch('/api/strategies');
    const data = await res.json();
    const sel = document.getElementById('strategy');
    data.strategies.forEach(s => sel.innerHTML += `<option value="${s.id}">${s.name}</option>`);
    if (data.strategies.length > 0) {
        sel.value = data.strategies[0].id;
        loadStrategyParams();
    }
}

async function loadStrategyParams() {
    const name = document.getElementById('strategy').value;
    if (!name) return;
    const res = await fetch(`/api/strategies/${name}`);
    const data = await res.json();
    strategyParams = data.parameters || [];
    renderParams();
}

function formatParamName(name) {
    let result = name.replace(/_/g, ' ');
    result = result.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2');
    result = result.replace(/([a-z])([A-Z])/g, '$1 $2');
    return result.split(' ').map(word => {
        if (word === word.toUpperCase() && word.length > 1) return word;
        return word.charAt(0).toUpperCase() + word.slice(1);
    }).join(' ');
}

function renderParams() {
    const container = document.getElementById('strategy-params');
    const filtered = strategyParams.filter(p => p.name !== 'bar_period');
    if (filtered.length === 0) {
        container.innerHTML = '<div style="color: #8b949e; font-size: 13px;">No parameters</div>';
        return;
    }
    container.innerHTML = filtered.map(p => {
        const label = formatParamName(p.name);
        if (p.choices && p.choices.length > 0) {
            const opts = p.choices.map(c => `<option value="${c}" ${c === p.default ? 'selected' : ''}>${c}</option>`).join('');
            return `<div class="param-row"><label>${label}</label><select id="sp_${p.name}">${opts}</select></div>`;
        }
        const inputType = p.type === 'bool' ? 'checkbox' : (p.type === 'float' || p.type === 'int' ? 'number' : 'text');
        const step = p.step || (p.type === 'float' ? '0.01' : '1');
        const checked = p.type === 'bool' && p.default ? 'checked' : '';
        return `<div class="param-row"><label>${label}</label><input type="${inputType}" id="sp_${p.name}" value="${p.default}" step="${step}" ${p.min !== undefined ? `min="${p.min}"` : ''} ${p.max !== undefined ? `max="${p.max}"` : ''} ${checked}></div>`;
    }).join('');
}

function tsToDate(ts) {
    const ms = Math.floor(ts / 1000000);
    const d = new Date(ms);
    return d.toISOString().split('T')[0];
}

async function loadCoverage() {
    const res = await fetch('/api/secmaster/symbols_coverage');
    const data = await res.json();
    coverageData = data.symbols || [];
    const rtypeSet = new Set();
    coverageData.forEach(row => rtypeSet.add(row.rtype));
    availableRtypes = Array.from(rtypeSet).sort((a, b) => a - b);
    populateBarPeriodDropdown();
}

function populateBarPeriodDropdown() {
    const sel = document.getElementById('bar-period');
    sel.innerHTML = '<option value="">-- Select bar period --</option>';
    availableRtypes.forEach(rt => {
        const label = RTYPE_LABELS[rt] || `rtype ${rt}`;
        sel.innerHTML += `<option value="${rt}">${label}</option>`;
    });
}

function onBarPeriodChange() {
    selectedSymbols = [];
    selectedPublisherId = null;
    symbolsForRtype = {};
    symbolCoverageForRtype = {};
    renderSelectedSymbols();
    updateDateRange();
    const rtype = document.getElementById('bar-period').value;
    const section = document.getElementById('symbols-section');
    const symbolSelection = document.getElementById('symbol-selection');
    document.getElementById('publisher-name').value = '';
    document.getElementById('publisher-dataset').innerHTML = '<option value="">-- Select Dataset --</option>';
    if (rtype) {
        section.style.display = 'block';
        loadPublishers();
    } else {
        section.style.display = 'none';
    }
    symbolSelection.style.display = 'none';
    document.getElementById('symbol-search').value = '';
    document.getElementById('search-results').innerHTML = '';
}

function getSelectedRtype() {
    return parseInt(document.getElementById('bar-period').value) || null;
}

function searchSymbols() {
    const query = document.getElementById('symbol-search').value.toLowerCase();
    const container = document.getElementById('search-results');
    const rtype = getSelectedRtype();
    if (!query || !rtype) {
        container.innerHTML = '';
        return;
    }
    const symbols = symbolsForRtype[rtype] || [];
    const matches = symbols.filter(s => s.toLowerCase().includes(query) && !selectedSymbols.includes(s)).slice(0, 20);
    container.innerHTML = matches.map(s =>
        `<div class="search-result" onclick="addSymbol('${s}')"><span class="symbol">${s}</span></div>`
    ).join('');
}

function addSymbol(symbol) {
    if (!selectedSymbols.includes(symbol)) {
        selectedSymbols.push(symbol);
        document.getElementById('preset-select').value = '';
        renderSelectedSymbols();
        updateDateRange();
    }
    document.getElementById('symbol-search').value = '';
    document.getElementById('search-results').innerHTML = '';
}

function removeSymbol(symbol) {
    selectedSymbols = selectedSymbols.filter(s => s !== symbol);
    document.getElementById('preset-select').value = '';
    renderSelectedSymbols();
    updateDateRange();
}

function renderSelectedSymbols() {
    const container = document.getElementById('selected-symbols');
    document.getElementById('selected-label').textContent = `Selected (${selectedSymbols.length}):`;
    container.innerHTML = selectedSymbols.map(s =>
        `<span class="selected-tag">${s}<span class="remove" onclick="removeSymbol('${s}')">&times;</span></span>`
    ).join('');
    updateButtonStates();
}

function renderSelectedSymbolsKeepPreset() {
    const container = document.getElementById('selected-symbols');
    document.getElementById('selected-label').textContent = `Selected (${selectedSymbols.length}):`;
    container.innerHTML = selectedSymbols.map(s =>
        `<span class="selected-tag">${s}<span class="remove" onclick="removeSymbol('${s}')">&times;</span></span>`
    ).join('');
    updateButtonStates();
}

function updateDateRange() {
    const startInput = document.getElementById('start-date');
    const endInput = document.getElementById('end-date');
    const rtype = getSelectedRtype();
    if (selectedSymbols.length === 0 || !rtype) {
        globalMinDate = null;
        globalMaxDate = null;
        startInput.value = '';
        endInput.value = '';
        startInput.removeAttribute('min');
        startInput.removeAttribute('max');
        endInput.removeAttribute('min');
        endInput.removeAttribute('max');
        return;
    }
    const coverage = symbolCoverageForRtype[rtype] || {};
    let minTs = null, maxTs = null;
    selectedSymbols.forEach(s => {
        const cov = coverage[s];
        if (cov) {
            if (minTs === null || cov.min_ts < minTs) minTs = cov.min_ts;
            if (maxTs === null || cov.max_ts > maxTs) maxTs = cov.max_ts;
        }
    });
    if (minTs === null) return;
    globalMinDate = tsToDate(minTs);
    globalMaxDate = tsToDate(maxTs);
    startInput.min = globalMinDate;
    startInput.max = globalMaxDate;
    startInput.value = globalMinDate;
    endInput.min = globalMinDate;
    endInput.max = globalMaxDate;
    endInput.value = globalMaxDate;
}

function clampDate(inputId) {
    if (!globalMinDate || !globalMaxDate) return;
    const input = document.getElementById(inputId);
    if (input.value < globalMinDate) input.value = globalMinDate;
    if (input.value > globalMaxDate) input.value = globalMaxDate;
}

function collectParams() {
    const result = {};
    strategyParams.forEach(p => {
        const el = document.getElementById(`sp_${p.name}`);
        if (!el) return;
        if (p.type === 'bool') result[p.name] = el.checked;
        else if (p.type === 'int') result[p.name] = parseInt(el.value);
        else if (p.type === 'float') result[p.name] = parseFloat(el.value);
        else result[p.name] = el.value;
    });
    return result;
}

async function loadDbRuns() {
    const res = await fetch('/api/runs');
    const data = await res.json();
    dbRuns = data.runs || [];
    renderRuns();
}

function toggleRunSelection(runId) {
    if (selectedRunIds.has(runId)) {
        selectedRunIds.delete(runId);
    } else {
        selectedRunIds.add(runId);
    }
    renderRuns();
}

function toggleSelectAll() {
    const allDbRunIds = dbRuns.map(r => r.run_id);
    if (selectedRunIds.size === allDbRunIds.length && allDbRunIds.length > 0) {
        selectedRunIds.clear();
    } else {
        allDbRunIds.forEach(id => selectedRunIds.add(id));
    }
    renderRuns();
}

async function deleteSelectedRuns() {
    if (selectedRunIds.size === 0) return;
    if (!confirm(`Delete ${selectedRunIds.size} run(s)? This cannot be undone.`)) return;
    const res = await fetch('/api/runs', {
        method: 'DELETE',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({run_ids: Array.from(selectedRunIds)})
    });
    if (res.ok) {
        selectedRunIds.clear();
        await loadDbRuns();
    } else {
        alert('Failed to delete runs');
    }
}

function renderRuns() {
    const container = document.getElementById('runs-list');
    const activeRunIds = Object.keys(activeRuns).filter(id => activeRuns[id].status === 'running');
    const allDbRunIds = dbRuns.map(r => r.run_id);
    const allSelected = allDbRunIds.length > 0 && selectedRunIds.size === allDbRunIds.length;

    let html = '';
    if (dbRuns.length > 0 || activeRunIds.length > 0) {
        html += `<div class="runs-toolbar">
            <label class="select-all-label">
                <input type="checkbox" ${allSelected ? 'checked' : ''} onchange="toggleSelectAll()">
                Select all
            </label>
            <button class="btn-delete" ${selectedRunIds.size === 0 ? 'disabled' : ''} onclick="deleteSelectedRuns()">
                Delete (${selectedRunIds.size})
            </button>
        </div>`;
    }

    activeRunIds.forEach(id => {
        const run = activeRuns[id];
        const progress = run.progress;
        html += `<div class="run-item">
            <div class="run-content">
                <div class="run-header">
                    <span class="run-name">${run.strategy}</span>
                    <span class="run-status running">running</span>
                </div>
                <div class="run-meta with-progress">${run.symbols.length} symbol${run.symbols.length !== 1 ? 's' : ''} · ${run.startDate || 'all'} to ${run.endDate || 'all'}</div>
                <div class="progress-bar"><div class="progress-fill" style="width: ${progress}%"></div></div>
            </div>
        </div>`;
    });

    dbRuns.forEach(r => {
        const config = r.config || {};
        const strategies = config.strategies ? config.strategies.join(', ') : r.name;
        const symbols = config.symbols || [];
        const symbolCount = symbols.length;
        const startDate = config.start_date || '-';
        const endDate = config.end_date || '-';
        const timePart = r.run_id.slice(11, 19).replace(/-/g, ':');
        const isSelected = selectedRunIds.has(r.run_id);
        const statusClass = r.status;
        html += `<div class="run-item ${isSelected ? 'selected' : ''}">
            <input type="checkbox" class="run-checkbox" ${isSelected ? 'checked' : ''} onchange="toggleRunSelection('${r.run_id}')">
            <div class="run-content">
                <div class="run-header">
                    <span class="run-name">${strategies} <span class="run-id">${timePart}</span></span>
                    <span class="run-status ${statusClass}">${r.status}</span>
                </div>
                <div class="run-meta">${symbolCount} symbol${symbolCount !== 1 ? 's' : ''} · ${startDate} to ${endDate}</div>
            </div>
        </div>`;
    });

    if (html === '') {
        html = '<div class="empty-runs"><p>No runs yet</p><p>Configure settings and click Run Backtest</p></div>';
    }
    container.innerHTML = html;
}

async function runBacktest() {
    const btn = document.getElementById('run-btn');
    const rtype = getSelectedRtype();
    if (!rtype) {
        alert('Please select a bar period');
        return;
    }
    if (!selectedPublisherId) {
        alert('Please select a publisher and dataset');
        return;
    }
    if (selectedSymbols.length === 0) {
        alert('Please select at least one symbol');
        return;
    }
    btn.disabled = true;

    const strategy = document.getElementById('strategy').value;
    const startDate = document.getElementById('start-date').value || null;
    const endDate = document.getElementById('end-date').value || null;
    const barPeriod = RTYPE_LABELS[rtype] || 'Unknown';

    const payload = {
        strategy: strategy,
        strategy_params: collectParams(),
        symbols: selectedSymbols,
        rtype: rtype,
        publisher_id: selectedPublisherId,
        start_date: startDate,
        end_date: endDate
    };

    try {
        const res = await fetch('/api/backtest/run', {
            method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload)
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.detail || 'Failed to start backtest');
        const runId = data.run_id;

        activeRuns[runId] = {
            strategy: strategy,
            symbols: [...selectedSymbols],
            barPeriod: barPeriod,
            startDate: startDate,
            endDate: endDate,
            status: 'running',
            progress: 10
        };
        renderRuns();
        btn.disabled = false;

        let progress = 10;
        const poll = setInterval(async () => {
            const r = await fetch(`/api/backtest/status/${runId}`);
            const d = await r.json();
            if (d.status === 'completed') {
                clearInterval(poll);
                delete activeRuns[runId];
                await loadDbRuns();
            } else if (d.status.startsWith('error')) {
                clearInterval(poll);
                delete activeRuns[runId];
                await loadDbRuns();
            } else {
                progress = Math.min(progress + 5, 90);
                activeRuns[runId].progress = progress;
                renderRuns();
            }
        }, 1000);
    } catch (e) {
        alert(`Error: ${e.message}`);
        btn.disabled = false;
    }
}

document.addEventListener('DOMContentLoaded', () => {
    loadStrategies();
    loadCoverage();
    loadDbRuns();
});
"""