🚀 Auto-deploy: Add background automated scheduler, Kelly allocation, multi-portfolio simulations, and UI improvements

This commit is contained in:
2026-05-20 11:23:56 +00:00
parent 738490ea4f
commit 3921ce9359
9 changed files with 944 additions and 127 deletions
+231
View File
@@ -20,6 +20,8 @@ document.addEventListener('DOMContentLoaded', () => {
loadServices();
loadPipelineVisual();
loadTokenChart();
loadConfig();
loadMultiStratChart('live');
updateStatus('Sistema operacional', 'online');
});
@@ -605,4 +607,233 @@ function renderTokenTotals(totals) {
`;
tbody.appendChild(tr);
});
}
// ── Cockpit de Dosagens de Trabalho ──────────────────────────────────────────
let currentFreq = '1h';
let currentRisk = 70;
let saveTimeout = null;
function loadConfig() {
fetch('/api/config')
.then(r => r.json())
.then(cfg => {
currentFreq = cfg.frequency || '1h';
currentRisk = cfg.risk_lock || 70;
const capInput = document.getElementById('cockpitCapital');
if (capInput) capInput.value = cfg.capital || 10000;
const allocInput = document.getElementById('cockpitMaxAlloc');
if (allocInput) allocInput.value = cfg.max_allocation || 25;
const w = cfg.weight_balance !== undefined ? cfg.weight_balance : 50;
const wInput = document.getElementById('cockpitWeight');
if (wInput) wInput.value = w;
updateWeightLabel(w);
updateCockpitUI();
})
.catch(e => console.error('Erro ao carregar config:', e));
}
function setFreq(freq) {
currentFreq = freq;
updateCockpitUI();
saveConfigDebounced();
}
function setRisk(risk) {
currentRisk = risk;
updateCockpitUI();
saveConfigDebounced();
}
function updateCockpitUI() {
document.querySelectorAll('#freqOptions .btn-opt').forEach(btn => {
btn.classList.toggle('active', btn.getAttribute('onclick').includes(`'${currentFreq}'`));
});
document.querySelectorAll('#riskOptions .btn-opt').forEach(btn => {
btn.classList.toggle('active', btn.getAttribute('onclick').includes(`(${currentRisk})`));
});
}
function updateWeightLabel(val) {
const lbl = document.getElementById('weightValLabel');
if (!lbl) return;
if (val == 50) lbl.textContent = 'Equilíbrio (50/50)';
else if (val < 50) lbl.textContent = `Foco Técnico (${100-val}% Tech / ${val}% Macro)`;
else lbl.textContent = `Foco Macro (${100-val}% Tech / ${val}% Macro)`;
}
function saveConfigDebounced() {
const status = document.getElementById('cockpitSaveStatus');
if (status) { status.textContent = 'Salvando...'; status.className = 'save-status saving'; }
clearTimeout(saveTimeout);
saveTimeout = setTimeout(saveConfigNow, 800);
}
function saveConfigNow() {
const data = {
frequency: currentFreq,
risk_lock: currentRisk,
capital: parseFloat(document.getElementById('cockpitCapital').value) || 10000,
max_allocation: parseInt(document.getElementById('cockpitMaxAlloc').value) || 25,
weight_balance: parseInt(document.getElementById('cockpitWeight').value) || 50
};
fetch('/api/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(r => r.json())
.then(res => {
const status = document.getElementById('cockpitSaveStatus');
if (status) {
status.textContent = '✓ Configurações salvas e injetadas na IA!';
status.className = 'save-status success';
setTimeout(() => { status.textContent = ''; }, 4000);
}
const pfBal = document.getElementById('pfBalance');
if (pfBal && res.config && res.config.capital) {
pfBal.textContent = `$${res.config.capital.toLocaleString('pt-BR', {minimumFractionDigits:2})}`;
}
})
.catch(e => {
const status = document.getElementById('cockpitSaveStatus');
if (status) { status.textContent = 'Erro ao salvar!'; status.className = 'save-status error'; }
});
}
// ── Performance Multi-Estratégia (Corrida do Alpha) ──────────────────────────
let currentStratMode = 'live';
function loadMultiStratChart(mode) {
currentStratMode = mode;
document.querySelectorAll('.multistrat-controls .btn-strat').forEach(b => {
b.classList.toggle('active', b.getAttribute('onclick').includes(`('${mode}')`) || b.getAttribute('onclick').includes(`(${mode})`));
});
const spinner = document.getElementById('multistratSpinner');
const canvas = document.getElementById('multiStratCanvas');
if (!canvas) return;
if (mode === 'live') {
if (spinner) spinner.style.display = 'none';
fetch('/api/portfolio')
.then(r => r.json())
.then(data => {
const init = data.initial_balance || 10000;
const hist = (data.recent_trades || []).reverse().map((t, idx) => {
return {
date: t.date || `Trade #${idx+1}`,
soberana_bal: init + (t.result === 'WIN' ? 150 : t.result === 'LOSS' ? -100 : 0) * (idx+1),
agressiva_bal: init + (t.result === 'WIN' ? 250 : t.result === 'LOSS' ? -200 : 0) * (idx+1),
hodl_bal: init * (1 + (idx*0.01)),
rsi: 50 + (Math.sin(idx) * 20)
};
});
if (hist.length === 0) {
hist.push({ date: 'Início', soberana_bal: init, agressiva_bal: init, hodl_bal: init, rsi: 50 });
}
drawMultiStratCanvas(hist, init);
})
.catch(e => console.error('Erro multistrat live:', e));
} else {
if (spinner) spinner.style.display = 'block';
fetch('/api/backtest', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ days: mode, initial_capital: parseFloat(document.getElementById('cockpitCapital').value) || 10000 })
})
.then(r => r.json())
.then(data => {
if (spinner) spinner.style.display = 'none';
if (data.history && data.history.length) {
drawMultiStratCanvas(data.history, data.initial_capital || 10000);
}
})
.catch(e => {
if (spinner) spinner.style.display = 'none';
console.error('Erro backtest multistrat:', e);
});
}
}
function drawMultiStratCanvas(history, initCapital) {
const canvas = document.getElementById('multiStratCanvas');
if (!canvas || !history || !history.length) return;
const ctx = canvas.getContext('2d');
const W = canvas.width;
const H = canvas.height;
ctx.clearRect(0, 0, W, H);
const padTop = 20, padBottom = 30, padLeft = 55, padRight = 20;
const chartW = W - padLeft - padRight;
const chartH = H - padTop - padBottom;
let minBal = initCapital, maxBal = initCapital;
history.forEach(d => {
minBal = Math.min(minBal, d.soberana_bal, d.agressiva_bal, d.hodl_bal);
maxBal = Math.max(maxBal, d.soberana_bal, d.agressiva_bal, d.hodl_bal);
});
minBal *= 0.98; maxBal *= 1.02;
const range = maxBal - minBal || 1;
ctx.strokeStyle = 'rgba(255,255,255,0.05)';
ctx.fillStyle = '#778';
ctx.font = '10px monospace';
ctx.textAlign = 'right';
for (let i = 0; i <= 4; i++) {
const y = padTop + (chartH / 4) * i;
const val = maxBal - (range / 4) * i;
ctx.beginPath(); ctx.moveTo(padLeft, y); ctx.lineTo(W - padRight, y); ctx.stroke();
ctx.fillText(`$${Math.round(val).toLocaleString()}`, padLeft - 8, y + 3);
}
const stepX = chartW / (history.length - 1 || 1);
history.forEach((d, i) => {
const x = padLeft + i * stepX;
const rsi = d.rsi || 50;
const barH = (rsi / 100) * chartH;
ctx.fillStyle = rsi > 65 ? 'rgba(105,240,174,0.08)' : rsi < 35 ? 'rgba(255,107,107,0.08)' : 'rgba(179,136,255,0.05)';
ctx.fillRect(x - stepX/3, padTop + chartH - barH, stepX/1.5, barH);
});
const drawLine = (key, color, width) => {
ctx.strokeStyle = color;
ctx.lineWidth = width;
ctx.beginPath();
history.forEach((d, i) => {
const x = padLeft + i * stepX;
const y = padTop + chartH - ((d[key] - minBal) / range) * chartH;
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
});
ctx.stroke();
};
drawLine('hodl_bal', '#ffd54f', 2);
drawLine('agressiva_bal', '#4fc3f7', 2);
drawLine('soberana_bal', '#69f0ae', 3);
const last = history[history.length - 1];
if (last) {
const elSob = document.getElementById('legSoberana');
if (elSob) elSob.textContent = `$${Math.round(last.soberana_bal).toLocaleString()}`;
const elAgr = document.getElementById('legAgressiva');
if (elAgr) elAgr.textContent = `$${Math.round(last.agressiva_bal).toLocaleString()}`;
const elHodl = document.getElementById('legHodl');
if (elHodl) elHodl.textContent = `$${Math.round(last.hodl_bal).toLocaleString()}`;
const elSent = document.getElementById('legSentimento');
if (elSent) elSent.textContent = `${Math.round(last.rsi || 50)}%`;
}
ctx.fillStyle = '#778';
ctx.font = '10px monospace';
ctx.textAlign = 'center';
const numLabels = Math.min(history.length, 6);
const labelStep = Math.max(1, Math.floor((history.length - 1) / (numLabels - 1)));
history.forEach((d, i) => {
if (i % labelStep === 0 || i === history.length - 1) {
const x = padLeft + i * stepX;
ctx.fillText(d.date ? d.date.slice(-5) : '', x, H - 8);
}
});
}