feat: добавить общий виртуальный счёт, справку и восстановление позиций
Offline regression tests / windows (3.11) (push) Canceled after 0s
Offline regression tests / windows (3.12) (push) Canceled after 0s
Offline regression tests / windows (3.13) (push) Canceled after 0s

This commit is contained in:
Igol committed 2026-10-22 23:07:50 +03:00
1 parent 6aa76064dc
commit c5aed5b970
29 files changed
+3600 -224

No files matched your search

+311 -44
View File
@@ -6,7 +6,7 @@ const MAIN_FIELDS = [
["auto_tp", "Авто тейк-профит по прогнозу", "check"], ["require_leader", "Входить, только если ведущая правда ведёт", "check"],
];
const MORE_FIELDS = [
["budget", "Бюджет, $"], ["cooldown_ms", "Пауза после сделки, мс"], ["lead_threshold_pct", "Отставание для входа, %"],
["cooldown_ms", "Пауза после сделки, мс"], ["lead_threshold_pct", "Отставание для входа, %"],
["lead_window_ms", "Окно сравнения, мс"], ["vector_window_seconds", "Вектор за, с"], ["vector_min_move_pct", "Мин. движение, %"],
["auto_tp_share_pct", "Доля догоняния, %"], ["auto_tp_horizon_seconds", "Горизонт прогноза, с"],
["cut_loss_ticks", "Минус для закрытия, шагов"], ["max_data_age_ms", "Данные не старше, мс"],
@@ -19,6 +19,12 @@ let state = null, selected = localStorage.getItem("sim.coin") || null, detail =
let detailEpoch = 0, detailRequest = 0, detailApplied = 0;
let bxEpoch = 0, bxRequest = 0, bxApplied = 0, bxDataVenue = null;
let range = +(localStorage.getItem("sim.range") || 300), seenOpen = new Set(), seenClosed = 0, settingsDirty = false;
let stateRequest = 0, stateApplied = 0, realRequest = 0, realApplied = 0;
const readHealth = new Map(), pendingReads = new Map(), pendingCommands = new Set(), pendingPolls = new Map(), readGenerations = new Map();
const FRESH_MS = 10000;
let accountData = null, accountBusy = false, pendingAccountAdjustment = null;
const accountIsStale = account => Array.isArray(account?.stale) ? account.stale.length > 0 : !!account?.stale;
const escapeHtml = value => String(value ?? "").replace(/[&<>"']/g, c => ({"&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;", "'":"&#39;"}[c]));
// all times on the page are Moscow time, whatever the computer's time zone
const MSK = new Intl.DateTimeFormat("ru-RU", {timeZone: "Europe/Moscow", hour: "2-digit", minute: "2-digit", second: "2-digit"});
@@ -32,10 +38,183 @@ const fmt = (v, d = 4) => v == null || isNaN(v) ? "—" : (+v).toFixed(d);
const price = v => v == null ? "—" : (+v).toPrecision(6);
const money = v => (v >= 0 ? "+" : "") + (+v).toFixed(4) + " $";
const cls = v => v > 0 ? "pos" : v < 0 ? "neg" : "mut";
function commandNotice(message, bad = false) {
const el = document.getElementById("commandNotice");
if (!el) return;
el.textContent = message; el.hidden = !message; el.className = bad ? "command-notice neg" : "command-notice pos";
}
function freshRead(path) {
const h = readHealth.get(path);
return !!h && !h.error && Date.now() - h.time < FRESH_MS;
}
function invalidateRead(path) {
readGenerations.set(path, (readGenerations.get(path) || 0) + 1);
pendingReads.delete(path); readHealth.delete(path);
}
function commandRead(path) {
if (path.startsWith("/api/account/")) return "/api/account";
if (/^\/api\/coin\/[^/]+\/remove$/.test(path)) return "/api/state";
if (path.startsWith("/api/coin/")) return path.split("/").slice(0, 4).join("/");
if (path.startsWith("/api/basis/")) return `/api/basis?ex=${path.split("/")[3]}`;
if (path.startsWith("/api/scanner/")) return "/api/scanner";
if (path.startsWith("/api/real/")) return "/api/real";
return "/api/state";
}
function activeRead() {
if (tab === "basis") return `/api/basis?ex=${bxVenue}`;
if (tab === "real") return "/api/real";
return selected === SCANNER ? "/api/scanner" : selected ? `/api/coin/${selected}` : "/api/state";
}
function connectionLabel(path) {
const h = readHealth.get(path);
if (!h) return "Подключение к серверу…";
const age = h.time ? Math.max(0, Math.floor((Date.now() - h.time) / 1000)) : null;
if (!freshRead(path)) return `Связь потеряна или данные устарели${age == null ? "" : ` · последние данные ${age} с назад`}. ${h.error || "Жду обновления"}. Команды заблокированы до восстановления связи.`;
return `Связь с сервером есть · получено ${age} с назад`;
}
function refreshConnection() {
const path = activeRead(), fresh = freshRead(path);
const el = document.getElementById("connectionStatus");
if (el) { el.textContent = connectionLabel(path); el.className = fresh ? "connection-status connected" : "connection-status disconnected"; }
const mode = document.getElementById("modeStatus");
if (mode) {
const selectedCoin = detail?.key === selected ? detail : state?.coins?.find(c => c.key === selected);
const live = tab === "basis" ? bxVenue === "cross_real" : tab === "sim" && !!selectedCoin?.real?.enabled;
mode.textContent = tab === "real" ? "API-ключи и журнал бирж" : tab === "sim" && selected && selected !== SCANNER && !selectedCoin ? "Режим выбранной монеты загружается…" : live ? "РЕАЛЬНАЯ ТОРГОВЛЯ · средства биржи" : "СИМУЛЯЦИЯ · общий виртуальный счёт";
mode.className = live ? "mode-status mode-live" : "mode-status";
}
document.querySelectorAll("button[onclick], input[onchange]").forEach(control => {
const handler = control.getAttribute("onclick") || control.getAttribute("onchange") || "";
if (/\b(saveSettings|trade|resetCoin|removeCoin|closePos|scanner|addCoin|keySave|keyCheck|keyDelete|coinReal|simRealTransfer|simRealPing|simRealSl|simRealTpsl|basisReal|crossToggle|crossFeesSave|basisSave|basisRun|basisClose|basisAdopt|basisReset)\s*\(/.test(handler)) {
control.dataset.command = /\b(saveSettings|removeCoin)\b/.test(handler) ? "state" : /\b(keySave|keyCheck|keyDelete|simRealTransfer|simRealPing|simRealSl|simRealTpsl)\b/.test(handler) ? "real" : "active";
}
});
document.querySelectorAll("[data-command]").forEach(control => {
const source = control.dataset.command === "account" ? "/api/account" : control.dataset.command === "state" ? "/api/state" : control.dataset.command === "real" ? "/api/real" : path;
const blocked = !freshRead(source) || (source === "/api/account" && (accountBusy || accountData?.error || (accountIsStale(accountData) && control.dataset.accountDirection === "-1")));
if (blocked && !control.dataset.connectionDisabled) {
control.dataset.wasDisabled = control.disabled ? "1" : "0"; control.dataset.connectionDisabled = "1"; control.disabled = true;
} else if (!blocked && control.dataset.connectionDisabled) {
control.disabled = control.dataset.wasDisabled === "1";
delete control.dataset.connectionDisabled; delete control.dataset.wasDisabled;
} else if (blocked) control.disabled = true;
});
updateAccountVisibility();
}
function setControlDisabled(control, disabled) {
if (control.dataset?.connectionDisabled) control.dataset.wasDisabled = disabled ? "1" : "0";
else control.disabled = disabled;
}
async function api(path, body) {
const r = await fetch(path, body === undefined ? {} : {method: "POST",
headers: {"Content-Type": "application/json", "X-Sim": "1"}, body: JSON.stringify(body)});
return r.json();
const reading = body === undefined;
if (reading && pendingReads.has(path)) return pendingReads.get(path);
const generation = readGenerations.get(path) || 0;
if (!reading && (!freshRead(commandRead(path)) || (path === "/api/real/simulator" && body.coin && !freshRead(`/api/coin/${body.coin}`)))) {
const error = new Error("Команда не отправлена: сначала дождитесь свежих данных сервера.");
commandNotice(error.message, true); throw error;
}
if (!reading && pendingCommands.has(path)) {
const error = new Error("Эта команда уже выполняется. Дождитесь ответа сервера.");
commandNotice(error.message, true); throw error;
}
const request = (async () => {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), reading ? 8000 : 20000);
if (!reading) pendingCommands.add(path);
try {
const response = await fetch(path, reading ? {signal: controller.signal, cache: "no-store"} : {method: "POST", signal: controller.signal,
headers: {"Content-Type": "application/json", "X-Sim": "1"}, body: JSON.stringify(body)});
let data;
try { data = await response.json(); } catch (_) { throw new Error(`Сервер вернул некорректный ответ (HTTP ${response.status})`); }
if (!response.ok) throw new Error(data.error || `Ошибка сервера HTTP ${response.status}`);
if (reading && data.error && !(path === "/api/account" && data.balance != null)) throw new Error(data.error);
if (reading) {
if (generation === (readGenerations.get(path) || 0)) readHealth.set(path, {time: Date.now(), error: data.error || ""});
}
else if (data.ok === false || data.error) commandNotice(data.error || data.message || "Команда отклонена сервером", true);
else commandNotice(data.message || "Команда подтверждена сервером");
return data;
} catch (cause) {
const reason = cause.name === "AbortError" ? "Сервер не ответил вовремя" : cause.message || "Нет связи с сервером";
if (reading) {
if (generation === (readGenerations.get(path) || 0)) readHealth.set(path, {time: readHealth.get(path)?.time || 0, error: reason});
}
else {
cause.userMessage = `Результат команды не подтверждён: ${reason}. Проверьте состояние перед повтором. Автоматического повтора нет.`;
commandNotice(cause.userMessage, true);
}
cause.apiHandled = true;
throw cause;
} finally {
clearTimeout(timeout);
if (!reading) pendingCommands.delete(path);
refreshConnection();
}
})();
if (reading) {
pendingReads.set(path, request);
try { return await request; } finally { if (pendingReads.get(path) === request) pendingReads.delete(path); }
}
return request;
}
async function poll(task) {
if (pendingPolls.has(task)) return pendingPolls.get(task);
const work = (async () => {
try { await task(); } catch (error) {
if (!error.apiHandled) commandNotice(`Не удалось обновить интерфейс: ${error.message || "неожиданная ошибка"}`, true);
// api() records connectivity; the next scheduled read recovers.
}
})();
pendingPolls.set(task, work);
try { await work; } finally { if (pendingPolls.get(task) === work) pendingPolls.delete(task); }
}
function updateAccountVisibility() {
const panel = document.getElementById("paperAccount");
if (panel) panel.hidden = !(tab === "sim" || (tab === "basis" && bxVenue === "cross"));
}
function renderAccount(account) {
if (!account) return;
if (accountData && account.version != null && accountData.version != null && account.version < accountData.version) return;
if (accountData && account.version === accountData.version && account.updated_at != null && accountData.updated_at != null && account.updated_at < accountData.updated_at) return;
accountData = account;
const health = document.getElementById("accountHealth");
if (health) { health.textContent = account.error || (accountIsStale(account) ? "Оценка открытых позиций устарела. Дождитесь свежих котировок." : "Один счёт для всех виртуальных сделок. Реальные деньги бирж учитываются отдельно."); health.className = account.error || accountIsStale(account) ? "statusline neg" : "statusline"; }
for (const key of ["balance", "equity", "reserved", "free"]) {
const el = document.getElementById(`account-${key}`);
if (el) el.textContent = account[key] == null ? "—" : `${Number(account[key]).toFixed(2)} $`;
}
const rows = document.getElementById("accountJournal");
if (rows) rows.innerHTML = (account.journal || []).slice(0, 100).map(entry => `<tr><td>${entry.time ? mskFull(entry.time) : "—"}</td><td>${escapeHtml(entry.reason || entry.type || entry.action || "Операция")}</td><td class="${cls(Number(entry.amount || 0))}">${entry.amount == null ? "—" : money(entry.amount)}</td><td>${entry.balance == null ? "—" : Number(entry.balance).toFixed(2)}</td></tr>`).join("") || '<tr><td colspan="4" class="empty">Операций пока нет</td></tr>';
}
async function loadAccount() { renderAccount(await api("/api/account")); }
async function adjustAccount(direction) {
if (accountBusy) return;
const input = document.getElementById("accountDelta"), msg = document.getElementById("accountMsg");
const value = input.value.trim().replace(",", ".");
if (!/^\d+(?:\.\d{1,8})?$/.test(value) || !Number.isFinite(Number(value)) || Number(value) <= 0) {
msg.textContent = "Введите сумму больше 0, до 8 знаков после запятой."; return;
}
const [whole, fraction = ""] = value.split("."), decimals = fraction.replace(/0+$/, "");
const amount = `${direction < 0 ? "-" : ""}${whole.replace(/^0+(?=\d)/, "")}${decimals ? "." + decimals : ""}`;
if (accountData?.error || (direction < 0 && accountIsStale(accountData))) { msg.textContent = accountData.error || "Оценка открытых позиций устарела. Списание доступно после обновления котировок."; return; }
if (pendingAccountAdjustment && pendingAccountAdjustment.amount !== amount) {
msg.textContent = `Прошлая операция (${pendingAccountAdjustment.amount} $) не подтверждена. Повторите её с той же суммой: повторное списание или пополнение исключено по идентификатору.`; return;
}
const request = pendingAccountAdjustment || {amount, request_id: globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(36).slice(2)}`};
accountBusy = true; refreshConnection(); msg.textContent = "Сохраняю операцию…";
try {
// Keep the identifier only after freshness checks: a blocked command has not been sent.
if (!freshRead("/api/account")) { msg.textContent = "Нет свежих данных счёта. Дождитесь восстановления связи."; return; }
pendingAccountAdjustment = request;
const result = await api("/api/account/adjust", request);
pendingAccountAdjustment = null;
if (result.account) renderAccount(result.account);
msg.textContent = result.ok ? `${direction > 0 ? "Пополнено" : "Списано"}: ${Number(value).toFixed(2)} $. Виртуальные деньги.` : result.error || result.message || "Операция отклонена";
if (result.ok) input.value = "";
await poll(loadAccount);
} catch (_) {
msg.textContent = "Ответ не получен. Проверьте журнал. Повтор этой суммы использует тот же идентификатор и не проведёт операцию дважды.";
} finally { accountBusy = false; refreshConnection(); }
}
function buildSettings() {
@@ -55,7 +234,12 @@ function buildSettings() {
};
make(document.getElementById("settingsMain"), MAIN_FIELDS);
make(document.getElementById("settingsMore"), MORE_FIELDS);
document.querySelectorAll("header [data-k]").forEach(el => el.addEventListener("input", () => settingsDirty = true));
document.querySelectorAll("header [data-k]").forEach(el => el.addEventListener("input", () => {
settingsDirty = true;
document.getElementById("settingsMsg").textContent = "Есть несохранённые изменения — нажмите «Применить ко всем монетам»";
}));
if (typeof applyHelpHints === "function") applyHelpHints();
refreshConnection();
}
function toggleMore() {
const m = document.getElementById("settingsMore");
@@ -126,19 +310,27 @@ function renderTiles() {
<div class="plusicon">+</div><div class="route" style="text-align:center">сканер новых монет</div></div>`;
}
async function loadState(rebuild) {
state = await api("/api/state");
const request = ++stateRequest, result = await api("/api/state");
if (request < stateApplied) return;
stateApplied = request; state = result;
renderAccount(state.account);
if (rebuild || !document.querySelector("header [data-k]")) buildSettings();
if ((!selected || (selected !== SCANNER && !state.coins.some(c => c.key === selected))) && state.coins.length) selected = state.coins[0].key;
if ((!selected || (selected !== SCANNER && !state.coins.some(c => c.key === selected))) && state.coins.length) {
detailEpoch++; detail = null; selected = state.coins[0].key;
}
renderTiles();
refreshConnection();
}
function selectCoin(key) {
detailEpoch++;
invalidateRead(key === SCANNER ? "/api/scanner" : `/api/coin/${key}`);
pendingPolls.delete(loadDetail); pendingPolls.delete(loadScanner);
selected = key; localStorage.setItem("sim.coin", key);
seenOpen = new Set(); seenClosed = 0; detail = null;
document.getElementById("center").textContent = "Загрузка выбранной монеты…";
renderTiles(); refreshCenter();
if (state) renderTiles(); refreshCenter(); refreshConnection();
}
function refreshCenter() { if (selected === SCANNER) loadScanner(); else loadDetail(); }
function refreshCenter() { return poll(selected === SCANNER ? loadScanner : loadDetail); }
// --- scanner panel -------------------------------------------------------------------------------
const SCANNER = "__scanner__";
@@ -169,12 +361,14 @@ function scannerSkeleton() {
scannerBuilt = true;
}
async function loadScanner() {
if (selected !== SCANNER || tab !== "sim") return;
const epoch = detailEpoch;
if (!document.getElementById("scRows")) scannerSkeleton();
const s = await api("/api/scanner");
if (selected !== SCANNER || !document.getElementById("scRows")) return;
if (selected !== SCANNER || epoch !== detailEpoch || tab !== "sim" || !document.getElementById("scRows")) return;
if (s.error) { document.getElementById("scMsg").textContent = s.error; return; }
document.getElementById("scStart").disabled = s.running;
document.getElementById("scStop").disabled = !s.running;
setControlDisabled(document.getElementById("scStart"), s.running);
setControlDisabled(document.getElementById("scStop"), !s.running);
document.getElementById("scAuto").checked = s.auto_add;
document.getElementById("scState").innerHTML = s.running
? `<span class="pos">● сканер работает</span> · циклов ${s.cycles}` : `<span class="mut">■ сканер остановлен</span> · циклов ${s.cycles}`;
@@ -190,17 +384,27 @@ async function loadScanner() {
<td>${c.dex_pool}</td><td>${c.lag}</td><td class="${cls(parseFloat(c.follow))}">${c.follow}%</td><td>${c.hit}</td>
<td>${c.t_stat}</td><td class="mut">${c.last_lead || c.last_time}</td><td>${action}</td></tr>`;
}).join("") || '<tr><td colspan="12" class="empty">Пока нет результатов — запустите сканер; первый цикл ≈ 20 минут</td></tr>';
refreshConnection();
}
async function scanner(action) {
const body = action === "config" ? {auto_add: document.getElementById("scAuto").checked}
: {minutes: document.getElementById("scMin").value, coins: document.getElementById("scCoins").value};
await api(`/api/scanner/${action}`, body);
setTimeout(loadScanner, 1200);
if (action === "start") {
body.minutes = Number(String(body.minutes).replace(",", ".")); body.coins = Number(body.coins);
if (!Number.isFinite(body.minutes) || body.minutes <= 0 || !Number.isInteger(body.coins) || body.coins < 1 || body.coins > 13) {
document.getElementById("scMsg").textContent = "Минут на цикл — число больше 0; монет за цикл — целое число от 1 до 13."; return;
}
}
const epoch = detailEpoch;
const result = await api(`/api/scanner/${action}`, body);
if (selected === SCANNER && epoch === detailEpoch && document.getElementById("scMsg")) document.getElementById("scMsg").textContent = result.error || result.message || "Команда подтверждена";
setTimeout(() => { if (selected === SCANNER && epoch === detailEpoch) poll(loadScanner); }, 1200);
}
async function addCoin(symbol) {
const epoch = detailEpoch;
const r = await api("/api/scanner/add", {symbol});
document.getElementById("scMsg").innerHTML = r.ok ? `<span class="pos">${r.message}</span>` : `<span class="neg">${r.error}</span>`;
await loadState(); loadScanner();
if (selected === SCANNER && epoch === detailEpoch && document.getElementById("scMsg")) document.getElementById("scMsg").textContent = r.message || r.error || "";
await loadState(); if (selected === SCANNER && epoch === detailEpoch) await loadScanner();
}
function centerSkeleton() {
@@ -222,7 +426,7 @@ function centerSkeleton() {
<button class="start" id="btnStart" onclick="trade('start')">▶ Старт</button>
<button class="stop" id="btnStop" onclick="trade('stop')">■ Стоп</button>
<button onclick="closePos()">Закрыть все позиции</button>
<button onclick="resetCoin()" title="Обнулить сделки, баланс и открытые позиции этой пары">↺ Сбросить статистику</button>
<button onclick="resetCoin()" title="Очистить статистику пары без изменения общего виртуального счёта; открытые позиции блокируют сброс">↺ Сбросить статистику</button>
<button id="btnReal" onclick="coinReal()" title="Настоящие ордера по этой монете с API-ключами её биржи">…</button>
<span class="statusline" id="cMsg"></span>
</div>
@@ -240,10 +444,10 @@ function centerSkeleton() {
function setRange(s) { range = s; localStorage.setItem("sim.range", s); document.querySelectorAll(".range button").forEach(b => b.classList.toggle("on", +b.dataset.r === s)); drawChart(); }
async function trade(action) { if (!coinReady()) return; const key = detail.key; await api(`/api/coin/${key}/${action}`, {}); loadDetail(); loadState(); }
async function resetCoin() {
if (!coinReady() || !confirm(`Сбросить статистику ${detail.symbol} (${detail.leader} → ${detail.follower})?\nСделки, баланс и открытые позиции этой пары будут обнулены.`)) return;
if (!coinReady() || !confirm(`Сбросить статистику ${detail.symbol} (${detail.leader} → ${detail.follower})?\nИстория этой пары будет очищена. Общий виртуальный счёт не меняется. При открытых позициях сброс недоступен.`)) return;
const r = await api(`/api/coin/${selected}/reset`, {});
document.getElementById("cMsg").textContent = r.message || "";
seenOpen = new Set(); seenClosed = 0;
if (document.getElementById("cMsg")) document.getElementById("cMsg").textContent = r.error || r.message || "";
if (r.ok) { seenOpen = new Set(); seenClosed = 0; }
loadDetail(); loadState();
}
async function removeCoin(key) {
@@ -262,12 +466,12 @@ function coinReady() { return !!detail && detail.key === selected; }
async function closePos(uid, key = detail?.key) {
if (!coinReady() || key !== selected) return;
const r = await api(`/api/coin/${key}/close${uid ? "/" + uid : ""}`, {});
if (key === selected && document.getElementById("cMsg")) document.getElementById("cMsg").textContent = r.message || "";
if (key === selected && document.getElementById("cMsg")) document.getElementById("cMsg").textContent = r.error || r.message || "";
loadDetail();
}
async function loadDetail() {
if (!selected || selected === SCANNER) return;
if (tab !== "sim" || !selected || selected === SCANNER) return;
const key = selected, epoch = detailEpoch, request = ++detailRequest;
const d = await api(`/api/coin/${key}`);
if (key !== selected || epoch !== detailEpoch || request < detailApplied) return;
@@ -312,7 +516,7 @@ async function loadDetail() {
];
} else {
stats = [
["Баланс", d.balance.toFixed(2) + " $", ""], ["Сделок", d.trades, ""], ["В плюс", winPct, ""],
["Общий виртуальный баланс", accountData ? Number(accountData.balance).toFixed(2) + " $" : "—", ""], ["Сделок", d.trades, ""], ["В плюс", winPct, ""],
["Итог", money(d.net), cls(d.net)], ["Комиссии", d.fees.toFixed(4) + " $", ""],
["Открыто", `${d.open} · ${money(d.unrealized)}`, cls(d.unrealized)],
];
@@ -324,12 +528,13 @@ async function loadDetail() {
["Подходит для сделок", suitability(d).html, ""]);
if (state && state.settings.auto_tp) stats.push(["Прогноз", `${d.forecast.toFixed(3)}%`, ""]);
document.getElementById("stats").innerHTML = stats.map(([k, v, c]) => `<div class="stat"><div class="k">${k}</div><div class="v ${c}">${v}</div></div>`).join("");
document.getElementById("btnStart").disabled = d.running;
document.getElementById("btnStop").disabled = !d.running;
setControlDisabled(document.getElementById("btnStart"), d.running);
setControlDisabled(document.getElementById("btnStop"), !d.running);
document.getElementById("cStatus").textContent = (d.running ? "● сделки открываются · " : "■ новые сделки остановлены (цены и прогноз работают) · ") + d.status;
if (d.message) document.getElementById("cMsg").textContent = d.message;
renderRows(d);
drawChart();
refreshConnection();
}
function renderRows(d) {
@@ -494,14 +699,18 @@ function showTab(name) {
document.getElementById("tabSim").classList.toggle("on", name === "sim");
document.getElementById("tabArb").classList.toggle("on", name === "basis");
document.getElementById("tabReal").classList.toggle("on", name === "real");
if (name === "basis") loadBasis();
if (name === "real") { realBuilt = false; loadReal(); }
if (name === "basis") poll(loadBasis);
if (name === "real") { realBuilt = false; poll(loadReal); }
if (name === "sim") refreshCenter();
refreshConnection();
}
// --- real trading: keys, switches, journal -------------------------------------------------------
let real = null, realBuilt = false;
async function loadReal() {
real = await api("/api/real");
const request = ++realRequest, result = await api("/api/real");
if (request < realApplied) return;
realApplied = request; real = result;
const s = real.simulator;
const tpsl = document.getElementById("simRealTpsl");
if (document.activeElement !== tpsl) tpsl.checked = s.exchange_tpsl !== false;
@@ -556,8 +765,8 @@ async function keyCheck(ex) {
}
async function keyDelete(ex) {
if (!confirm("Удалить сохранённые ключи этой биржи?")) return;
await api(`/api/real/keys/${ex}/delete`, {});
document.getElementById(`kmsg-${ex}`).textContent = "удалены";
const r = await api(`/api/real/keys/${ex}/delete`, {});
document.getElementById(`kmsg-${ex}`).textContent = r.ok ? "удалены" : r.error || r.message || "Удаление не подтверждено";
loadReal();
}
async function coinReal() {
@@ -701,13 +910,18 @@ async function crossToggle(ex, on) {
}
async function crossFeesSave() {
if (!basisReady()) return;
const venue = bxVenue, epoch = bxEpoch;
const fees = {}, limits = {};
document.querySelectorAll("#cxBal input[data-cxfee]").forEach(el => {
const [e, leg] = el.dataset.cxfee.split("|"); (fees[e] = fees[e] || {})[leg] = el.value; });
document.querySelectorAll("#cxBal input[data-cxlimit]").forEach(el => limits[el.dataset.cxlimit] = el.value);
const r = await api(`/api/basis/${bxVenue}/settings`, {fees, limits});
const r = await api(`/api/basis/${venue}/settings`, {fees, limits});
if (venue !== bxVenue || epoch !== bxEpoch) return;
document.getElementById("cxBalMsg").textContent = r.ok ? "комиссии и лимиты сделок сохранены" : r.error;
if (r.ok) document.querySelectorAll("#cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => delete el.dataset.dirty);
if (r.ok) {
document.querySelectorAll("#cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => delete el.dataset.dirty);
rememberBasisDraft();
}
loadBasis();
}
const CX_ROWS_HEAD = `<tr><th data-b="base">Монета</th><th data-b="kind_name">Тип</th><th data-b="spot_ex">Покупка на</th><th data-b="fut_ex">Продажа / шорт на</th>
@@ -724,6 +938,29 @@ const CX_POS_HEAD = `<tr><th>Время (МСК)</th><th>Монета</th><th>Т
<th>Funding $</th><th>Комиссии $</th><th>Если закрыть сейчас</th><th></th></tr>`;
let bxHeads = null;
let bxVenue = ["cross", "cross_real"].includes(localStorage.getItem("bx.venue")) ? localStorage.getItem("bx.venue") : "cross", bx = null, bxBuilt = false, bxDirty = false;
const basisDrafts = new Map();
function rememberBasisDraft() {
if (!bxBuilt) return;
const fields = {};
document.querySelectorAll("#bxSettings input, #cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => {
if (!el.dataset.bx && !el.dataset.dirty) return;
if (el.dataset.bx && !bxDirty) return;
const key = el.dataset.bx ? `bx:${el.dataset.bx}` : el.dataset.cxfee ? `fee:${el.dataset.cxfee}` : `limit:${el.dataset.cxlimit}`;
fields[key] = el.type === "checkbox" ? el.checked : el.value;
});
if (Object.keys(fields).length) basisDrafts.set(bxVenue, fields); else basisDrafts.delete(bxVenue);
}
function restoreBasisDraft() {
const draft = basisDrafts.get(bxVenue);
if (!draft) return;
document.querySelectorAll("#bxSettings input, #cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => {
const key = el.dataset.bx ? `bx:${el.dataset.bx}` : el.dataset.cxfee ? `fee:${el.dataset.cxfee}` : `limit:${el.dataset.cxlimit}`;
if (!(key in draft)) return;
if (el.type === "checkbox") el.checked = draft[key]; else el.value = draft[key];
if (el.dataset.bx) bxDirty = true; else el.dataset.dirty = "1";
});
document.getElementById("bxMsg").textContent = "Восстановлены несохранённые изменения этого режима";
}
let bxSort = localStorage.getItem("bx.sort") || "entry_gap";
const BX_FIELDS = [
["amount", "Сумма сделки, $"], ["min_gap_pct", "Мин. расхождение для входа, %"], ["max_gap_pct", "Макс. расхождение, %"],
@@ -743,13 +980,15 @@ function bxTabs() {
: `<button disabled title="пока не подключена">${n} · скоро</button>`).join(" ");
}
function bxSelect(k) {
rememberBasisDraft();
invalidateRead(`/api/basis?ex=${k}`); pendingPolls.delete(loadBasis);
bxEpoch++; bx = null; bxDataVenue = null; bxDirty = false;
setBasisReady(false);
document.getElementById("bxPos").innerHTML = "";
document.getElementById("bxMsg").textContent = "Загрузка выбранного режима…";
bxVenue = k; localStorage.setItem("bx.venue", k); bxBuilt = false;
bxSort = "net_pct"; // the net profit decides the entry — sorted by it
bxTabs(); loadBasis();
bxTabs(); poll(loadBasis); refreshConnection();
}
function bxBuild(s) {
const cross = true; // «Арбитраж»: one mode, simulation or real
@@ -780,14 +1019,22 @@ function bxBuild(s) {
document.querySelectorAll("#basisView th[data-b]").forEach(th => th.onclick = () => {
bxSort = th.dataset.b; localStorage.setItem("bx.sort", bxSort); renderBasis(); });
bxBuilt = true; bxDirty = false;
restoreBasisDraft();
if (typeof applyHelpHints === "function") applyHelpHints();
}
async function basisSave() {
if (!basisReady()) return;
const body = {};
document.querySelectorAll("#bxSettings input").forEach(el => body[el.dataset.bx] = el.type === "checkbox" ? el.checked : el.value);
const r = await api(`/api/basis/${bxVenue}/settings`, body);
const venue = bxVenue, epoch = bxEpoch;
const r = await api(`/api/basis/${venue}/settings`, body);
if (venue !== bxVenue || epoch !== bxEpoch) return;
document.getElementById("bxMsg").textContent = r.ok ? "сохранено" : r.error;
if (r.ok) { bxBuilt = false; loadBasis(); }
if (r.ok) {
bxDirty = false;
rememberBasisDraft(); // Fee/limit drafts belong to their separate Save button.
bxBuilt = false; await loadBasis();
}
}
async function basisRun() {
if (!basisReady()) return;
@@ -807,7 +1054,7 @@ async function basisRun() {
async function basisClose(uid, venue = bxDataVenue) {
if (!basisReady() || venue !== bxVenue) return;
const r = await api(`/api/basis/${venue}/close${uid ? "/" + uid : ""}`, {});
if (venue === bxVenue) document.getElementById("bxMsg").textContent = r.message || "";
if (venue === bxVenue) document.getElementById("bxMsg").textContent = r.error || r.message || "";
loadBasis();
}
async function basisAdopt() {
@@ -820,13 +1067,15 @@ async function basisAdopt() {
}
async function basisReset() {
if (!basisReady()) return;
if (!confirm("Сбросить статистику спот-фьюч? Сделки и открытые позиции будут удалены.")) return;
await api(`/api/basis/${bxVenue}/reset`, {}); loadBasis();
if (!confirm("Сбросить статистику этого режима? История закрытых сделок будет очищена. Общий виртуальный счёт не меняется; при открытых позициях сброс недоступен.")) return;
const venue = bxVenue, r = await api(`/api/basis/${venue}/reset`, {});
if (venue === bxVenue) document.getElementById("bxMsg").textContent = r.error || r.message || (r.ok ? "Статистика сброшена" : "Сброс отклонён");
await loadBasis();
}
function basisReady() { return !!bx && bxDataVenue === bxVenue; }
function setBasisReady(ready) {
document.querySelectorAll("#basisView button, #basisView input").forEach(el => {
if (!el.closest("#bxTabs")) el.disabled = !ready;
if (!el.closest("#bxTabs")) setControlDisabled(el, !ready);
});
}
async function loadBasis() {
@@ -838,9 +1087,11 @@ async function loadBasis() {
bxApplied = request;
if (r.error) { document.getElementById("bxStatus").textContent = r.error; return; }
bx = r; bxDataVenue = venue;
renderAccount(r.paper_account);
if (!bxBuilt) bxBuild(bx.settings);
renderBasis();
setBasisReady(true);
refreshConnection();
}
const dollars = v => v == null ? "—" : (v >= 0 ? "+" : "−") + Math.abs(v).toFixed(2);
const hold = s => s < 60 ? `${s.toFixed(0)} с` : s < 3600 ? `${(s / 60).toFixed(1)} мин` : `${(s / 3600).toFixed(1)} ч`;
@@ -1215,10 +1466,26 @@ function renderArb() {
}
function toggleArb(coin) { arbOpen.has(coin) ? arbOpen.delete(coin) : arbOpen.add(coin); renderArb(); }
window.addEventListener("resize", drawChart);
window.addEventListener("unhandledrejection", event => {
commandNotice(event.reason?.userMessage || event.reason?.message || "Не удалось выполнить действие. Проверьте связь и состояние сервера.", true);
event.preventDefault();
});
window.addEventListener("beforeunload", event => {
rememberBasisDraft();
if (settingsDirty || basisDrafts.size) { event.preventDefault(); event.returnValue = ""; }
});
function startApplication() {
// Register recovery before the first request: a failed initial GET must never stop polling.
setInterval(() => poll(loadState), 2000);
setInterval(() => poll(loadDetail), 1000);
setInterval(() => poll(loadBasis), 500);
setInterval(() => poll(loadReal), 3000);
setInterval(() => poll(loadAccount), 2000);
setInterval(() => { if (selected === SCANNER) poll(loadScanner); }, 5000);
setInterval(refreshConnection, 1000);
poll(async () => { await loadState(true); await refreshCenter(); });
poll(loadReal); poll(loadAccount); showTab(tab);
}
(async () => {
await loadState(true); refreshCenter(); showTab(tab);
setInterval(loadBasis, 500); // the hot links change every 0.5 s
loadReal(); setInterval(loadReal, 3000);
setInterval(loadState, 2000); setInterval(loadDetail, 1000);
setInterval(() => { if (selected === SCANNER) loadScanner(); }, 5000);
startApplication();
})();