First commit
This commit is contained in:
@@ -0,0 +1,650 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="dark">
|
||||
<meta name="theme-color" content="#0b0d12">
|
||||
<title>Yote-In-Vest</title>
|
||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%230b0d12'/%3E%3Cpath d='M6 22l6-7 5 4 9-11' fill='none' stroke='%23f0a145' stroke-width='3' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E">
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg:#0b0d12; --surface:#12151c; --surface-2:#181c26; --line:#252a38; --line-soft:#1b2030;
|
||||
--ink:#e9ebf1; --muted:#8c94a8; --faint:#5f677c;
|
||||
--accent:#f0a145; --accent-soft:rgba(240,161,69,.14);
|
||||
--up:#3fd08f; --down:#ff6b6b; --warn:#f2b84b; --info:#7aa7ff;
|
||||
--radius:14px;
|
||||
}
|
||||
* { box-sizing:border-box; }
|
||||
html { background:var(--bg); }
|
||||
body { margin:0; background:radial-gradient(1200px 500px at 85% -10%, rgba(240,161,69,.07), transparent 60%), var(--bg);
|
||||
color:var(--ink); font:15px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
-webkit-font-smoothing:antialiased; }
|
||||
.wrap { max-width:1180px; margin:0 auto; padding:22px 16px 56px; }
|
||||
a, button, input { font:inherit; }
|
||||
:focus-visible { outline:2px solid var(--accent); outline-offset:2px; border-radius:6px; }
|
||||
|
||||
/* header */
|
||||
header { display:flex; flex-wrap:wrap; gap:12px 16px; align-items:center; justify-content:space-between; }
|
||||
.brand { display:flex; align-items:center; gap:12px; }
|
||||
.logo { width:36px; height:36px; border-radius:10px; background:var(--surface); border:1px solid var(--line);
|
||||
display:grid; place-items:center; }
|
||||
h1 { font-size:21px; margin:0; letter-spacing:-.015em; font-weight:650; }
|
||||
h1 span { color:var(--accent); }
|
||||
.tagline { color:var(--muted); font-size:13px; margin-top:1px; }
|
||||
.badges { display:flex; flex-wrap:wrap; gap:8px; }
|
||||
.pill { display:inline-flex; align-items:center; gap:6px; font-size:12px; padding:4px 11px; border-radius:99px;
|
||||
border:1px solid var(--line); color:var(--muted); background:var(--surface); white-space:nowrap; }
|
||||
.pill.ok { color:var(--up); border-color:rgba(63,208,143,.4); background:rgba(63,208,143,.07); }
|
||||
.pill.live { color:var(--down); border-color:rgba(255,107,107,.5); background:rgba(255,107,107,.08); }
|
||||
|
||||
/* demo banner */
|
||||
.demo-bar { margin-top:18px; padding:12px 16px; border-radius:var(--radius); font-size:13px; color:var(--muted);
|
||||
border:1px solid rgba(240,161,69,.35); background:var(--accent-soft);
|
||||
display:flex; flex-wrap:wrap; gap:8px 18px; align-items:center; justify-content:space-between; }
|
||||
.demo-bar b { color:var(--accent); font-weight:600; }
|
||||
.demo-bar .txt { flex:1 1 420px; }
|
||||
|
||||
/* cards */
|
||||
.grid { display:grid; grid-template-columns:repeat(auto-fit, minmax(230px, 1fr)); gap:14px; margin:18px 0; }
|
||||
.card { background:var(--surface); border:1px solid var(--line); border-radius:var(--radius); padding:16px 18px; min-width:0; }
|
||||
.label { font-size:11.5px; text-transform:uppercase; letter-spacing:.09em; color:var(--muted); font-weight:500; }
|
||||
.big { font-size:30px; font-weight:620; font-variant-numeric:tabular-nums; margin-top:6px; letter-spacing:-.01em; }
|
||||
.sub { font-size:13px; color:var(--muted); }
|
||||
.pos { color:var(--up); } .neg { color:var(--down); }
|
||||
|
||||
h2 { font-size:13px; text-transform:uppercase; letter-spacing:.09em; color:var(--muted); font-weight:600; margin:30px 0 12px; }
|
||||
.row-h { display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; }
|
||||
.row-h h2 { margin-bottom:12px; }
|
||||
|
||||
/* exchanges */
|
||||
.exch { display:grid; grid-template-columns:repeat(auto-fit, minmax(170px, 1fr)); gap:10px; }
|
||||
.ex { background:var(--surface); border:1px solid var(--line); border-radius:12px; padding:12px 14px; min-width:0; }
|
||||
.ex .nm { font-weight:600; font-size:14px; display:flex; align-items:center; gap:8px; }
|
||||
.ex .meta { color:var(--muted); font-size:12.5px; margin-top:4px; }
|
||||
.ex .via { color:var(--faint); font-size:12px; margin-top:6px; }
|
||||
.dot { display:inline-block; width:8px; height:8px; border-radius:50%; background:var(--faint); flex:none; }
|
||||
.dot.open { background:var(--up); box-shadow:0 0 0 3px rgba(63,208,143,.18); }
|
||||
.state-open { color:var(--up); } .state-closed { color:var(--muted); }
|
||||
|
||||
/* tables */
|
||||
.scroll { overflow-x:auto; background:var(--surface); border:1px solid var(--line); border-radius:var(--radius); }
|
||||
table { width:100%; border-collapse:collapse; font-size:14px; font-variant-numeric:tabular-nums; }
|
||||
th { text-align:left; font-weight:500; color:var(--muted); font-size:12px; padding:11px 14px; white-space:nowrap;
|
||||
border-bottom:1px solid var(--line); background:var(--surface-2); }
|
||||
td { padding:11px 14px; border-bottom:1px solid var(--line-soft); vertical-align:top; }
|
||||
tr:last-child td { border-bottom:0; }
|
||||
tr.grp td { background:var(--surface-2); color:var(--muted); font-size:12px; letter-spacing:.04em; padding:8px 14px;
|
||||
border-bottom:1px solid var(--line-soft); }
|
||||
td:first-child { white-space:nowrap; font-weight:550; }
|
||||
.why { color:var(--muted); font-size:13px; max-width:380px; }
|
||||
.empty { color:var(--muted); padding:20px 18px; }
|
||||
.spark { width:104px; height:26px; display:block; }
|
||||
.held { font-size:11px; color:var(--accent); border:1px solid rgba(240,161,69,.5); border-radius:5px; padding:0 6px; margin-left:8px; font-weight:500; }
|
||||
.cur { color:var(--faint); font-size:12px; }
|
||||
|
||||
.tag { font-size:12px; padding:2px 9px; border-radius:6px; font-weight:550; white-space:nowrap; display:inline-block; }
|
||||
.executed { background:rgba(63,208,143,.14); color:var(--up); }
|
||||
.blocked { background:rgba(242,184,75,.14); color:var(--warn); }
|
||||
.error { background:rgba(255,107,107,.14); color:var(--down); }
|
||||
.ignored { background:rgba(140,148,168,.14); color:var(--muted); }
|
||||
.bullish { color:var(--up); } .bearish { color:var(--down); } .neutral, .unavailable { color:var(--muted); }
|
||||
.src { color:var(--faint); font-size:12px; margin-top:3px; }
|
||||
.src .bad { color:var(--warn); }
|
||||
details.hl { margin-top:5px; font-size:12.5px; color:var(--muted); }
|
||||
details.hl summary { cursor:pointer; color:var(--info); }
|
||||
details.hl ul { margin:6px 0 0; padding-left:16px; max-width:420px; }
|
||||
details.hl li { margin:2px 0; }
|
||||
|
||||
/* news sources */
|
||||
.sources { display:grid; grid-template-columns:repeat(auto-fit, minmax(250px, 1fr)); gap:10px; }
|
||||
.source { background:var(--surface); border:1px solid var(--line); border-radius:12px; padding:12px 14px; }
|
||||
.source .nm { display:flex; align-items:center; justify-content:space-between; gap:8px; font-weight:600; font-size:14px; }
|
||||
.source p { margin:6px 0 0; color:var(--muted); font-size:12.5px; }
|
||||
.chip { font-size:11px; padding:1px 8px; border-radius:99px; border:1px solid var(--line); color:var(--muted); font-weight:500; }
|
||||
.chip.on { color:var(--up); border-color:rgba(63,208,143,.4); }
|
||||
.chip.off { color:var(--faint); }
|
||||
|
||||
/* buttons */
|
||||
button { cursor:pointer; padding:7px 15px; border-radius:9px; border:1px solid var(--line); background:var(--surface-2); color:var(--ink); }
|
||||
button:hover { border-color:var(--faint); }
|
||||
button.danger { color:var(--down); border-color:rgba(255,107,107,.45); background:transparent; }
|
||||
button.danger.on { background:var(--down); color:#1a0a0a; border-color:var(--down); }
|
||||
button.accent { color:var(--accent); border-color:rgba(240,161,69,.5); background:transparent; }
|
||||
button.primary { background:var(--accent); color:#1b1204; border-color:var(--accent); font-weight:600; }
|
||||
|
||||
#equity { width:100%; height:130px; display:block; margin:10px 0 4px; }
|
||||
|
||||
/* dialog + toast */
|
||||
dialog { background:var(--surface); color:var(--ink); border:1px solid var(--line); border-radius:16px; padding:22px; width:min(380px, calc(100vw - 32px)); }
|
||||
dialog::backdrop { background:rgba(4,5,8,.72); backdrop-filter:blur(2px); }
|
||||
dialog h3 { margin:0 0 6px; font-size:17px; }
|
||||
dialog p { margin:0 0 14px; color:var(--muted); font-size:13.5px; }
|
||||
dialog input { width:100%; padding:10px 12px; border-radius:9px; border:1px solid var(--line); background:var(--bg); color:var(--ink); }
|
||||
dialog .actions { display:flex; gap:10px; justify-content:flex-end; margin-top:16px; }
|
||||
#toast { position:fixed; left:50%; bottom:22px; transform:translateX(-50%); background:var(--surface-2); border:1px solid var(--line);
|
||||
padding:10px 16px; border-radius:10px; font-size:14px; opacity:0; pointer-events:none; transition:opacity .2s; max-width:calc(100vw - 32px); }
|
||||
#toast.show { opacity:1; }
|
||||
@media (prefers-reduced-motion: reduce) { #toast { transition:none; } }
|
||||
|
||||
footer { margin-top:36px; color:var(--faint); font-size:12.5px; }
|
||||
|
||||
#markets { min-width:640px; } #positions { min-width:560px; }
|
||||
.ex .nm .dot { margin-top:6px; align-self:flex-start; }
|
||||
.ex .nm { align-items:flex-start; }
|
||||
|
||||
@media (max-width:560px) {
|
||||
.big { font-size:26px; }
|
||||
td, th { padding:10px 11px; }
|
||||
}
|
||||
/* On phones the signals feed becomes a stack of cards instead of a squeezed table. */
|
||||
@media (max-width:700px) {
|
||||
#events { min-width:0; }
|
||||
#events tr.hd { display:none; }
|
||||
#events tr { display:block; padding:12px 14px; border-bottom:1px solid var(--line-soft); }
|
||||
#events tr:last-child { border-bottom:0; }
|
||||
#events td { display:flex; gap:12px; padding:3px 0; border:0; white-space:normal; font-weight:400; }
|
||||
#events td::before { content:attr(data-l); flex:0 0 64px; color:var(--faint); font-size:12px; padding-top:2px; }
|
||||
#events td.empty { display:block; padding:6px 4px; }
|
||||
#events td.empty::before { content:none; }
|
||||
#events td:first-child { font-weight:550; }
|
||||
#events .why { max-width:none; }
|
||||
}
|
||||
|
||||
/* scorecard + backtest */
|
||||
.stats { display:grid; grid-template-columns:repeat(auto-fit, minmax(150px, 1fr)); gap:10px; }
|
||||
.stat { background:var(--surface); border:1px solid var(--line); border-radius:12px; padding:12px 14px; min-width:0; }
|
||||
.stat .v { font-size:22px; font-weight:600; font-variant-numeric:tabular-nums; margin-top:4px; }
|
||||
.stat .n { color:var(--muted); font-size:12px; margin-top:2px; }
|
||||
.notes { margin:12px 0 0; padding:0; list-style:none; display:grid; gap:6px; }
|
||||
.notes li { font-size:13px; color:var(--muted); padding:8px 12px; border-radius:10px; background:var(--surface);
|
||||
border:1px solid var(--line); border-left:3px solid var(--warn); }
|
||||
.sub-h { font-size:12.5px; color:var(--muted); margin:18px 0 8px; font-weight:500; }
|
||||
#fwd, #btsens, #btsym, #trades { min-width:520px; }
|
||||
.chart2 { width:100%; height:150px; display:block; margin:8px 0 4px; }
|
||||
.legend { display:flex; gap:16px; font-size:12.5px; color:var(--muted); flex-wrap:wrap; }
|
||||
.legend i { display:inline-block; width:10px; height:3px; border-radius:2px; margin-right:6px; vertical-align:middle; }
|
||||
.bt-ctl { display:flex; flex-wrap:wrap; gap:10px; align-items:center; }
|
||||
.bt-ctl select { padding:7px 10px; border-radius:9px; border:1px solid var(--line); background:var(--surface-2); color:var(--ink); font:inherit; }
|
||||
.bar { height:6px; border-radius:99px; background:var(--line); overflow:hidden; flex:1 1 160px; min-width:120px; }
|
||||
.bar > div { height:100%; background:var(--accent); transition:width .3s; }
|
||||
tr.used td { background:var(--accent-soft); }
|
||||
|
||||
/* health panel */
|
||||
#health { min-width:760px; }
|
||||
.chks { display:flex; flex-wrap:wrap; gap:4px; }
|
||||
.chk { font-size:11.5px; padding:1px 7px; border-radius:6px; white-space:nowrap; font-weight:500; }
|
||||
.chk.y { background:rgba(63,208,143,.13); color:var(--up); }
|
||||
.chk.n { background:rgba(140,148,168,.12); color:var(--muted); }
|
||||
.feed-ok { color:var(--up); } .feed-bad { color:var(--down); } .feed-wait { color:var(--warn); }
|
||||
.st-buy { background:rgba(63,208,143,.18); color:var(--up); } .st-hold { background:var(--accent-soft); color:var(--accent); }
|
||||
.st-wait { background:rgba(140,148,168,.12); color:var(--muted); }
|
||||
|
||||
@media (max-width:700px) {
|
||||
#health { min-width:0; }
|
||||
#health tr.hd { display:none; }
|
||||
#health tr.hrow { display:grid; grid-template-columns:1fr auto; gap:4px 10px; padding:11px 14px; border-bottom:1px solid var(--line-soft); }
|
||||
#health tr.hrow td { padding:0; border:0; white-space:normal; }
|
||||
#health .h-sym { grid-column:1; grid-row:1; } #health .h-st { grid-column:2; grid-row:1; text-align:right; }
|
||||
#health .h-feed, #health .h-chk { grid-column:1 / -1; }
|
||||
#health tr.grp { display:block; } #health tr.grp td { display:block; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<header>
|
||||
<div class="brand">
|
||||
<div class="logo" aria-hidden="true">
|
||||
<svg width="22" height="22" viewBox="0 0 32 32"><path d="M5 23l7-8 5 4 10-12" fill="none" stroke="#f0a145" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
||||
</div>
|
||||
<div>
|
||||
<h1>Yote<span>-In-</span>Vest</h1>
|
||||
<div class="tagline">Trend investing with a news filter and hard risk limits</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="badges"><span id="badges" style="display:contents"></span><span class="pill" id="live" title="The page updates itself; no refresh needed">● connecting…</span></div>
|
||||
</header>
|
||||
|
||||
<div class="demo-bar" id="demobar" hidden></div>
|
||||
|
||||
<div class="grid" id="cards"></div>
|
||||
|
||||
<div id="moneysec">
|
||||
<div class="row-h">
|
||||
<h2>Your money</h2>
|
||||
<button id="adddep" class="accent">Add money</button>
|
||||
</div>
|
||||
<div class="stats" id="money"></div>
|
||||
<details class="hl" id="depwrap" style="margin-top:10px" hidden><summary id="depsum"></summary>
|
||||
<div class="scroll" style="margin-top:8px"><table id="deps"></table></div></details>
|
||||
</div>
|
||||
|
||||
<div class="card" id="equitycard" hidden style="margin-top:14px">
|
||||
<div class="label">Account value over time</div>
|
||||
<svg id="equity" viewBox="0 0 600 120" preserveAspectRatio="none" role="img" aria-label="Account value over time"></svg>
|
||||
<div class="sub" id="equitynote"></div>
|
||||
</div>
|
||||
|
||||
<h2>Exchanges</h2>
|
||||
<div class="exch" id="exchanges"></div>
|
||||
|
||||
<div id="healthsec" hidden>
|
||||
<div class="row-h"><h2>Health</h2><span class="sub" id="healthnote"></span></div>
|
||||
<div class="stats" id="healthstats"></div>
|
||||
<div class="sub-h">A buy needs all five checks to be green at the same time. Hover a check for its current value.
|
||||
<label style="margin-left:12px;white-space:nowrap"><input type="checkbox" id="hfilter" checked> Only markets close to a buy (<span id="hcount"></span>)</label></div>
|
||||
<div class="scroll"><table id="health"></table></div>
|
||||
</div>
|
||||
|
||||
<div id="marketsec" hidden>
|
||||
<h2>Markets</h2>
|
||||
<div class="scroll"><table id="markets"></table></div>
|
||||
</div>
|
||||
|
||||
<div class="row-h">
|
||||
<h2>Open positions</h2>
|
||||
<button id="kill" class="danger" title="Stops all new buys. Exits keep working.">Kill switch: off</button>
|
||||
</div>
|
||||
<div class="scroll"><table id="positions"></table></div>
|
||||
|
||||
<div id="scoresec">
|
||||
<h2>Scorecard</h2>
|
||||
<div class="stats" id="score"></div>
|
||||
<ul class="notes" id="scorenotes"></ul>
|
||||
<div class="sub-h">What happened after each buy signal, by what the bot did with it (average price change afterwards)</div>
|
||||
<div class="scroll"><table id="fwd"></table></div>
|
||||
<div class="sub-h">Recent finished trades</div>
|
||||
<div class="scroll"><table id="trades"></table></div>
|
||||
</div>
|
||||
|
||||
<h2>Signals and decisions</h2>
|
||||
<div class="scroll"><table id="events"></table></div>
|
||||
|
||||
<div class="row-h">
|
||||
<h2>Backtest on history</h2>
|
||||
<div class="bt-ctl">
|
||||
<select id="btint" aria-label="Candle size"><option value="1d">Daily candles, 5 years</option><option value="1h">Hourly candles, 2 years</option></select>
|
||||
<button id="btrun" class="accent">Run backtest</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="btbox"></div>
|
||||
|
||||
<h2>News sources</h2>
|
||||
<div class="sources" id="sources"></div>
|
||||
|
||||
<footer>Not financial advice. Paper trading only unless you deliberately switch on live trading. <span id="ver"></span></footer>
|
||||
</div>
|
||||
|
||||
<dialog id="dlg">
|
||||
<form method="dialog">
|
||||
<h3 id="dlg-title">Confirm</h3>
|
||||
<p id="dlg-text"></p>
|
||||
<input id="dlg-amount" type="number" step="0.01" inputmode="decimal" placeholder="Amount in euros (negative = take out)" aria-label="Amount in euros" hidden style="margin-bottom:10px">
|
||||
<input id="dlg-input" type="password" autocomplete="off" placeholder="Webhook secret" aria-label="Webhook secret">
|
||||
<div class="actions">
|
||||
<button type="button" id="dlg-cancel">Cancel</button>
|
||||
<button value="ok" class="primary">Confirm</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
<div id="toast" role="status" aria-live="polite"></div>
|
||||
|
||||
<script>
|
||||
const $ = id => document.getElementById(id);
|
||||
const esc = s => String(s ?? "").replace(/[&<>"']/g, c => ({"&":"&","<":"<",">":">",'"':""","'":"'"}[c]));
|
||||
const money = n => Number(n).toLocaleString("en-GB", {minimumFractionDigits:2, maximumFractionDigits:2});
|
||||
let killOn = false;
|
||||
|
||||
function toast(text) {
|
||||
const t = $("toast"); t.textContent = text; t.classList.add("show");
|
||||
clearTimeout(toast.h); toast.h = setTimeout(() => t.classList.remove("show"), 3200);
|
||||
}
|
||||
function askSecret(title, text, withAmount = false) {
|
||||
return new Promise(resolve => {
|
||||
const d = $("dlg"); $("dlg-amount").hidden = !withAmount; $("dlg-amount").value = ""; $("dlg-title").textContent = title; $("dlg-text").textContent = text;
|
||||
$("dlg-input").value = ""; d.returnValue = "";
|
||||
d.onclose = () => resolve(d.returnValue === "ok" && $("dlg-input").value ? $("dlg-input").value : null);
|
||||
d.showModal(); (withAmount ? $("dlg-amount") : $("dlg-input")).focus();
|
||||
});
|
||||
}
|
||||
$("dlg-cancel").onclick = () => $("dlg").close("cancel"); // Cancel must not be a submit button, or Enter would trigger it
|
||||
async function post(url, body) {
|
||||
const r = await fetch(url, {method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify(body)});
|
||||
return r.ok;
|
||||
}
|
||||
|
||||
function sparkPath(vals, w, h, pad = 2) {
|
||||
if (!vals || vals.length < 2) return "";
|
||||
const lo = Math.min(...vals), hi = Math.max(...vals), r = hi - lo || 1;
|
||||
return vals.map((v, i) => `${i ? "L" : "M"}${(i / (vals.length - 1) * w).toFixed(1)},${(h - pad - (v - lo) / r * (h - 2 * pad)).toFixed(1)}`).join("");
|
||||
}
|
||||
const ago = t => { if (!t) return "never"; const m = Math.round((Date.now()/1000 - t) / 60);
|
||||
return m < 1 ? "just now" : m < 60 ? m + " min ago" : m < 1440 ? Math.round(m/60) + " h ago" : Math.round(m/1440) + " d ago"; };
|
||||
|
||||
function renderBadges(s) {
|
||||
$("badges").innerHTML = s.demo_mode
|
||||
? '<span class="pill ok">Demo · fake money</span>'
|
||||
: (s.live_trading ? '<span class="pill live">LIVE MONEY</span>' : '<span class="pill ok">Paper trading</span>') +
|
||||
`<span class="pill">${s.alpaca_connected ? "Alpaca connected" : "Alpaca not set"}</span>`;
|
||||
}
|
||||
|
||||
function renderCards(s) {
|
||||
const cards = s.accounts.map(a => {
|
||||
if (a.error) return `<div class="card"><div class="label">${esc(a.name)}</div><div class="sub neg">${esc(a.error)}</div></div>`;
|
||||
let extra = "";
|
||||
if (a.name === "paper") {
|
||||
const ch = (a.equity - s.paper_start_cash) / s.paper_start_cash * 100;
|
||||
extra = `<div class="sub ${ch >= 0 ? "pos" : "neg"}">${ch >= 0 ? "+" : ""}${ch.toFixed(2)}% since start</div>`;
|
||||
}
|
||||
const title = a.name === "paper" ? (s.demo_mode ? "Fake money account (€)" : "Built-in paper account") : "Alpaca paper account";
|
||||
return `<div class="card"><div class="label">${title}</div><div class="big">${money(a.equity)}</div>${extra}</div>`;
|
||||
});
|
||||
const ev = s.events, n = k => ev.filter(e => e.decision === k).length;
|
||||
cards.push(`<div class="card"><div class="label">Last ${ev.length} signals</div>
|
||||
<div class="big">${n("executed")} <span class="sub">executed</span></div>
|
||||
<div class="sub">${n("blocked")} blocked by rules or news · ${n("error")} errors</div></div>`);
|
||||
$("cards").innerHTML = cards.join("");
|
||||
}
|
||||
|
||||
function renderExchanges(s) {
|
||||
$("exchanges").innerHTML = (s.exchanges || []).map(e => {
|
||||
const via = s.demo_mode ? "Fake money" : e.trade_via === "alpaca" ? "Orders: Alpaca paper" : "Orders: built-in simulator";
|
||||
return `<div class="ex" title="${esc(e.note)}">
|
||||
<div class="nm"><span class="dot ${e.open ? "open" : ""}"></span>${esc(e.name)}</div>
|
||||
<div class="meta"><span class="${e.open ? "state-open" : "state-closed"}">${e.open ? "Open" : "Closed"}</span>
|
||||
· ${esc(e.hours)}${e.local_time ? ` · now ${esc(e.local_time)}` : ""}</div>
|
||||
<div class="via">${via} · quoted in ${esc(e.currency)}</div></div>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
function renderDemo(s) {
|
||||
const d = s.demo, real = d.data === "real";
|
||||
const bar = $("demobar"); bar.hidden = false;
|
||||
const fx = Object.entries(d.fx || {}).map(([k, v]) => `EUR/${k} ${v}`).join(" · ");
|
||||
bar.innerHTML = `<span class="txt"><b>Demo mode.</b> ${real
|
||||
? `Real prices (Yahoo Finance, ${esc(d.interval)} candles) and real news (${esc(d.news)}). Fake money only, nothing is sent to any broker.`
|
||||
: `Simulated prices and news, a new candle every ${d.every_seconds}s. Fake money only.`}
|
||||
Last update ${ago(d.last_update)}${real && fx ? " · " + esc(fx) : ""}.</span>
|
||||
<button id="reset" class="accent">Reset demo</button>`;
|
||||
$("reset").onclick = resetDemo;
|
||||
|
||||
const eq = d.equity_history.map(p => p[1]);
|
||||
$("equitycard").hidden = eq.length < 2;
|
||||
if (eq.length >= 2) {
|
||||
const all = eq.concat([s.paper_start_cash]);
|
||||
const lo = Math.min(...all), hi = Math.max(...all), r = hi - lo || 1;
|
||||
const y = v => (116 - (v - lo) / r * 112).toFixed(1);
|
||||
const line = eq.map((v, i) => `${i ? "L" : "M"}${(i / (eq.length - 1) * 600).toFixed(1)},${y(v)}`).join("");
|
||||
const col = eq[eq.length - 1] >= s.paper_start_cash ? "var(--up)" : "var(--down)";
|
||||
$("equity").innerHTML =
|
||||
`<line x1="0" x2="600" y1="${y(s.paper_start_cash)}" y2="${y(s.paper_start_cash)}" style="stroke:var(--line)" stroke-dasharray="4 4"/>
|
||||
<path d="${line} L600,120 L0,120 Z" style="fill:${col}" opacity=".10"/>
|
||||
<path d="${line}" fill="none" style="stroke:${col}" stroke-width="2" vector-effect="non-scaling-stroke"/>`;
|
||||
$("equitynote").textContent = `Dashed line = starting balance of €${money(s.paper_start_cash)} · ${eq.length} updates shown`;
|
||||
}
|
||||
|
||||
const open = Object.fromEntries((s.exchanges || []).map(e => [e.id, e]));
|
||||
const names = Object.fromEntries((s.exchanges || []).map(e => [e.id, e.name]));
|
||||
let html = `<tr><th>Market</th><th>Price</th><th>20-candle change</th><th>Trend</th><th>Recent</th><th>Data</th></tr>`;
|
||||
let last = null;
|
||||
for (const p of d.prices) {
|
||||
if (p.exchange !== last) {
|
||||
last = p.exchange; const e = open[p.exchange];
|
||||
html += `<tr class="grp"><td colspan="6">${esc(names[p.exchange] || p.exchange)}${e ? ` · <span class="${e.open ? "state-open" : "state-closed"}">${e.open ? "open now" : "closed"}</span>` : ""}</td></tr>`;
|
||||
}
|
||||
if (p.price === undefined) { html += `<tr><td>${esc(p.symbol)}</td><td colspan="5" class="why neg">${esc(p.error || "waiting for data")}</td></tr>`; continue; }
|
||||
const up = p.change_20 >= 0, col = up ? "var(--up)" : "var(--down)";
|
||||
html += `<tr><td>${esc(p.symbol)}${p.in_position ? '<span class="held">held</span>' : ""}</td>
|
||||
<td>${money(p.price)} <span class="cur">${esc(p.currency)}</span></td>
|
||||
<td class="${up ? "pos" : "neg"}">${up ? "+" : ""}${p.change_20.toFixed(2)}%</td>
|
||||
<td><span style="color:${p.trend === "up" ? "var(--up)" : "var(--down)"}">${p.trend === "up" ? "▲ Up" : "▼ Down"}</span></td>
|
||||
<td><svg class="spark" viewBox="0 0 104 26" preserveAspectRatio="none" aria-hidden="true"><path d="${sparkPath(p.spark, 104, 26)}" fill="none" style="stroke:${col}" stroke-width="1.5" vector-effect="non-scaling-stroke"/></svg></td>
|
||||
<td class="why">${p.error ? `<span class="neg">${esc(p.error)}</span>` : (real ? "candle " + ago(p.last_candle) : "simulated")}</td></tr>`;
|
||||
}
|
||||
$("markets").innerHTML = html; $("marketsec").hidden = false;
|
||||
}
|
||||
|
||||
const inn = t => { if (!t) return "–"; const m = Math.round((t - Date.now()/1000) / 60);
|
||||
return m <= 0 ? "any moment" : m < 60 ? "in " + m + " min" : "in " + Math.round(m/60) + " h"; };
|
||||
const SHORT = {trend:"Trend", price:"Price", volume:"Volume", strength:"Strength", fresh:"Fresh"};
|
||||
function renderHealth(s) {
|
||||
const h = s.demo && s.demo.health; $("healthsec").hidden = !h; if (!h) return;
|
||||
const bad = h.markets.filter(m => m.feed === "error" || m.feed === "stale").length;
|
||||
const warm = h.markets.filter(m => m.warming).length;
|
||||
$("healthstats").innerHTML = [
|
||||
stat("Price feeds", `${h.feed_ok}/${h.total}`, bad ? `${bad} with problems` : "all working", bad ? "neg" : "pos"),
|
||||
stat("Last check", ago(h.last_check), `next ${inn(h.next_check)} · every ${h.every_seconds >= 60 ? Math.round(h.every_seconds / 60) + " min" : h.every_seconds + "s"}`),
|
||||
stat("Updates so far", h.updates, "checks since start"),
|
||||
stat("In an uptrend", `${h.uptrend}/${h.total}`, h.uptrend ? "" : "none yet, so no buys expected"),
|
||||
stat("Buy signal now", h.buy_ready.length ? h.buy_ready.join(", ") : "none", warm ? `${warm} still loading history` : "", h.buy_ready.length ? "pos" : ""),
|
||||
stat("Closest to a buy", h.closest.length ? h.closest[0].symbol : "–", h.closest.length ? "missing: " + h.closest[0].missing.map(x => x.toLowerCase()).join(", ") : ""),
|
||||
].join("");
|
||||
$("healthnote").textContent = "";
|
||||
const names = Object.fromEntries((s.exchanges || []).map(e => [e.id, e.name]));
|
||||
const only = $("hfilter").checked;
|
||||
const show = m => !only || m.status !== "waiting" || m.warming || m.missing.length <= 2 || m.feed !== "ok";
|
||||
$("hcount").textContent = `${h.markets.filter(show).length} of ${h.markets.length} shown`;
|
||||
let html = `<tr class="hd"><th>Market</th><th>Price feed</th><th>Buy checks</th><th>Status</th></tr>`, last = null;
|
||||
for (const m of h.markets) {
|
||||
if (!show(m)) continue;
|
||||
if (m.exchange !== last) { last = m.exchange; html += `<tr class="grp"><td colspan="4">${esc(names[m.exchange] || m.exchange)}</td></tr>`; }
|
||||
const feed = m.feed === "ok" ? `<span class="feed-ok">● ok</span> <span class="cur">${m.last_candle ? "candle " + esc(ago(m.last_candle)) : "simulated"}</span>${m.note ? `<div class="src">${esc(m.note)}</div>` : ""}`
|
||||
: m.feed === "waiting" ? `<span class="feed-wait">● waiting</span>`
|
||||
: `<span class="feed-bad">● ${esc(m.feed)}</span><div class="src">${esc(m.note)}</div>`;
|
||||
const chk = m.warming ? `<span class="cur">loading history: ${m.have}/${m.need} candles</span>`
|
||||
: `<div class="chks">${m.checks.map(c => `<span class="chk ${c.ok ? "y" : "n"}" title="${esc(c.label)}: ${esc(c.detail)}">${c.ok ? "✓" : "✗"} ${SHORT[c.key]}</span>`).join("")}</div>`;
|
||||
const st = m.status === "holding" ? '<span class="tag st-hold">holding</span>'
|
||||
: m.status === "buy_signal" ? '<span class="tag st-buy">buy signal</span>'
|
||||
: m.status === "warming" ? '<span class="tag st-wait">warming up</span>'
|
||||
: `<span class="tag st-wait">waiting</span> <span class="cur">${m.missing.length} of 5 missing</span>`;
|
||||
html += `<tr class="hrow"><td class="h-sym">${esc(m.symbol)}</td><td class="h-feed">${feed}</td><td class="h-chk">${chk}</td><td class="h-st">${st}</td></tr>`;
|
||||
}
|
||||
$("health").innerHTML = html;
|
||||
}
|
||||
|
||||
function renderPositions(s) {
|
||||
const pos = s.accounts.flatMap(a => a.positions.map(p => ({...p, broker:a.name})));
|
||||
const eur = s.demo_mode ? " (€)" : "";
|
||||
$("positions").innerHTML = pos.length
|
||||
? `<tr><th>Asset</th><th>Account</th><th>Quantity</th><th>Avg price${eur}</th><th>Value${eur}</th><th>Result</th></tr>` +
|
||||
pos.map(p => { const pl = p.market_value - p.qty * p.avg_price;
|
||||
return `<tr><td>${esc(p.symbol)}</td><td>${s.demo_mode ? "demo" : esc(p.broker)}</td><td>${Number(p.qty).toFixed(4)}</td>
|
||||
<td>${money(p.avg_price)}</td><td>${money(p.market_value)}</td>
|
||||
<td class="${pl >= 0 ? "pos" : "neg"}">${pl >= 0 ? "+" : ""}${money(pl)}</td></tr>`; }).join("")
|
||||
: `<tr><td class="empty">No open positions.</td></tr>`;
|
||||
}
|
||||
|
||||
function newsCell(v) {
|
||||
if (!v) return "";
|
||||
const conf = v.sentiment !== "unavailable" ? ` ${Math.round(v.confidence * 100)}%` : "";
|
||||
const src = Object.entries(v.sources || {}).map(([k, n]) => `${esc(k)} ${n}`).join(" · ");
|
||||
const bad = (v.source_errors || []).map(e => `<span class="bad">⚠ ${esc(e)}</span>`).join("<br>");
|
||||
const hl = (v.headlines || []).length
|
||||
? `<details class="hl"><summary>${v.headlines.length} headlines</summary><ul>${v.headlines.map(h => `<li>${esc(h)}</li>`).join("")}</ul></details>` : "";
|
||||
return `<span class="${esc(v.sentiment)}"><b>${esc(v.sentiment)}${conf}</b></span>
|
||||
<div class="why">${esc(v.summary)}</div>
|
||||
${src || bad ? `<div class="src">${src}${src && bad ? "<br>" : ""}${bad}</div>` : ""}${hl}`;
|
||||
}
|
||||
|
||||
function renderEvents(s) {
|
||||
const eur = s.demo_mode ? " (€)" : "";
|
||||
$("events").innerHTML = s.events.length
|
||||
? `<tr class="hd"><th>Time (UTC)</th><th>Asset</th><th>Signal</th><th>Price${eur}</th><th>Decision</th><th>Why</th><th>News</th></tr>` +
|
||||
s.events.map(e => { const o = e.order_info;
|
||||
const pnl = o && o.pnl !== undefined ? ` <span class="${o.pnl >= 0 ? "pos" : "neg"}">(${o.pnl >= 0 ? "+" : ""}${money(o.pnl)})</span>` : "";
|
||||
return `<tr><td data-l="Time">${esc(e.ts.slice(5,16).replace("T"," "))}</td><td data-l="Asset">${esc(e.symbol)}</td>
|
||||
<td data-l="Signal">${esc(e.action)}</td><td data-l="Price">${money(e.price)}</td>
|
||||
<td data-l="Decision"><span><span class="tag ${esc(e.decision)}">${esc(e.decision)}</span>${pnl}</span></td>
|
||||
<td class="why" data-l="Why"><span>${esc(e.reason)}</span></td>
|
||||
<td data-l="News"><span>${newsCell(e.sentiment)}</span></td></tr>`; }).join("")
|
||||
: `<tr><td class="empty">No signals yet. They appear here when a trend signal fires.</td></tr>`;
|
||||
}
|
||||
|
||||
function renderSources(s) {
|
||||
$("sources").innerHTML = (s.news_sources || []).map(n => {
|
||||
const state = n.enabled ? '<span class="chip on">on</span>'
|
||||
: n.needs_key && !n.configured ? '<span class="chip off">needs API key</span>' : '<span class="chip off">off</span>';
|
||||
return `<div class="source"><div class="nm">${esc(n.name)} ${state}</div>
|
||||
<p>${esc(n.about)}</p></div>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
// Live updating: every part of the page fetches its data in the background (no page reload).
|
||||
let lastOk = 0;
|
||||
async function api(url) {
|
||||
const r = await fetch(url, {cache: "no-store"});
|
||||
if (!r.ok) throw new Error(r.status);
|
||||
return r.json();
|
||||
}
|
||||
function tickLive(failed) {
|
||||
const el = $("live"), age = Math.round((Date.now() - lastOk) / 1000);
|
||||
const lost = failed || !lastOk || age > 35;
|
||||
el.textContent = lost ? "● connection lost" : `● live · updated ${age}s ago`;
|
||||
el.style.color = lost ? "var(--down)" : "var(--up)";
|
||||
}
|
||||
setInterval(() => tickLive(), 1000);
|
||||
document.addEventListener("visibilitychange", () => { if (!document.hidden) { load(); loadScore(); loadMoney(); } });
|
||||
|
||||
async function load() {
|
||||
let s;
|
||||
try { s = await api("api/state"); lastOk = Date.now(); tickLive(); } catch { tickLive(true); return; }
|
||||
killOn = s.kill_switch; $("ver").textContent = s.version ? "· version " + s.version : "";
|
||||
renderBadges(s); renderCards(s); renderExchanges(s);
|
||||
if (s.demo) { renderDemo(s); renderHealth(s); } else { $("healthsec").hidden = true; $("demobar").hidden = true; $("equitycard").hidden = true; $("marketsec").hidden = true; }
|
||||
renderPositions(s); renderEvents(s); renderSources(s);
|
||||
const b = $("kill");
|
||||
b.textContent = "Kill switch: " + (killOn ? "ON (no new buys)" : "off");
|
||||
b.classList.toggle("on", killOn);
|
||||
}
|
||||
|
||||
$("kill").onclick = async () => {
|
||||
const secret = await askSecret(killOn ? "Turn the kill switch off?" : "Turn the kill switch on?",
|
||||
"While it is on, no new buys are placed. Selling still works. Enter your webhook secret to confirm.");
|
||||
if (!secret) return;
|
||||
if (await post("api/kill", {secret, on: !killOn})) load(); else toast("Wrong secret.");
|
||||
};
|
||||
async function resetDemo() {
|
||||
const secret = await askSecret("Reset the demo?",
|
||||
"This clears all fake trades and puts the fake account back to its starting balance. Enter your webhook secret to confirm.");
|
||||
if (!secret) return;
|
||||
if (await post("api/demo/reset", {secret})) { toast("Demo reset."); load(); } else toast("Wrong secret.");
|
||||
}
|
||||
|
||||
const pct = (v, d = 1) => v === null || v === undefined ? "–" : (v > 0 ? "+" : "") + Number(v).toFixed(d) + "%";
|
||||
const cls = v => v === null || v === undefined ? "" : v >= 0 ? "pos" : "neg";
|
||||
const stat = (l, v, n = "", c = "") => `<div class="stat"><div class="label">${l}</div><div class="v ${c}">${v}</div><div class="n">${n}</div></div>`;
|
||||
|
||||
function renderScore(r) {
|
||||
const st = r.stats;
|
||||
$("score").innerHTML = [
|
||||
stat("Return", pct(r.return_pct, 2), `since start · €${money(r.equity)}`, cls(r.return_pct)),
|
||||
stat("Just holding", pct(r.hold_return_pct, 2), "all markets, equal weight", cls(r.hold_return_pct)),
|
||||
stat("Worst drop", pct(r.max_drawdown_pct, 1), "peak to trough", r.max_drawdown_pct < -5 ? "neg" : ""),
|
||||
stat("Finished trades", st.trades, `${st.wins} won · ${st.losses} lost · ${r.open_trades} still open`),
|
||||
stat("Win rate", st.win_rate === null ? "–" : st.win_rate + "%", st.trades < 30 ? "too few trades to trust" : ""),
|
||||
stat("Avg win / loss", `${st.avg_win === null ? "–" : "€" + money(st.avg_win)} / ${st.avg_loss === null ? "–" : "€" + money(Math.abs(st.avg_loss))}`, "per trade"),
|
||||
stat("Profit factor", st.profit_factor ?? "–", "money won ÷ money lost (above 1 = profit)"),
|
||||
stat("Return on money used", pct(r.return_on_deployed_pct, 2), `€${money(r.deployed)} invested in total`, cls(r.return_on_deployed_pct)),
|
||||
].join("");
|
||||
$("scorenotes").innerHTML = r.warnings.map(w => `<li>${esc(w)}</li>`).join("");
|
||||
const names = {bought: "Bought", vetoed_by_news: "Skipped: bad news", blocked_other: "Skipped: other rules"};
|
||||
const hs = ["6", "24", "72"];
|
||||
$("fwd").innerHTML = `<tr><th>Buy signal that was…</th><th>Signals</th>${hs.map(h => `<th>After ${h} candles</th>`).join("")}</tr>` +
|
||||
Object.keys(names).map(k => `<tr><td>${names[k]}</td><td>${r.signals[k]}</td>` + hs.map(h => {
|
||||
const f = r.forward[k][h];
|
||||
return f.n ? `<td><span class="${cls(f.avg_pct)}">${pct(f.avg_pct, 2)}</span> <span class="cur">${f.up_pct}% up · n=${f.n}</span></td>` : `<td class="cur">no data yet</td>`;
|
||||
}).join("") + "</tr>").join("");
|
||||
$("trades").innerHTML = r.recent_trades.length
|
||||
? `<tr><th>Closed (UTC)</th><th>Asset</th><th>Bought at</th><th>Sold at</th><th>Result</th><th>Exit</th></tr>` +
|
||||
r.recent_trades.map(t => `<tr><td>${esc(t.sell_ts.slice(5,16).replace("T"," "))}</td><td>${esc(t.symbol)}</td><td>${money(t.buy_price)}</td><td>${money(t.sell_price)}</td>
|
||||
<td class="${cls(t.pnl)}">${t.pnl >= 0 ? "+" : ""}${money(t.pnl)} (${pct(t.ret_pct, 1)})</td><td class="why">${esc(t.why)}</td></tr>`).join("")
|
||||
: `<tr><td class="empty">No finished trades yet.</td></tr>`;
|
||||
}
|
||||
async function loadScore() {
|
||||
try { renderScore(await api("api/scorecard")); } catch {}
|
||||
}
|
||||
|
||||
function lineChart(a, b) { // two curves normalised to 100
|
||||
const all = a.concat(b), lo = Math.min(...all.map(p => p[1])), hi = Math.max(...all.map(p => p[1])), r = hi - lo || 1;
|
||||
const path = pts => pts.map((p, i) => `${i ? "L" : "M"}${(i / (pts.length - 1) * 600).toFixed(1)},${(136 - (p[1] - lo) / r * 128).toFixed(1)}`).join("");
|
||||
return `<svg class="chart2" viewBox="0 0 600 140" preserveAspectRatio="none" role="img" aria-label="Strategy compared with holding">
|
||||
<path d="${path(b)}" fill="none" style="stroke:var(--muted)" stroke-width="1.6" vector-effect="non-scaling-stroke"/>
|
||||
<path d="${path(a)}" fill="none" style="stroke:var(--accent)" stroke-width="2.2" vector-effect="non-scaling-stroke"/></svg>
|
||||
<div class="legend"><span><i style="background:var(--accent)"></i>Strategy</span><span><i style="background:var(--muted)"></i>Just holding</span></div>`;
|
||||
}
|
||||
let btPoll = null;
|
||||
function renderBacktest(d) {
|
||||
const run = $("btrun"); run.disabled = d.running; run.textContent = d.running ? "Running…" : "Run backtest";
|
||||
let h = "";
|
||||
if (d.running) h += `<div class="card"><div class="sub">Downloading history and replaying the strategy… ${d.done}/${d.total || "?"} markets</div>
|
||||
<div class="bar" style="margin-top:10px"><div style="width:${d.total ? d.done / d.total * 100 : 3}%"></div></div></div>`;
|
||||
if (d.error) h += `<ul class="notes"><li>${esc(d.error)}</li></ul>`;
|
||||
const r = d.result;
|
||||
if (!r) {
|
||||
$("btbox").innerHTML = h || `<div class="card sub">No backtest yet. It replays the strategy over years of real price history for all markets and compares it with simply holding. Takes a minute or two.</div>`;
|
||||
} else {
|
||||
const o = r.overall, b = r.benchmark;
|
||||
h += `<div class="stats">${[
|
||||
stat("Strategy", pct(o.return_pct), `${pct(o.per_year_pct)} per year`, cls(o.return_pct)),
|
||||
stat("Just holding", pct(b.return_pct), `${pct(b.per_year_pct)} per year`, cls(b.return_pct)),
|
||||
stat("Worst drop", pct(o.max_drawdown_pct), `holding: ${pct(b.max_drawdown_pct)}`),
|
||||
stat("Trades", o.trades, `win rate ${o.win_rate_pct ?? "–"}% · profit factor ${o.profit_factor ?? "–"}`),
|
||||
stat("Test on unseen data", pct(r.out_of_sample.strategy.return_pct), `last 40% of period · holding: ${pct(r.out_of_sample.hold.return_pct)} · first 60%: ${pct(r.in_sample.strategy.return_pct)}`, cls(r.out_of_sample.strategy.return_pct)),
|
||||
].join("")}</div>
|
||||
<div class="card" style="margin-top:12px"><div class="label">Account value, both starting at 100</div>${lineChart(r.equity, r.hold_equity)}</div>
|
||||
<ul class="notes">${r.verdict.map(v => `<li>${esc(v)}</li>`).join("")}</ul>
|
||||
<div class="sub-h">Do slightly different settings change the story? A fragile strategy swings wildly here.</div>
|
||||
<div class="scroll"><table id="btsens"><tr><th>Settings</th><th>Return</th><th>Worst drop</th><th>Trades</th></tr>${
|
||||
r.sensitivity.map(s => `<tr class="${s.used ? "used" : ""}"><td>${esc(s.label)}${s.used ? ' <span class="held">in use</span>' : ""}</td><td class="${cls(s.return_pct)}">${pct(s.return_pct)}</td><td>${pct(s.max_drawdown_pct)}</td><td>${s.trades}</td></tr>`).join("")}</table></div>
|
||||
<div class="sub-h">By market</div>
|
||||
<div class="scroll"><table id="btsym"><tr><th>Market</th><th>Trades</th><th>Win rate</th><th>Avg per trade</th><th>Holding</th></tr>${
|
||||
r.by_symbol.map(s => `<tr><td>${esc(s.symbol)}</td><td>${s.trades}</td><td>${s.win_rate_pct === null ? "–" : s.win_rate_pct + "%"}</td><td class="${cls(s.avg_trade_pct)}">${pct(s.avg_trade_pct, 2)}</td><td class="${cls(s.hold_pct)}">${pct(s.hold_pct)}</td></tr>`).join("")}</table></div>
|
||||
<div class="sub-h">${esc(r.interval)} candles, ${esc(r.range)} of history, ${r.period.assets} markets${Object.keys(r.errors || {}).length ? ` · could not load: ${Object.keys(r.errors).map(esc).join(", ")}` : ""}. Assumed: ${r.assumptions.fee_pct}% fee and ${r.assumptions.slippage_pct}% slippage per trade, ${r.assumptions.size_pct * 100}% of the account per buy, max ${r.assumptions.max_positions} positions.</div>`;
|
||||
$("btbox").innerHTML = h;
|
||||
}
|
||||
if (d.running && !btPoll) btPoll = setInterval(loadBacktest, 3000);
|
||||
if (!d.running && btPoll) { clearInterval(btPoll); btPoll = null; }
|
||||
}
|
||||
async function loadBacktest() {
|
||||
try { renderBacktest(await api("api/backtest")); } catch {}
|
||||
}
|
||||
$("btrun").onclick = async () => {
|
||||
const secret = await askSecret("Run a backtest?", "Downloads years of price history for all markets and replays the strategy. Takes a minute or two. Enter your webhook secret to confirm.");
|
||||
if (!secret) return;
|
||||
const r = await fetch("api/backtest/run", {method:"POST", headers:{"Content-Type":"application/json"},
|
||||
body: JSON.stringify({secret, interval: $("btint").value, years: 5})});
|
||||
if (r.ok) { toast("Backtest started."); loadBacktest(); } else toast(r.status === 401 ? "Wrong secret." : r.status === 409 ? "Already running." : "Could not start.");
|
||||
};
|
||||
|
||||
function renderMoney(m) {
|
||||
$("money").innerHTML = [
|
||||
stat("Put in", "€" + money(m.invested), m.deposits.length ? `${m.deposits.length} deposit${m.deposits.length > 1 ? "s" : ""} + €${money(m.start_cash)} start` : `€${money(m.start_cash)} starting balance`),
|
||||
stat("Worth now", "€" + money(m.value), "all accounts"),
|
||||
stat("Gain", (m.gain >= 0 ? "+" : "−") + "€" + money(Math.abs(m.gain)), m.gain_pct === null ? "" : pct(m.gain_pct, 2) + " on what you put in", cls(m.gain)),
|
||||
].join("");
|
||||
$("depwrap").hidden = !m.deposits.length;
|
||||
$("depsum").textContent = `${m.deposits.length} deposit${m.deposits.length === 1 ? "" : "s"} recorded`;
|
||||
$("deps").innerHTML = `<tr><th>Date (UTC)</th><th>Amount</th><th>Note</th></tr>` + m.deposits.map(d =>
|
||||
`<tr><td>${esc(d.ts.slice(0,16).replace("T"," "))}</td><td class="${cls(d.amount)}">${d.amount >= 0 ? "+" : "−"}€${money(Math.abs(d.amount))}</td><td class="why">${esc(d.note || "")}</td></tr>`).join("");
|
||||
}
|
||||
async function loadMoney() { try { renderMoney(await api("api/money")); } catch {} }
|
||||
$("hfilter").onchange = () => load();
|
||||
$("adddep").onclick = async () => {
|
||||
const secret = await askSecret("Add money", "Record money you put into the account. Use a negative amount for money you take out. Enter the amount and your webhook secret.", true);
|
||||
const amount = parseFloat($("dlg-amount").value);
|
||||
if (!secret) return;
|
||||
if (!amount) return toast("Enter an amount first.");
|
||||
const r = await fetch("api/deposits", {method:"POST", headers:{"Content-Type":"application/json"}, body: JSON.stringify({secret, amount})});
|
||||
if (r.ok) { toast("Recorded."); loadMoney(); loadScore(); load(); }
|
||||
else toast(r.status === 401 ? "Wrong secret." : (await r.json()).detail || "Could not record.");
|
||||
};
|
||||
|
||||
load(); setInterval(load, 10000);
|
||||
loadMoney(); setInterval(loadMoney, 15000);
|
||||
loadScore(); setInterval(loadScore, 60000);
|
||||
loadBacktest();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user