const MAIN_FIELDS = [ ["mode", "Режим", "select"], ["stake", "Ставка, $"], ["leverage", "Плечо"], ["min_target_pct", "Тейк-профит, %"], ["stop_loss_pct", "Стоп-лосс, %"], ["max_hold_seconds", "Удержание, с"], ["max_positions", "Позиций одновременно"], ["entry_gap_seconds", "Между входами, с"], ["min_confidence", "Мин. уверенность"], ["auto_stop_pct", "Автостоп: CEX опережает на, %"], ["auto_tp", "Авто тейк-профит по прогнозу", "check"], ["require_leader", "Входить, только если ведущая правда ведёт", "check"], ]; const MORE_FIELDS = [ ["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", "Данные не старше, мс"], ["leader_min_edge", "Перевес ведущей (корр.)"], ["basis_window_seconds", "Разрыв: обычный за, с"], ["basis_entry_z", "Разрыв: вход, σ"], ["basis_exit_z", "Разрыв: выход, σ"], ["basis_min_gap_pct", "Разрыв: мин., %"], ["auto_tp_learn", "Учить долю на истории", "check"], ["one_per_tick", "Одна позиция на шаг цены", "check"], ["cut_loss", "Сразу закрывать в минусе", "check"], ]; let state = null, selected = localStorage.getItem("sim.coin") || null, detail = null; 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 => ({"&":"&", "<":"<", ">":">", '"':""", "'":"'"}[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"}); const MSK_DAY = new Intl.DateTimeFormat("ru-RU", {timeZone: "Europe/Moscow", day: "2-digit", month: "2-digit"}); const msk = seconds => MSK.format(new Date(seconds * 1000)); const mskFull = seconds => { const d = new Date(seconds * 1000), today = MSK_DAY.format(new Date()); return (MSK_DAY.format(d) === today ? "" : MSK_DAY.format(d) + " ") + MSK.format(d); }; 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 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 => `${entry.time ? mskFull(entry.time) : "—"}${escapeHtml(entry.reason || entry.type || entry.action || "Операция")}${entry.amount == null ? "—" : money(entry.amount)}${entry.balance == null ? "—" : Number(entry.balance).toFixed(2)}`).join("") || 'Операций пока нет'; } 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() { const s = state.settings; const make = (box, list) => { box.innerHTML = ""; for (const [key, label, kind] of list) { if (kind === "check") { box.insertAdjacentHTML("beforeend", ``); } else if (kind === "select") { const opts = Object.entries(state.modes).map(([k, v]) => ``).join(""); box.insertAdjacentHTML("beforeend", `
`); } else { box.insertAdjacentHTML("beforeend", `
`); } } }; 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.getElementById("settingsMsg").textContent = "Есть несохранённые изменения — нажмите «Применить ко всем монетам»"; })); if (typeof applyHelpHints === "function") applyHelpHints(); refreshConnection(); } function toggleMore() { const m = document.getElementById("settingsMore"); m.classList.toggle("open"); document.getElementById("moreBtn").textContent = m.classList.contains("open") ? "Скрыть ▴" : "Ещё настройки ▾"; } async function saveSettings() { const body = {}; document.querySelectorAll("header [data-k]").forEach(el => body[el.dataset.k] = el.type === "checkbox" ? el.checked : el.value); const r = await api("/api/settings", body); const msg = document.getElementById("settingsMsg"); msg.textContent = r.ok ? "Настройки применены ко всем монетам" : "Ошибка: " + r.error; msg.style.color = r.ok ? "var(--green)" : "var(--red)"; if (r.ok) { settingsDirty = false; await loadState(true); } } function leaderBadge(c) { const l = c.leadership || {}; if (l.edge == null) return 'проверяется…'; const edge = l.edge, who = edge >= 0 ? c.leader : c.follower; const ok = !c.leader_block; return `${who} ${ok ? "✓" : "✗"} (${Math.abs(l.pct ?? 0).toFixed(0)}%)`; } // Is the coin suitable for trades now: does the leader (DEX / KuCoin) really move before the futures? function suitability(c) { const l = c.leadership || {}, edge = l.edge, min = c.min_edge ?? 0.1; const tip = l.edge == null ? "" : `${c.leader}→${c.follower} ${l.lead.toFixed(2)} / ${c.follower}→${c.leader} ${l.follow.toFixed(2)} · перевес ${edge >= 0 ? "+" : ""}${edge.toFixed(2)}, нужно ${min}`; const pct = l.pct ?? 0; let level, text; if (edge == null) { level = "check"; text = `◌ проверяю, кто ведёт (${(c.grid_minutes || 0).toFixed(1)} из 2 мин данных)`; } else if (edge >= min) { const mins = l.since ? (c.now - l.since) / 60 : 0; const fresh = mins < 2; level = fresh ? "new" : "ok"; text = `● подходит: ${c.leader} опережает ${c.follower} на ${pct.toFixed(0)}%` + (l.since ? ` · ${fresh ? "только что" : "уже " + mins.toFixed(0) + " мин"}, с ${msk(l.since).slice(0, 5)}` : ""); } else if (edge > 0) { level = "near"; text = `◐ почти: ${c.leader} впереди на ${pct.toFixed(0)}%, мало`; } else { level = "no"; text = `○ не подходит: ${c.follower} опережает ${c.leader} на ${(-pct).toFixed(0)}%`; } const stop = c.auto_stop ? `
⏸ ${c.auto_stop}
` : ""; return {level, html: `
${text}
${stop}`}; } function renderTiles() { const box = document.getElementById("tiles"); box.innerHTML = state.coins.map(c => { const realOn = !!(c.real && c.real.enabled); if (realOn) c = {...c, trades: c.real.trades, wins: c.real.wins, net: c.real.net, unrealized: 0}; // exchange figures const pnl = c.net + c.unrealized; const fit = suitability(c); return `
${realOn ? 'РЕАЛ' : ""}
${c.symbol} ${c.follower} ${c.open ? `${c.open} откр.` : ""}
сигнал: ${c.leader} → фьючерс ${c.follower} ${c.follow_ticker}${c.live ? "" : " · нет данных"}
${suitability(c).html}
цена${price(c.price)}
сделок ${c.trades}${money(pnl)}
винрейт${c.trades ? `${(c.wins / c.trades * 100).toFixed(0)}% · ${c.wins} из ${c.trades}` : '—'}
`; }).join("") + `
+
сканер новых монет
`; } async function loadState(rebuild) { 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) { 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 = "Загрузка выбранной монеты…"; if (state) renderTiles(); refreshCenter(); refreshConnection(); } function refreshCenter() { return poll(selected === SCANNER ? loadScanner : loadDetail); } // --- scanner panel ------------------------------------------------------------------------------- const SCANNER = "__scanner__"; let scannerBuilt = false; function scannerSkeleton() { document.getElementById("center").innerHTML = `
Сканер новых монет
ищет монеты, где цена на DEX опережает фьючерсы (запись 15 мин на цикл, по кругу)

Проверенные монеты — «Добавить» переносит монету в левую панель (остановленной); зелёные — где DEX опережал

МонетаПроверокDEX опережалПоследний выводФьючерсПул DEX Лаг, сt+1→t+5Попад.tКогда

Журнал сканера

`; 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 || epoch !== detailEpoch || tab !== "sim" || !document.getElementById("scRows")) return; if (s.error) { document.getElementById("scMsg").textContent = s.error; return; } 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 ? `● сканер работает · циклов ${s.cycles}` : `■ сканер остановлен · циклов ${s.cycles}`; document.getElementById("scLog").textContent = s.log.join("\n"); document.getElementById("scRows").innerHTML = s.coins.map(c => { let action; if (c.in_list) action = 'в левой панели'; else if (c.addable && c.leads) action = ``; else if (c.addable) action = ``; else action = `${c.unsupported || "нельзя добавить"}`; return `${c.symbol}${c.checks} ${c.leads}${c.verdict}${c.futures} ${c.futures_symbol} ${c.dex_pool}${c.lag}${c.follow}%${c.hit} ${c.t_stat}${c.last_lead || c.last_time}${action}`; }).join("") || 'Пока нет результатов — запустите сканер; первый цикл ≈ 20 минут'; 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}; 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}); 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() { document.getElementById("center").innerHTML = `
${[60, 300, 600].map(s => ``).join(" ")}
изменение цены в % от начала окна · ▲▼ — входы, ● — выходы

Сделки — открытые сверху (жёлтым), ✕ закрывает по текущей цене

Время (МСК)Напр.Объём, $ВходВыход / сейчас%Итог, $ КомиссияПричинаСек.Почему вошли
`; document.querySelectorAll(".range button").forEach(b => b.classList.toggle("on", +b.dataset.r === range)); } 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; const r = await api(`/api/coin/${selected}/reset`, {}); 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) { const c = state.coins.find(x => x.key === key); if (!c || !confirm(`Удалить ${c.name}?\n\nСбор цен и сравнение для этой пары остановятся` + (c.open ? `, открытые позиции (${c.open}) закроются по текущей цене` : "") + `.\nВернуть можно через «+» → сканер → «Добавить».`)) return; const r = await api(`/api/coin/${key}/remove`, {}); const wasSelected = selected === key; if (wasSelected) selected = null; await loadState(); if (wasSelected) selectCoin(selected || SCANNER); alert(r.message || r.error || ""); } 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.error || r.message || ""; loadDetail(); } async function loadDetail() { 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; detailApplied = request; if (d.error) { document.getElementById("center").innerHTML = `
${d.error}
`; return; } if (!document.getElementById("chart") || !detail || detail.key !== d.key) centerSkeleton(); detail = d; document.getElementById("cName").innerHTML = `${d.symbol} фьючерс на ${d.follower} сигнал: ${d.leader} → ставки: ${d.follower} ${d.follow_ticker}`; const lat = v => v == null ? "" : ` · ~${v.toFixed(0)} мс`; const linksBox = document.getElementById("cLinks"); const linksHtml = (d.links || []).map(l => `${l.label} ↗`).join(""); if (linksBox.innerHTML !== linksHtml) linksBox.innerHTML = linksHtml; document.getElementById("cFeeds").textContent = `${d.lead_status}${lat(d.lead_latency)} | ${d.follow_status}${lat(d.follow_latency)}`; document.getElementById("lgLead").textContent = `${d.leader}: ${price(d.lead_price)}`; document.getElementById("lgFollow").textContent = `${d.follower} ${d.follow_ticker}: ${price(d.bid)} / ${price(d.ask)}`; const winPct = d.trades ? (d.wins / d.trades * 100).toFixed(0) + "%" : "—"; const realOn = !!(d.real && d.real.enabled); const rb = document.getElementById("btnReal"); rb.textContent = realOn ? "● РЕАЛЬНАЯ торговля — выключить" : "Включить реальную торговлю"; rb.className = realOn ? "realon" : ""; let stats; if (realOn) { // real mode: every figure is from the exchange (its fill history for this coin, the account's balance) const r = d.real, bal = real && real.balances && real.balances[d.exchange]; const age = bal && bal.time ? Math.round(Date.now() / 1000 - bal.time) : null; const balText = !bal ? "нет ключей" : !bal.values ? `${bal.error}` : Object.entries(bal.values).map(([k, v]) => `
${k}: ${typeof v === "number" ? v.toFixed(4) : v}
`).join("") + `
${bal.error ? 'не обновился: ' + bal.error + " · " : ""}${age} с назад
`; const stateText = {"": "нет", opening: "открывается…", open: "открыта", closing: "закрывается…", check: "проверка закрытия…"}[r.state] || r.state; const src = r.source === "биржа" ? `история биржи, ${Math.round(Date.now() / 1000 - r.synced)} с назад` + (r.sync_error ? ` · ${r.sync_error}` : "") : `жду историю биржи${r.sync_error ? ": " + r.sync_error : ""}`; stats = [ ["Баланс на бирже", balText, ""], ["Реальных сделок", r.trades, ""], ["В плюс", r.trades ? `${r.winrate.toFixed(0)}% · ${r.wins} из ${r.trades}` : "—", ""], ["PNL биржи (до комиссий)", money(r.gross), cls(r.gross)], ["Комиссии биржи", "−" + r.fees.toFixed(4) + " $", "neg"], ["Итог после комиссий", money(r.net), cls(r.net)], ["Итог, % от объёма", r.net_pct == null ? "—" : r.net_pct.toFixed(3) + "%", cls(r.net_pct || 0)], ["Реальная позиция", stateText + (r.problem ? `
${r.problem}
` : "") + (r.paused_s > 0 ? `
пауза ${Math.ceil(r.paused_s / 60)} мин: ${r.last_error}
` : ""), r.state || r.paused_s > 0 ? "neg" : ""], ["Откуда цифры", `${src}`, ""], ]; } else { stats = [ ["Общий виртуальный баланс", 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)], ]; } stats.push( ["Сигнал", `${d.signal >= 0 ? "+" : ""}${d.signal.toFixed(3)}%`, cls(d.signal)], ["Уверенность", d.confidence.toFixed(2), ""], ["Кто ведёт", leaderBadge(d), ""], ["Подходит для сделок", suitability(d).html, ""]); if (state && state.settings.auto_tp) stats.push(["Прогноз", `${d.forecast.toFixed(3)}%`, ""]); document.getElementById("stats").innerHTML = stats.map(([k, v, c]) => `
${k}
${v}
`).join(""); 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) { const t = mskFull; const open = d.positions.map(p => { const fresh = !seenOpen.has(p.uid); seenOpen.add(p.uid); return `${t(p.opened)}${p.real ? ' РЕАЛ' : ""}${p.side}${p.usd.toFixed(2)} ${price(p.entry)}${price(p.side === "LONG" ? d.bid : d.ask)}${p.pct.toFixed(3)}% ${money(p.pnl)}тейк ${price(p.target)} · стоп ${price(p.stop)} открыта${p.age.toFixed(0)}${p.why} `; }).join(""); if (d.real && d.real.enabled) { // real mode: closed trades are the real ones, rebuilt from the exchange's own fills const rows = (d.real_trades || []).map(c => ` ${mskFull(c.closed)} РЕАЛ${c.side}${(c.entry * c.coins).toFixed(2)} ${price(c.entry)}${price(c.exit)}${c.pct.toFixed(3)}% ${money(c.net)} ${c.fees.toFixed(4)}${c.exact ? "" : ' ≈'} PNL биржи ${money(c.gross)}${(c.closed - c.opened).toFixed(0)}${c.reason}`).join(""); document.getElementById("rows").innerHTML = open + rows || 'Реальных сделок пока нет'; return; } const freshClosed = d.closed.length - seenClosed; seenClosed = d.closed.length; const closed = d.closed.map((c, i) => ` ${mskFull(Date.parse(c.closed) / 1000)}${c.side}${c.usd.toFixed(2)}${price(c.entry)}${price(c.exit)} ${c.pct.toFixed(3)}%${money(c.net)}${c.fee.toFixed(4)} ${c.reason}${c.hold.toFixed(0)}${c.why}`).join(""); document.getElementById("rows").innerHTML = open + closed || 'Сделок пока нет'; } function drawChart() { const cv = document.getElementById("chart"); if (!cv || !detail) return; const dpr = window.devicePixelRatio || 1, w = cv.clientWidth, h = cv.clientHeight; cv.width = w * dpr; cv.height = h * dpr; const g = cv.getContext("2d"); g.scale(dpr, dpr); g.clearRect(0, 0, w, h); const t1 = detail.now, t0 = t1 - range, pad = {l: 52, r: 10, t: 10, b: 22}; const norm = s => { const pts = s.filter(p => p[0] >= t0); if (!pts.length) return []; const b = pts[0][1]; return pts.map(p => [p[0], (p[1] / b - 1) * 100]); }; const L = norm(detail.lead_series), F = norm(detail.follow_series); const all = L.concat(F).map(p => p[1]); let lo = Math.min(-0.05, ...all), hi = Math.max(0.05, ...all); const span = hi - lo; lo -= span * 0.08; hi += span * 0.08; const X = t => pad.l + (t - t0) / (t1 - t0) * (w - pad.l - pad.r), Y = v => pad.t + (hi - v) / (hi - lo) * (h - pad.t - pad.b); g.strokeStyle = "#2a3240"; g.fillStyle = "#8b95a7"; g.font = "11px Segoe UI"; g.lineWidth = 1; const raw = (hi - lo) / 5, mag = Math.pow(10, Math.floor(Math.log10(raw))); const step = [1, 2, 5, 10].map(k => k * mag).find(s => s >= raw); for (let v = Math.ceil(lo / step) * step; v <= hi; v += step) { g.beginPath(); g.moveTo(pad.l, Y(v)); g.lineTo(w - pad.r, Y(v)); g.stroke(); g.fillText(v.toFixed(step < 0.01 ? 3 : 2) + "%", 4, Y(v) + 4); } for (let k = 0; k <= 4; k++) { const t = t0 + k * range / 4; g.fillText(msk(t), X(t) - 22, h - 6); } const line = (pts, color, stepped) => { if (!pts.length) return; g.strokeStyle = color; g.lineWidth = 1.8; g.beginPath(); pts.forEach((p, i) => { const x = X(p[0]), y = Y(p[1]); if (!i) g.moveTo(x, y); else { if (stepped) g.lineTo(x, Y(pts[i - 1][1])); g.lineTo(x, y); } }); g.lineTo(X(t1), Y(pts[pts.length - 1][1])); g.stroke(); }; line(L, getComputedStyle(document.body).getPropertyValue("--lead"), true); line(F, getComputedStyle(document.body).getPropertyValue("--follow"), false); // trade markers on the futures line const at = t => { let best = null; for (const p of F) { if (p[0] <= t) best = p; else break; } return best || F[0]; }; const mark = (t, up, color, circle) => { if (t < t0 || !F.length) return; const p = at(t); if (!p) return; const x = X(t), y = Y(p[1]); g.fillStyle = color; g.beginPath(); if (circle) g.arc(x, y, 3.5, 0, 7); else if (up) { g.moveTo(x, y - 8); g.lineTo(x - 5, y); g.lineTo(x + 5, y); } else { g.moveTo(x, y + 8); g.lineTo(x - 5, y); g.lineTo(x + 5, y); } g.fill(); }; for (const c of detail.closed) { const tc = Date.parse(c.closed) / 1000; if (tc < t0) continue; mark(tc - c.hold, c.side === "LONG", "#8b95a7"); mark(tc, false, c.net > 0 ? "#2ecc71" : "#ff5c5c", true); } for (const p of detail.positions) mark(p.opened, p.side === "LONG", "#f5c542"); if (!L.length && !F.length) { g.fillStyle = "#8b95a7"; g.fillText("копятся цены…", w / 2 - 40, h / 2); } } // --- arbitrage tab ------------------------------------------------------------------------------- let tab = localStorage.getItem("sim.tab") || "sim", arb = null, arbSort = localStorage.getItem("arb.sort") || "net_transfer"; let arbMarket = localStorage.getItem("arb.market") || "spot"; let arbOpen = new Set(), arbExBuilt = false, feesFor = null; const isSpot = () => arbMarket === "spot"; const val = (id, d) => { const v = parseFloat(document.getElementById(id).value); return isNaN(v) ? d : v; }; // --- budget calculator (top of the page, every tab) ----------------------------------------------------------- // One spot–futures trade of «stake» $: the coins bought on spot (stake + fees) and the short's futures money. With // E $ behind a short of N $ the short is liquidated at a rise of x = (E/N − mmr)/(1 + mmr), so for a wanted x: // E = N·((1 + mmr)·x + mmr) — the same formula the program checks before every short. const CALC_IDS = ["cStake", "cCount", "cLiq", "cEx", "cMmr", "cFee"]; function calcToggle() { const p = document.getElementById("calcPanel"), open = p.style.display === "none"; p.style.display = open ? "" : "none"; document.getElementById("calcBtn").classList.toggle("on", open); if (open) calcRun(); } function calcRun() { const v = id => { const x = parseFloat(String(document.getElementById(id).value).replace(",", ".")); return isFinite(x) ? x : NaN; }; const stake = v("cStake"), n = Math.floor(v("cCount")), liq = v("cLiq"), ex = Math.floor(v("cEx")), mmr = v("cMmr") / 100, fee = v("cFee") / 100; const out = document.getElementById("calcOut"); try { localStorage.setItem("calc", JSON.stringify(Object.fromEntries(CALC_IDS.map(i => [i, document.getElementById(i).value])))); } catch (e) {} if (![stake, n, liq, ex, mmr, fee].every(isFinite) || stake <= 0 || n < 1 || liq <= 0 || ex < 1 || mmr < 0 || fee < 0) { out.innerHTML = '
Заполните поля положительными числами
'; return; } const spot = stake * (1 + fee); // the coins bought on spot, with the buy fee const futFor = x => stake * ((1 + mmr) * x / 100 + mmr); // futures money for a liquidation x % above the entry const fut = futFor(liq), money = x => x.toFixed(2) + " $"; const back = stake * (liq / 100); // what the short loses at the liquidation price // what the program itself requires before an entry (cross.py: SPOT_NEED 1.01, FUT_NEED 1.03 or more for the // liquidation reserve): spot of A ≥ 101 % of the stake, futures of B ≥ max(103 %, the reserve's money) const pSpot = stake * 1.01, pFut = Math.max(stake * 1.03, fut); const progLiq = ((pFut / stake) - mmr) / (1 + mmr) * 100; // money on the accounts for the wanted move to the liquidation: the futures account carries the shorts, the spot // account buys the coins; between exchanges every trade has its spot on one exchange and its short on another const trades = Math.max(1, Math.floor(n * ex / 2)); // n per exchange, each trade takes two exchanges const steps = [...new Set([25, 50, 100, 150, 200, Math.round(liq)])].sort((a, b) => a - b); out.innerHTML = `
Цена может вырасти на ${liq}% до ликвидации шорта — для этого на счетах каждой биржи:
Фьючерсный счёт (${n} шорт.)${money(n * fut)}
Спотовый счёт (${n} покупок монет)${money(n * spot)}
С автопереводом между спотом и фьючерсами биржи${money(n * Math.max(spot, fut))}
Под шорты: ${n} × ${money(fut)}; ликвидация при росте монеты на ${liq}% (шорт теряет ≈ ${money(back)} на сделку). Сделки одной биржи: шорты на её фьючерсах, покупки — на её споте.
Всего на ${ex} ${ex === 1 ? "бирже" : "биржах"}: ${money(n * Math.max(spot, fut) * ex)}
чтобы каждая биржа могла быть и стороной спота, и стороной шорта в ${n} сделках. Минимум, если все ${trades} сделок в одну сторону (спот на одних биржах, шорт на других): ${money(trades * (spot + fut))}
Одна сделка: спот / фьючерсы / обе ноги${money(spot)} / ${money(fut)} / ${money(spot + fut)}
Спот-фьюч на одной бирже (обе ноги там же), ${n} сделок${money(n * (spot + fut))}
${steps.map(x => ``).join("")}
До ликвидацииФьючерсы на 1 шортФьючерсы на ${n} шорт.
+${x}% ${money(futFor(x))}${money(n * futFor(x))}
По текущей логике программы на каждой бирже: ${money(n * Math.max(pSpot, pFut))}, всего на ${ex}: ${money(n * Math.max(pSpot, pFut) * ex)}
Фьючерсный / спотовый счёт${money(n * pFut)} / ${money(n * pSpot)}
${liq < progLiq - 0.5 ? `
Желаемые ${liq}% меньше, чем держит программа: на фьючерсах будет ${money(n * pFut)} и ликвидация ≈ +${progLiq.toFixed(0)}% — дальше, чем вы просили.
` : ""}
Перед входом программа требует на споте биржи A 101% ставки, а на фьючерсах биржи B — не меньше 103% ставки (ликвидация ≈ +${progLiq.toFixed(0)}%) или больше, если «Мин. запас до ликвидации» выше. Меньше — биржа краснеет и не участвует в поиске.
`; } async function calcFromSettings() { const r = await api("/api/basis?ex=cross_real"); if (!r || r.error) return; const limits = ((r.balances || {}).rows || []).map(x => x.limit).filter(x => x != null); document.getElementById("cStake").value = r.settings.amount; document.getElementById("cLiq").value = r.settings.min_liq_pct; if (limits.length) document.getElementById("cCount").value = Math.max(...limits); const keyed = ((r.balances || {}).rows || []).filter(x => x.keys && x.on).length; if (keyed) document.getElementById("cEx").value = keyed; calcRun(); } (function calcInit() { let saved = {}; try { saved = JSON.parse(localStorage.getItem("calc") || "{}"); } catch (e) {} for (const id of CALC_IDS) { const el = document.getElementById(id); if (saved[id] != null) el.value = saved[id]; el.addEventListener("input", calcRun); } })(); function showTab(name) { if (name === "arb") name = "basis"; // the old «Арбитраж» is gone: the one mode lives in «basis» tab = name; localStorage.setItem("sim.tab", name); document.getElementById("simView").style.display = name === "sim" ? "" : "none"; document.getElementById("basisView").style.display = name === "basis" ? "" : "none"; document.getElementById("realView").style.display = name === "real" ? "" : "none"; 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") 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() { 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; const trBox = document.getElementById("simRealTransfer"); if (document.activeElement !== trBox) trBox.checked = s.auto_transfer !== false; const slBox = document.getElementById("simRealSl"); if (document.activeElement !== slBox) slBox.value = s.sl_pct ?? 1.5; const pingBox = document.getElementById("simRealPing"); if (document.activeElement !== pingBox) pingBox.value = s.max_ping_ms ?? 400; const fees = Object.entries(s.fees || {}).map(([e, p]) => `${e} ${p.toFixed(3)}%`).join(", "); const lat = Object.entries(real.latency || {}).map(([h, ms]) => `${h.split(".").slice(0, -1).join(".")} ${ms.toFixed(0)} мс`).join(", "); document.getElementById("simRealFees").textContent = (fees ? `· комиссия с биржи: ${fees}` : "") + (lat ? ` · задержка до бирж: ${lat}` : ""); const realCoins = state ? state.coins.filter(c => c.real && c.real.enabled).map(c => c.symbol) : []; document.getElementById("simReal").classList.toggle("on", realCoins.length > 0); document.getElementById("simRealHint").innerHTML = realCoins.length ? `РЕАЛЬНАЯ ТОРГОВЛЯ: ${realCoins.join(", ")} · остальные монеты — виртуальные сделки` : "виртуальные сделки, ордера на биржи не отправляются"; if (tab !== "real") return; if (!realBuilt) { document.getElementById("keyCards").innerHTML = Object.entries(real.keys).map(([ex, k]) => `
${k.name}
`).join(""); realBuilt = true; } for (const [ex, k] of Object.entries(real.keys)) { document.getElementById(`kst-${ex}`).innerHTML = k.set ? `ключ сохранён: ${k.key}` : 'ключей нет'; } document.getElementById("realJournal").innerHTML = real.journal.map(j => ` ${mskFull(j.time)}${j.tab === "basis" ? "Арбитраж" : "Симулятор"}${j.exchange}${j.coin} ${{open: "открытие", close: "закрытие", orphan: "закрытие осиротевшей", transfer: "перевод USDT"}[j.action] || j.action} ${j.text}`).join("") || 'Реальных ордеров ещё не было'; } async function keySave(ex) { const key = document.getElementById(`kk-${ex}`), secret = document.getElementById(`ks-${ex}`); const r = await api(`/api/real/keys/${ex}`, {api_key: key.value, api_secret: secret.value}); document.getElementById(`kmsg-${ex}`).innerHTML = r.ok ? 'сохранено' : `${r.error}`; if (r.ok) { key.value = ""; secret.value = ""; } loadReal(); } async function keyCheck(ex) { const msg = document.getElementById(`kmsg-${ex}`); msg.textContent = "проверяю…"; const r = await api(`/api/real/keys/${ex}/check`, {}); msg.innerHTML = r.ok ? 'ключи работают: ' + Object.entries(r.balances).map(([k, v]) => `${k} ${typeof v === "number" ? v.toFixed(2) : v}`).join(" · ") + "" : `${r.error}`; } async function keyDelete(ex) { if (!confirm("Удалить сохранённые ключи этой биржи?")) return; const r = await api(`/api/real/keys/${ex}/delete`, {}); document.getElementById(`kmsg-${ex}`).textContent = r.ok ? "удалены" : r.error || r.message || "Удаление не подтверждено"; loadReal(); } async function coinReal() { if (!coinReady()) return; const want = !(detail.real && detail.real.enabled); if (want) { const keys = real && real.keys[detail.exchange]; if (!keys || !keys.set) { alert(`Сначала сохраните API-ключи ${detail.follower} во вкладке «Реальная торговля · API-ключи».`); return; } if (!confirm(`Включить РЕАЛЬНУЮ торговлю для ${detail.symbol} (${detail.follower} ${detail.follow_ticker})?\n\n` + "Каждая новая позиция этой монеты будет открываться настоящим рыночным ордером на фьючерсе " + `(ставка × плечо из настроек)${real.simulator.exchange_tpsl !== false ? ", с TP и SL на бирже" : ""}. ` + "Одна сделка за раз: следующая — только после подтверждённого закрытия.")) return; } const r = await api("/api/real/simulator", {coin: detail.key, enabled: want}); document.getElementById("cMsg").textContent = r.ok ? (want ? "реальная торговля включена" : "реальная торговля выключена") : r.error; await loadState(); await loadReal(); loadDetail(); } async function simRealTransfer() { const r = await api("/api/real/simulator", {auto_transfer: document.getElementById("simRealTransfer").checked}); document.getElementById("simRealMsg").textContent = r.ok ? "сохранено" : r.error; loadReal(); } async function simRealPing() { const r = await api("/api/real/simulator", {max_ping_ms: document.getElementById("simRealPing").value}); document.getElementById("simRealMsg").textContent = r.ok ? "порог пинга сохранён" : r.error; loadReal(); } async function simRealSl() { const r = await api("/api/real/simulator", {sl_pct: document.getElementById("simRealSl").value}); document.getElementById("simRealMsg").textContent = r.ok ? "стоп-лосс сохранён" : r.error; loadReal(); } async function simRealTpsl() { const r = await api("/api/real/simulator", {exchange_tpsl: document.getElementById("simRealTpsl").checked}); document.getElementById("simRealMsg").textContent = r.ok ? "сохранено" : r.error; loadReal(); } async function basisReal() { if (!basisReady()) return; const want = !bx.settings.real; if (want && bx.mode === "cross") { const ready = (bx.balances?.rows || []).filter(r => r.keys && r.on).map(r => r.exchange); if (ready.length < 2) { alert("Нужны API-ключи хотя бы двух включённых бирж (вкладка «Реальная торговля · API-ключи»)."); return; } if (!confirm(`Включить РЕАЛЬНУЮ торговлю «Между биржами»?\n\nБиржи с ключами: ${ready.join(", ")}.\n\nПри входе: шорт на бирже B, ` + `затем покупка тех же монет на споте биржи A на ${bx.settings.amount} $; при возврате разницы к обычной — выкуп шорта и продажа ` + "спота. Нужны USDT на споте A и на фьючерсах B. Одна сделка за раз; изменение баланса считается с момента «Старт».")) return; } else if (want) { const keys = (real && real.keys[bxVenue]) || {}; if (!keys.set) { alert(`Сначала сохраните API-ключи ${bx.venue} во вкладке «Реальная торговля · API-ключи».`); return; } if (!confirm(`Включить РЕАЛЬНУЮ торговлю «Спот-фьюч» на ${bx.venue}?\n\nПри входе: покупка монеты на споте на ` + `${bx.settings.amount} $ и шорт того же количества на фьючерсе; при схождении — выкуп шорта и продажа спота.`)) return; } const r = await api(`/api/basis/${bxVenue}/settings`, {real: want}); document.getElementById("bxMsg").textContent = r.ok ? "" : r.error; loadBasis(); } // --- spot–futures tab -------------------------------------------------------------------------- // «Арбитраж»: the simulation and real trading — two engines, each with its own Start / Stop, settings and trades const BX_VENUES = [["cross", "Симуляция"], ["cross_real", "● Реальная торговля"]]; const BX_READY = new Set(["cross", "cross_real"]); // «between exchanges»: spot on A, perp on B — its own settings and tables const CX_FIELDS = [ ["amount", "Сумма сделки, $"], ["min_net_pct", "Мин. чистая прибыль для входа, %"], ["max_gap_pct", "Макс. разница, %"], ["history_min", "Наблюдать пару не меньше, мин"], ["exit_over_usual_pct", "Закрыть при разнице ≤ обычной + , %"], ["exit_hold_s", "Выход: условие держится не меньше, с (0 — сразу)"], ["stop_widen_pct", "Стоп: разница шире входа на, % (0 — нет)"], ["max_hold_hours", "Макс. держать, ч (0 — нет)"], ["cooldown_s", "Пауза по монете, с"], ["min_turnover", "Мин. оборот каждой ноги 24ч, $"], ["limit_hold_s", "Лимитный вход: ждать, с"], ["negative_funding_before_minutes", "При отрицательном funding не входить за, мин"], ["min_funding_pct", "Не входить, если funding ниже, %"], ["simulation_execution_delay_ms", "Задержка исполнения в симуляции, мс"], ["max_spread_pct", "Макс. спред каждой ноги, % (0 — нет)"], ["confirm_ms", "Подтверждение по стакану: пауза между 2 проверками, мс"], ["min_liq_pct", "Мин. запас до ликвидации шорта при входе, %"], ["liq_close_pct", "Закрыть, если до ликвидации меньше, % (0 — нет)"]]; const CX_CHECKS = [["search_sf", "Искать: спот → фьючерс между биржами"], ["search_in", "Искать: спот → фьючерс внутри биржи"], ["search_ss", "Искать: спот → спот между биржами (реально — из запаса монеты на бирже продажи)"], ["auto_transfer", "Автоперевод USDT между спотом и фьючерсами внутри биржи (реальный режим)"], ["entry_ioc", "Вход первой ногой лимитным IOC по подтверждённой цене: не исполнился — сделки нет (реальный режим)"], ["entry_limit", "Вход лимитным шортом с ожиданием «Лимитный вход: ждать, с» (если IOC выключен)"], ["block_negative_funding", "Не открывать сделку при отрицательном funding"], ["fees_auto", "Комиссии сами корректируются по завершённым реальным сделкам"]]; const CX_EX = ["Bybit", "Binance", "MEXC", "HTX", "Gate"]; // the balances card: built once (the fee fields keep what is typed), its figures refreshed with every update function cxBalBuild() { document.getElementById("cxBal").innerHTML = CX_EX.map(e => ` ${e}
————— 0 /
${e === "Bybit" ? `
зона инноваций:
` : ""}`).join(""); document.querySelectorAll("#cxBal input[data-cxfee], #cxBal input[data-cxlimit]").forEach(el => el.addEventListener("input", () => { el.dataset.dirty = "1"; document.getElementById("cxBalMsg").textContent = "есть изменения — нажмите «Сохранить комиссии и лимиты»"; })); } function cxBalRender() { const b = bx.balances, s = bx.settings; if (!b) return; const money = v => v == null ? "—" : v.toFixed(2); const chg = (p, usd) => p == null ? '—' : `${pct(p, 2)}${usd != null ? ` (${dollars(usd)} $)` : ""}`; for (const r of b.rows) { const e = r.exchange, on = document.getElementById(`cxon-${e}`); if (!on) continue; on.checked = r.on; // too little money for a trade of «Сумма»: red, out of the search until it is topped up (then back by itself) const tr = document.getElementById(`cxrow-${e}`); tr.style.background = r.low_funds ? "rgba(239, 68, 68, 0.16)" : ""; tr.style.boxShadow = r.low_funds ? "inset 3px 0 0 #ef4444" : ""; document.getElementById(`cxk-${e}`).innerHTML = (r.low_funds ? `${r.low_funds} — не участвует в поиске, вернётся сама после пополнения
` : "") + (!r.keys ? "нет API-ключей" : r.error ? `ошибка чтения` : r.age != null ? `${r.age.toFixed(0)} с назад` : ""); document.getElementById(`cxs-${e}`).innerHTML = r.unified ? `${money(r.spot)} единый счёт` : money(r.spot); document.getElementById(`cxf-${e}`).textContent = r.unified ? "—" : money(r.futures); document.getElementById(`cxc-${e}`).textContent = r.coins ? money(r.coins) : r.keys ? "0.00" : "—"; document.getElementById(`cxt-${e}`).innerHTML = `${money(r.total)}`; document.getElementById(`cxd-${e}`).innerHTML = chg(r.change_pct, r.start != null && r.total != null ? r.total - r.start : null); const oc = document.getElementById(`cxo-${e}`); oc.textContent = r.open_count; oc.className = r.open_count >= r.limit ? "neg" : ""; const li = document.querySelector(`#cxBal input[data-cxlimit="${e}"]`); if (document.activeElement !== li && !li.dataset.dirty) li.value = r.limit; for (const leg of ["spot", "fut", "fut_innovation"]) { const el = document.querySelector(`#cxBal input[data-cxfee="${e}|${leg}"]`); if (!el) continue; if (document.activeElement !== el && !el.dataset.dirty) el.value = r[`fee_${leg}`]; document.getElementById(`cxsrc-${e}-${leg}`).textContent = r[`fee_${leg}_src`] || "базовая"; } } document.getElementById("cxBalTotal").innerHTML = `Всего на всех биржах с ключами` + (b.start_time ? ` · отсчёт с запуска ${mskFull(b.start_time)} МСК${b.start_total != null ? ` (было ${money(b.start_total)} $)` : " — жду первые балансы после запуска"}` : ' · изменение считается с момента запуска реальной торговли (кнопка «Старт»)') + `${money(b.total)}${chg(b.change_pct, b.change_usd)}`; } async function crossToggle(ex, on) { if (!basisReady()) return; const r = await api(`/api/basis/${bxVenue}/settings`, {[`use_${ex.toLowerCase()}`]: on}); document.getElementById("cxBalMsg").textContent = r.ok ? `${ex}: ${on ? "включена в поиск и торговлю" : "выключена из поиска и торговли"}` : r.error; loadBasis(); } 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/${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); rememberBasisDraft(); } loadBasis(); } const CX_ROWS_HEAD = `МонетаТипПокупка наПродажа / шорт на Покупка (ask)Продажа (bid)Разница для входа Обычная Выше обычной Чистая прибыль, % Наблюдаем, минFunding (шорт)Объём по ценам, $ Мин. вход, $ Оборот 24ч`; const CX_POS_HEAD = `Время (МСК)МонетаТип · биржиМонетКуплено (A)Продано / шорт (B) Разница при входеОбычная (цель)Разница сейчас До ликвидации, % Funding $Комиссии $Если закрыть сейчас`; 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", "Макс. расхождение, %"], ["exit_gap_pct", "Закрыть при разнице ≤, %"], ["stop_gap_pct", "Стоп: разница ≥, % (0 — нет)"], ["max_hold_hours", "Макс. держать, ч (0 — нет)"], ["max_positions", "Макс. позиций"], ["cooldown_s", "Пауза по монете, с"], ["min_turnover", "Мин. оборот 24ч, $"], ["min_depth", "Мин. объём по ценам, $"], ["new_days", "Новые: фьючерсу ≤ дней"], ["limit_hold_s", "Лимитный вход: ждать, с"], ["max_real_positions", "Одновременно реальных позиций"], ["spot_fee", "Комиссия спот, %"], ["fut_fee", "Комиссия фьюч, %"], ["fut_fee_innovation", "Комиссия фьюч зоны инноваций, %", "bybit"]]; const BX_CHECKS = [["use_new", "Новые монеты"], ["use_innovation", "Зона инноваций / метка «новая» биржи"], ["use_memes", "Мемкойны"], ["all_coins", "Все монеты со спотом и фьючем"], ["auto_transfer", "Автоперевод USDT между спотом и фьючерсами (реальный режим)"], ["entry_limit", "Вход лимитным шортом по цене сигнала, потом спот (реальный режим)"], ["block_negative_funding", "Не открывать сделку при отрицательном funding"]]; function bxTabs() { document.getElementById("bxTabs").innerHTML = BX_VENUES.map(([k, n]) => BX_READY.has(k) ? `` : ``).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(); poll(loadBasis); refreshConnection(); } function bxBuild(s) { const cross = true; // «Арбитраж»: one mode, simulation or real if (!bxHeads) bxHeads = {rows: document.getElementById("bxRowsHead").innerHTML, pos: document.getElementById("bxPosHead").innerHTML, title: document.getElementById("bxTitle").textContent, help: document.getElementById("bxHelp").innerHTML}; document.getElementById("bxRowsHead").innerHTML = cross ? CX_ROWS_HEAD : bxHeads.rows; document.getElementById("bxPosHead").innerHTML = cross ? CX_POS_HEAD : bxHeads.pos; document.getElementById("bxTitle").textContent = (bxVenue === "cross_real" ? "Арбитраж · РЕАЛЬНАЯ торговля" : "Арбитраж · симуляция") + ": купить там, где дешевле, продать там, где дороже, закрыть при возврате разницы к обычной"; document.getElementById("bxHelp").innerHTML = "Связки трёх типов (включаются галочками ниже): спот → фьючерс между биржами (покупка на споте A, шорт на фьючерсе B), " + "спот → фьючерс внутри биржи (обе ноги на одной бирже) и спот → спот (покупка на споте A, продажа тех же монет на " + "споте B из запаса, который лежит на B; при закрытии — продажа на A и выкуп запаса на B). Для каждой связки программа следит за " + "обычной разницей (~30 мин). Вход — по «Чистой прибыли, %»: сколько останется, если разница вернётся к обычной, за вычетом запаса " + "выхода и 4 комиссий (из таблицы бирж). Биржи, их лимиты сделок и комиссии — в карточке «Биржи». Симуляция и реальная торговля — " + "отдельные вкладки: у каждой свой «Старт», свои настройки и сделки. Деньги между биржами программа не переводит."; document.getElementById("bxReal").style.display = "none"; // the tab decides paper or real document.getElementById("bxAdoptBox").style.display = cross ? "none" : ""; document.getElementById("cxBalCard").style.display = cross ? "" : "none"; if (cross) cxBalBuild(); const fieldsList = cross ? CX_FIELDS : BX_FIELDS, checks = cross ? CX_CHECKS : BX_CHECKS; document.getElementById("bxSettings").innerHTML = fieldsList.filter(([, , only]) => !only || only === bxVenue) // a field of one exchange only .map(([k, l]) => `
`).join("") + checks.map(([k, l]) => ``).join(""); document.querySelectorAll("#bxSettings input").forEach(el => el.addEventListener("input", () => { bxDirty = true; document.getElementById("bxMsg").textContent = "есть несохранённые изменения"; })); 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 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) { bxDirty = false; rememberBasisDraft(); // Fee/limit drafts belong to their separate Save button. bxBuilt = false; await loadBasis(); } } async function basisRun() { if (!basisReady()) return; if (bxVenue === "cross_real" && !bx.settings.running) { const ready = (bx.balances?.rows || []).filter(r => r.keys && r.on).map(r => r.exchange); if (!ready.length) { alert("Нет включённых бирж с API-ключами (вкладка «Реальная торговля · API-ключи»)."); return; } const s = bx.settings, kinds = [s.search_sf && "спот → фьючерс между биржами", s.search_in && "спот → фьючерс внутри биржи", s.search_ss && "спот → спот (из запаса монет)"].filter(Boolean).join(", "); if (!confirm(`Запустить РЕАЛЬНУЮ торговлю?\n\nБиржи: ${ready.join(", ")}.\nСвязки: ${kinds || "ни одной не включено"}.\n` + `Сумма сделки: ${s.amount} $. Настоящие ордера с вашими API-ключами; одна сделка за раз, лимиты сделок по биржам.\n` + "Изменение баланса считается с этого момента.")) return; } const r = await api(`/api/basis/${bxVenue}/settings`, {running: !bx.settings.running}); document.getElementById("bxMsg").textContent = r.ok ? "" : r.error; loadBasis(); } 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.error || r.message || ""; loadBasis(); } async function basisAdopt() { if (!basisReady()) return; const base = document.getElementById("bxAdopt").value.trim(); if (!base) return; const r = await api(`/api/basis/${bxVenue}/adopt`, {base, price: document.getElementById("bxAdoptPrice").value.trim()}); document.getElementById("bxAdoptMsg").innerHTML = `${r.message || r.error}`; loadBasis(); } async function basisReset() { if (!basisReady()) return; 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")) setControlDisabled(el, !ready); }); } async function loadBasis() { if (tab !== "basis") return; bxTabs(); const venue = bxVenue, epoch = bxEpoch, request = ++bxRequest; const r = await api(`/api/basis?ex=${venue}`); if (venue !== bxVenue || epoch !== bxEpoch || request < bxApplied) return; 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)} ч`; const kusd = v => v >= 1e6 ? (v / 1e6).toFixed(1) + "M" : v >= 1e3 ? (v / 1e3).toFixed(0) + "K" : v.toFixed(0); // how fresh the prices of an open position are (the fast watch looks several times a second) const freshness = p => p.price_age == null ? '
жду быстрые цены…
' : `
цены ${(p.price_age * 1000).toFixed(0)} мс назад · опрос ${p.fast_ms} мс
`; // the smallest amount both legs accept; red when «Сумма сделки» is below it (then not traded, paper or real) function minEntryCell(r, s) { if (r.min_entry == null) return '?'; const parts = [r.min_spot != null ? `спот ≥ ${r.min_spot.toFixed(2)} $` : "", r.min_fut != null ? `фьюч ≥ ${r.min_fut.toFixed(2)} $` : ""] .filter(Boolean).join(", "); return `${r.min_entry.toFixed(2)}`; } function renderCross() { const s = bx.settings; const bad = Object.entries(bx.ex_status || {}).map(([k, v]) => `${k}: ${v}`).join("; "); document.getElementById("bxStatus").textContent = (bx.status === "ok" ? `связок «спот на A → шорт на B»: ${bx.pairs_total}, обновлено ${msk(bx.updated)} МСК (цикл ${(bx.cycle_ms / 1000).toFixed(1)} с)` : bx.status) + ` · ${s.running ? `новые ${s.real ? "РЕАЛЬНЫЕ" : "бумажные"} сделки открываются` : "остановлено — новые сделки не открываются"}` + (bx.real_pause ? ` · ПАУЗА реальных входов: ${bx.real_pause}` : "") + (bad ? ` · ${bad}` : ""); cxBalRender(); document.getElementById("bxPos").innerHTML = bx.positions.map(p => ` ${mskFull(p.opened)}${p.real ? ' РЕАЛ' : ""}${p.error ? `
${p.error}` : ""}${p.base} спот · фьюч ${p.spot_ex} → ${p.fut_ex}
${p.kind_name}
${p.qty.toPrecision(5)} ${price(p.spot_entry)}${p.spot_now ? ` → ${price(p.spot_now)}` : ""} ${price(p.fut_entry)}${p.fut_now ? ` → ${price(p.fut_now)}` : ""} ${pct(p.entry_gap)}${p.exit_level != null && p.exit_level > p.usual ? `${pct(p.exit_level)} (+${s.exit_over_usual_pct})
сместилась: при входе ${pct(p.usual)}
` : `${pct(p.usual)} (+${s.exit_over_usual_pct})${p.usual_now != null ? `
сейчас обычная ${pct(p.usual_now)}
` : ""}`} ${pct(p.gap_now)}${freshness(p)}${p.exit_held != null ? `
у обычной ${p.exit_held.toFixed(1)} из ${s.exit_hold_s} с — закрытие, если удержится
` : ""} ${p.liq_pct == null ? "—" : `${p.liq_pct.toFixed(1)}%
${price(p.liq_price)} · ${p.liq_src}${ p.liq_src === "биржа" && p.liq_calc ? ` (расчёт ${price(p.liq_calc)})` : ""}
`} ${dollars(p.funding)}${(p.fees_total ?? p.fees).toFixed(3)} ${dollars(p.net)} `).join("") || 'Нет открытых позиций'; const key = bxSort, val = r => r[key]; const rows = [...bx.rows].sort((a, b) => typeof val(a) === "string" ? val(a).localeCompare(val(b)) : (val(b) ?? -1e9) - (val(a) ?? -1e9)); document.querySelectorAll("#basisView th[data-b]").forEach(th => th.classList.toggle("sorted", th.dataset.b === key)); document.getElementById("bxCount").textContent = `Связки: лучшие для ${rows.length} монет (подходят под вход сейчас: ${rows.filter(r => r.fits).length})`; const open = new Set(bx.positions.map(p => p.base)); document.getElementById("bxRows").innerHTML = rows.map(r => ` ${r.base}${r.kind_name}${r.spot_ex} ${r.fut_ex}${r.innovation ? ' иннов.' : ""} ${price(r.spot_ask)} ${price(r.fut_bid)} ${pct(r.entry_gap)}${r.usual == null ? "—" : pct(r.usual)} ${r.excess == null ? "—" : pct(r.excess)} ${r.net_pct == null ? "—" : pct(r.net_pct)}${r.hot ? `
⚡ ${r.price_age == null ? "" : (r.price_age < 1 ? (r.price_age * 1000).toFixed(0) + " мс" : r.price_age.toFixed(1) + " с")}
` : ""} ${r.history.toFixed(0)} ${pct(r.funding_pct, 4)} / ${r.interval_h} ч ${r.depth == null ? '?' : kusd(r.depth)} ${minEntryCell(r, s)}${kusd(r.turnover)} ${open.has(r.base) ? 'в позиции' : r.fits && !r.why ? 'подходит' : r.fits ? `подходит — но ${r.why}` : `${r.why}`}`).join("") || 'Нет связок под фильтры'; document.getElementById("bxTrades").innerHTML = bx.trades.map(t => ` ${mskFull(t.closed)}${t.base} ${t.spot_ex} → ${t.fut_ex} · ${({sf: "спот → фьюч", in: "внутри биржи", ss: "спот → спот"})[t.kind] || ""}${hold(t.closed - t.opened)} ${pct(t.entry_gap)} → ${pct(t.exit_gap)} (обычная ${pct(t.usual)})${dollars(t.spot_pnl)} ${dollars(t.fut_pnl)}${t.fees.toFixed(3)}${dollars(t.funding)} ${dollars(t.net)}${t.amount ? pct(t.net / t.amount * 100, 2) : "—"} ${t.reason}`).join("") || 'Сделок пока нет'; } function renderBasis() { const s = bx.settings, st = bx.stats; const run = document.getElementById("bxRun"); run.textContent = s.running ? "■ Стоп" : "▶ Старт"; run.className = s.running ? "stop" : "start"; const rb = document.getElementById("bxReal"); rb.textContent = s.real ? "● РЕАЛЬНАЯ торговля — выключить" : "Бумажная торговля (включить реальную)"; rb.className = s.real ? "realon" : ""; document.getElementById("bxStatus").textContent = (bx.status === "ok" ? `${bx.venue}: монет со спотом и фьючем ${bx.pairs_total}, обновлено ${msk(bx.updated)} МСК (${bx.cycle_ms} мс)` : bx.status) + ` · мемкойны: ${bx.memes_source} · ${s.running ? "новые сделки открываются" : "остановлено — новые сделки не открываются"}` + (bx.real_pause ? ` · ПАУЗА реальных входов: ${bx.real_pause}` : ""); const wr = st.trades ? `${(st.wins / st.trades * 100).toFixed(0)}% · ${st.wins} из ${st.trades}` : "—"; const ex = st.real ? " (биржа)" : ""; const tiles = [ ["Итог закрытых, $" + ex, dollars(st.net), cls(st.net)], ["Итог, % от вложенного" + ex, st.net_pct == null ? "—" : pct(st.net_pct, 3), cls(st.net_pct || 0)], ["Открыто", st.open, ""], ["Если закрыть открытые, $", dollars(st.unrealized), cls(st.unrealized)], ["Сделок" + ex, st.trades, ""], ["Винрейт", wr, ""], ["Комиссии, $" + ex, st.fees.toFixed(4), "neg"], ["Funding, $ (оценка)", dollars(st.funding), cls(st.funding)], ["Среднее удержание", st.avg_hold_min == null ? "—" : hold(st.avg_hold_min * 60), ""]]; if (st.real && bx.mode === "cross") { const b = bx.balances || {}; tiles.unshift(["Баланс всех бирж, $", b.total == null ? "—" : b.total.toFixed(2), ""], ["С запуска", b.change_pct == null ? 'жду балансы' : `${pct(b.change_pct, 2)} (${dollars(b.change_usd)} $)`, cls(b.change_pct || 0)]); if (!st.exact) tiles.push(["Внимание", 'часть цифр оценочная — биржа не вернула данные', "neg"]); } else if (st.real) { const bal = real && real.balances && real.balances[bxVenue]; tiles.unshift(["Баланс на бирже", !bal ? "нет ключей" : bal.error ? `${bal.error}` : Object.entries(bal.values).map(([k, v]) => `
${k}: ${typeof v === "number" ? v.toFixed(2) : v}
`).join(""), ""]); if (!st.exact) tiles.push(["Внимание", 'часть цифр оценочная — биржа не вернула данные', "neg"]); } document.getElementById("bxStats").innerHTML = tiles .map(([k, v, c]) => `
${k}
${v}
`).join(""); if (bx.mode === "cross") { renderCross(); return; } document.getElementById("bxPos").innerHTML = bx.positions.map(p => ` ${mskFull(p.opened)}${p.real ? ' РЕАЛ' : ""}${p.tp_order ? `
TP на бирже: ${price(p.tp_price)}` : ""}${p.error ? `
${p.error}` : ""}${p.base} спот · фьюч ${p.qty.toPrecision(5)}${price(p.spot_entry)}${p.spot_now ? ` → ${price(p.spot_now)}` : ""} ${price(p.fut_entry)}${p.fut_now ? ` → ${price(p.fut_now)}` : ""} ${pct(p.entry_gap)}${pct(p.gap_now)}${freshness(p)} ${dollars(p.funding)}${(p.fees_total ?? p.fees).toFixed(3)} ${dollars(p.net)} `).join("") || 'Нет открытых позиций'; const key = bxSort, val = r => key === "depth" ? r.depth : key === "turnover" ? Math.min(r.spot_turnover, r.fut_turnover) : r[key]; const rows = [...bx.rows].sort((a, b) => typeof val(a) === "string" ? val(a).localeCompare(val(b)) : (val(b) ?? -1e9) - (val(a) ?? -1e9)); document.querySelectorAll("#basisView th[data-b]").forEach(th => th.classList.toggle("sorted", th.dataset.b === key)); document.getElementById("bxCount").textContent = `Монеты: ${rows.length} (подходят под вход сейчас: ${rows.filter(r => r.fits).length})`; const open = new Set(bx.positions.map(p => p.base)); document.getElementById("bxRows").innerHTML = rows.map(r => { const groups = [r.age_days != null && r.age_days <= s.new_days ? "новая" : "", r.innovation ? "инновации" : "", r.meme ? "мем" : ""].filter(Boolean).join(", "); return ` ${r.base}${r.mult > 1 ? ` фьюч ×${r.mult}` : ""} ${price(r.spot_ask)} ${price(r.fut_bid)} ${pct(r.entry_gap)}${pct(r.exit_gap)} ${pct(r.net_if_closed_pct)} ${pct(r.funding_pct, 4)} / ${r.interval_h} ч ${r.depth == null ? '?' : kusd(r.depth)} ${minEntryCell(r, s)}${kusd(Math.min(r.spot_turnover, r.fut_turnover))} ${r.age_days == null ? "—" : r.age_days.toFixed(0)}${groups} ${open.has(r.base) ? 'в позиции' : r.real_block ? `реально нельзя: ${r.real_block}` : r.fits && !r.why ? 'подходит' : r.fits ? `подходит — но ${r.why}` : `${r.why || ""}`}`; }).join("") || 'Нет монет под фильтры'; document.getElementById("bxTrades").innerHTML = bx.trades.map(t => ` ${mskFull(t.closed)}${t.base}${hold(t.closed - t.opened)} ${pct(t.entry_gap)} → ${pct(t.exit_gap)}${dollars(t.spot_pnl)} ${dollars(t.fut_pnl)}${t.fees.toFixed(3)}${dollars(t.funding)} ${dollars(t.net)}${t.amount ? pct(t.net / t.amount * 100, 2) : "—"} ${t.reason}`).join("") || 'Сделок пока нет'; } function setMarket(m) { arbMarket = m; localStorage.setItem("arb.market", m); arb = null; feesFor = null; arbOpen.clear(); document.getElementById("arbRows").innerHTML = 'загружаю цены…'; loadArb(); } // spot always means moving the coin; futures only when asked function transferOn() { return isSpot() || document.getElementById("afTransfer").checked; } function fee(ex) { const el = document.querySelector(`#afFees input[data-fee="${ex}"]`); const v = el ? parseFloat(el.value) : NaN; return isNaN(v) ? (arb?.taker?.[ex] ?? 0.1) : v; } function buildFees() { const saved = JSON.parse(localStorage.getItem("arb.fees." + arbMarket) || "{}"); document.getElementById("afFees").innerHTML = `Комиссия по рынку (${isSpot() ? "спот" : "фьючерсы"}), %:` + Object.keys(arb.taker).map(e => `
`).join("") + 'базовый уровень без скидок — поправьте под свой'; document.querySelectorAll("#afFees input").forEach(el => el.addEventListener("input", () => { const f = {}; document.querySelectorAll("#afFees input").forEach(i => f[i.dataset.fee] = i.value); localStorage.setItem("arb.fees." + arbMarket, JSON.stringify(f)); renderArb(); })); feesFor = arbMarket; } // filters, transfer time, amount… are remembered in this browser, so they survive reloads and restarts const ARB_FIELDS = ["afCoin", "afVol", "afDepth", "afGross", "afNet", "afSuspect", "afTransfer", "afClosed", "afTMin", "afAmount", "afTFee"]; (function restoreArbSettings() { let saved = {}; try { saved = JSON.parse(localStorage.getItem("arb.settings") || "{}"); } catch (e) {} for (const id of ARB_FIELDS) { const el = document.getElementById(id); if (!el || !(id in saved)) continue; if (el.type === "checkbox") el.checked = !!saved[id]; else el.value = saved[id]; } const save = () => { const out = {}; for (const id of ARB_FIELDS) { const el = document.getElementById(id); if (el) out[id] = el.type === "checkbox" ? el.checked : el.value; } try { localStorage.setItem("arb.settings", JSON.stringify(out)); } catch (e) {} }; ARB_FIELDS.forEach(id => { const el = document.getElementById(id); if (el) { el.addEventListener("input", save); el.addEventListener("change", save); } }); })(); async function arbRun() { await api(`/api/arb/${arbMarket}/${arb && arb.paused ? "start" : "stop"}`, {}); loadArb(); } async function loadArb() { if (tab !== "arb") return; const tmin = val("afTMin", 15); arb = await api(`/api/arb?market=${arbMarket}` + (transferOn() ? `&transfer=${tmin}` : "")); document.getElementById("mkSpot").classList.toggle("on", isSpot()); document.getElementById("mkFut").classList.toggle("on", !isSpot()); document.getElementById("afTransferBox").style.display = isSpot() ? "none" : ""; document.getElementById("afClosedBox").style.display = isSpot() ? "" : "none"; if (!arbExBuilt && arb.taker) { const saved = JSON.parse(localStorage.getItem("arb.ex") || "null"); document.getElementById("afEx").innerHTML = 'Биржи:' + Object.keys(arb.taker).map(e => ``).join(""); document.querySelectorAll("#afEx input, #arbView .controls input").forEach(el => el.addEventListener("input", renderArb)); ["afTransfer", "afTMin"].forEach(id => document.getElementById(id).addEventListener("change", loadArb)); document.querySelectorAll("#arbView th[data-s]").forEach(th => th.addEventListener("click", () => { arbSort = th.dataset.s; localStorage.setItem("arb.sort", arbSort); renderArb(); })); arbExBuilt = true; } if (arb.taker && feesFor !== arbMarket) buildFees(); const run = document.getElementById("arbRun"); run.textContent = arb.paused ? "▶ Старт сканирования" : "■ Стоп сканирования"; run.className = arb.paused ? "start" : "stop"; const unit = isSpot() ? "пар USDT" : "фьюч."; const st = Object.entries(arb.status || {}).map(([e, s]) => `${e}: ${s === "ok" ? arb.counts[e] + " " + unit : s}`).join(" · "); document.getElementById("arbStatus").textContent = (arb.paused ? "Сканирование остановлено — цены ниже последние полученные. " : "") + (arb.updated ? `${st} · обновлено ${msk(arb.updated)} МСК (цикл ${(arb.cycle_ms / 1000).toFixed(1)} с, каждые ${arb.cycle_s} с)` : arb.paused ? "данных ещё нет" : "загружаю цены со всех бирж…"); document.getElementById("arbTitle").textContent = `Арбитраж ${isSpot() ? "на споте" : "на фьючерсах"}: Bybit · Binance · MEXC · HTX · Gate`; document.getElementById("arbFees").textContent = isSpot() ? "спот: купить на одной бирже → вывести монету → продать на другой" : "фьючерсы: лонг на одной + шорт на другой, закрыть при схождении"; renderArb(); } // What is left of the trade amount at current prices after every fee and the transfer, in $ (same sums as the plan). function arbProfit(amount, buyPrice, sellPrice, feeA, feeB, transferFee) { const coins = amount / buyPrice; if (isSpot()) { // buy fee comes out of the coins bought, the withdrawal fee too; the sell fee out of the USDT received const arrive = Math.max(0, coins * (1 - feeA / 100) - transferFee / buyPrice); return arrive * sellPrice * (1 - feeB / 100) - amount; } const fees = 2 * amount * feeA / 100 + amount * feeB / 100 + coins * sellPrice * feeB / 100 + transferFee; return coins * (sellPrice - buyPrice) - fees; } function arbPairs() { const ex = [...document.querySelectorAll("#afEx input:checked")].map(i => i.dataset.ex); localStorage.setItem("arb.ex", JSON.stringify(ex)); const amount = val("afAmount", 1000), tmin = val("afTMin", 15), userFee = val("afTFee", 1); const out = []; for (const r of arb.rows || []) { const ps = Object.entries(r.prices).filter(([e]) => ex.includes(e)); if (ps.length < 2) continue; let best = null; for (const [a, pa] of ps) for (const [b, pb] of ps) { if (a === b) continue; const gross = (pb.bid / pa.ask - 1) * 100; if (!best || gross > best.gross) best = {gross, a, b, pa, pb}; } const fa_ = fee(best.a), fb_ = fee(best.b); const cost = isSpot() ? fa_ + fb_ : 2 * (fa_ + fb_); // spot: two trades; futures: open + close const same = best.a === r.buy && best.b === r.sell; const usual = same ? r.usual : null; const fa = best.pa.funding_8h, fb = best.pb.funding_8h; const t = same ? r.transfer : null; // transfer fee: the exchange's own withdrawal fee where it is public (HTX), otherwise the field value const tfee = t && t.fee_usd != null ? t.fee_usd : userFee; const feePct = transferOn() ? tfee / amount * 100 : 0; const low = same ? r.window_low : null, enough = same && r.history_min != null && r.history_min >= tmin; const closed = !!t && (t.withdraw === false || t.deposit === false); const profit = arbProfit(amount, best.pa.ask, best.pb.bid, fa_, fb_, transferOn() ? tfee : 0); out.push({profit_usd: profit, profit_pct: profit / amount * 100,...r, buy: best.a, sell: best.b, buy_price: best.pa.ask, sell_price: best.pb.bid, buy_url: best.pa.url, sell_url: best.pb.url, gross: best.gross, round_cost: cost, net_now: best.gross - cost, usual, expected: usual == null ? null : best.gross - Math.max(usual, 0) - cost, funding_buy: fa, funding_sell: fb, carry_8h: fa == null || fb == null ? null : fb - fa, depth_usd: same ? r.depth_usd : null, suspect: best.gross > 10 || (same && r.suspect), pa: best.pa, pb: best.pb, fee_a: fa_, fee_b: fb_, held_min: same ? r.held_min : null, window_low: low, history_ok: enough, history_have: same ? r.history_min : null, fee_pct: feePct, tfee, tfee_known: !!(t && t.fee_usd != null), transfer: t, closed, net_transfer: low == null || !enough ? null : low - cost - feePct}); } return out; } const usd = v => v == null ? "—" : v >= 1e6 ? (v / 1e6).toFixed(1) + "M" : v >= 1e3 ? (v / 1e3).toFixed(1) + "K" : v.toFixed(0); const pct = (v, d = 3) => v == null ? "—" : (v >= 0 ? "+" : "") + v.toFixed(d) + "%"; const yesno = (v, yes, no) => v === true ? `${yes}` : v === false ? `${no}` : 'неизвестно'; function transferCell(r) { const t = r.transfer; if (!t) return '—'; const nets = t.networks.length ? t.networks.slice(0, 4).join(", ") : 'сеть не известна'; return `вывод ${r.buy}: ${yesno(t.withdraw, "открыт", "закрыт")}
ввод ${r.sell}: ${yesno(t.deposit, "открыт", "закрыт")}
` + `сети: ${nets}${t.fee_usd != null ? `
комиссия вывода ≈ ${t.fee_usd.toFixed(2)} $ (${t.fee_net})` : ""}`; } // Step-by-step plan for one row, in dollars for the trade amount, every fee included. function arbPlan(r) { const amount = val("afAmount", 1000), tr = transferOn(), tmin = val("afTMin", 15); const money = v => (v >= 0 ? "" : "−") + Math.abs(v).toFixed(2) + " $"; const coins = amount / r.buy_price; const steps = []; const depthWarn = r.depth_usd != null && r.depth_usd < amount ? `
  • По лучшим ценам доступно только ${r.depth_usd.toFixed(0)} $ из ${amount} $ — остальное исполнится хуже, уменьшите сумму
  • ` : ""; const spreadUsed = tr && r.window_low != null && r.history_ok ? r.window_low : r.gross; const holdNote = tr ? (r.history_ok ? ` Разница за последние ${tmin} мин не опускалась ниже ${pct(r.window_low)}.` : ` Сканер видит связку меньше ${tmin} мин — неизвестно, продержится ли разница весь перевод.`) : ""; if (isSpot()) { const feeBuy = amount * r.fee_a / 100; // the fee is usually taken from the coins bought const coinsNet = coins * (1 - r.fee_a / 100); const tCoins = r.tfee / r.buy_price; // withdrawal fee in coins const arrive = Math.max(0, coinsNet - tCoins); const sellValue = arrive * r.sell_price, feeSell = sellValue * r.fee_b / 100; const result$ = sellValue - feeSell - amount; const resultAtLow$ = arrive * r.buy_price * (1 + spreadUsed / 100) * (1 - r.fee_b / 100) - amount; const t = r.transfer || {}; const nets = t.networks && t.networks.length ? t.networks.join(", ") : "общую сеть проверить на обеих биржах"; steps.push(`На ${r.buy} иметь ${amount} USDT на спотовом счёте; на ${r.sell} узнать адрес пополнения ${r.coin} (сеть: ${nets}).` + (t.withdraw === false || t.deposit === false ? ' Сейчас ввод или вывод закрыт — перевод невозможен.' : (t.withdraw == null || t.deposit == null ? ' Статус ввода/вывода этой биржи не публикуется — проверьте на сайте.' : ""))); steps.push(`${r.buy} ${r.pa.symbol}: купить по рынку ≈ ${price(r.buy_price)} на ${amount} $ ≈ ${coins.toPrecision(5)} ${r.coin}. Комиссия ${money(feeBuy)} (${r.fee_a}%) → на счёте ≈ ${coinsNet.toPrecision(5)} ${r.coin}.`); steps.push(`Вывести ${r.coin} с ${r.buy} на ${r.sell}: комиссия вывода ≈ ${money(r.tfee)}${r.tfee_known ? "" : " (из поля «Комиссия перевода»)"}, дойдёт ≈ ${arrive.toPrecision(5)} ${r.coin}, ждать ≈ ${tmin} мин.${holdNote}`); steps.push(`${r.sell} ${r.pb.symbol}: продать по рынку ≈ ${price(r.sell_price)} → ≈ ${money(sellValue)}, комиссия ${money(feeSell)} (${r.fee_b}%).`); steps.push(`Итог по текущим ценам: ${money(sellValue - feeSell)} − ${money(amount)} = ${money(result$)}` + (tr && r.history_ok ? `; если разница сожмётся до минимума за ${tmin} мин: ${money(resultAtLow$)}` : "") + `. Все расходы: ${money(feeBuy + r.tfee + feeSell)}, безубыток при разнице ≥ ${((feeBuy + r.tfee + feeSell) / amount * 100).toFixed(3)}%.`); return `
      ${steps.map(s => `
    1. ${s}
    2. `).join("")}${depthWarn}
    `; } const tfee = tr ? r.tfee : 0; const unitsA = coins / (r.pa.mult || 1), unitsB = coins / (r.pb.mult || 1); const qty = (u, m) => `${u >= 100 ? u.toFixed(0) : u.toPrecision(4)} ${m > 1 ? `ед. (×${m} монет)` : "монет"}`; const feeInA = amount * r.fee_a / 100, feeInB = amount * r.fee_b / 100; const feeOutA = amount * r.fee_a / 100, feeOutB = coins * r.sell_price * r.fee_b / 100; const fees = feeInA + feeInB + feeOutA + feeOutB + tfee; const usual = Math.max(r.usual ?? 0, 0), toUsual$ = amount * (r.gross - usual) / 100; const carry$ = r.carry_8h == null ? null : amount * r.carry_8h / 100; const result$ = amount * spreadUsed / 100 - fees; if (tr) steps.push(`Перевести маржу: на ${r.buy} и ${r.sell} должно быть по ${amount} $ (плечо 1). Перевод ≈ ${tmin} мин, плата ${money(tfee)}.${holdNote}`); else steps.push(`Проверить маржу: на ${r.buy} и на ${r.sell} заранее по ${amount} $ USDT на фьючерсном счёте (плечо 1).`); steps.push(`${r.buy} ${r.pa.symbol}: открыть LONG по рынку ≈ ${price(r.buy_price)}, ${qty(unitsA, r.pa.mult || 1)} на ${amount} $. Комиссия ${money(feeInA)} (${r.fee_a}%).`); steps.push(`Сразу же ${r.sell} ${r.pb.symbol}: открыть SHORT по рынку ≈ ${price(r.sell_price)}, ${qty(unitsB, r.pb.mult || 1)}. Комиссия ${money(feeInB)} (${r.fee_b}%).`); steps.push(`Держать, пока разница не сузится${r.usual != null ? ` до обычной ${pct(usual)}` : " к нулю"}. Funding за 8 ч: ${carry$ == null ? "нет данных" : (carry$ >= 0 ? "получите " : "заплатите ") + money(Math.abs(carry$))} (лонг ${pct(r.funding_buy, 4)}, шорт ${pct(r.funding_sell, 4)}).`); steps.push(`Закрыть обе позиции одновременно по рынку. Комиссии выхода ≈ ${money(feeOutA + feeOutB)}.`); steps.push(`Итог при схождении к нулю: ${money(amount * spreadUsed / 100)} разницы − ${money(fees)} комиссий${tfee ? " и перевода" : ""} = ${money(result$)}` + (r.usual != null ? `; к обычной: ${money(toUsual$ - fees)}` : "") + `. Безубыток при разнице ≥ ${(fees / amount * 100).toFixed(3)}%.`); return `
      ${steps.map(s => `
    1. ${s}
    2. `).join("")}${depthWarn}
    `; } function renderArb() { if (!arb || !arb.rows) return; const q = document.getElementById("afCoin").value.trim().toUpperCase(); const minVol = val("afVol", 0), minDepth = val("afDepth", 0), minGross = val("afGross", 0); const onlyNet = document.getElementById("afNet").checked, hideSuspect = document.getElementById("afSuspect").checked; const hideClosed = isSpot() && document.getElementById("afClosed").checked; const tr = transferOn(), spot = isSpot(); document.querySelectorAll("#arbView .tcol").forEach(el => el.style.display = tr ? "" : "none"); document.querySelectorAll("#arbView .futcol").forEach(el => el.style.display = spot ? "none" : ""); document.querySelectorAll("#arbView .spotcol").forEach(el => el.style.display = spot ? "" : "none"); let rows = arbPairs().filter(r => (!q || r.coin.includes(q)) && r.volume_usd >= minVol && r.gross >= minGross && (!minDepth || (r.depth_usd ?? 0) >= minDepth) && (!hideSuspect || !r.suspect) && (!hideClosed || !r.closed) && (!onlyNet || (tr ? (r.net_transfer ?? r.net_now - r.fee_pct) > 0 : r.net_now > 0))); const key = arbSort, num = v => v == null ? -Infinity : v; rows.sort((a, b) => typeof a[key] === "string" ? a[key].localeCompare(b[key]) : num(b[key]) - num(a[key])); document.querySelectorAll("#arbView th[data-s]").forEach(th => th.classList.toggle("sorted", th.dataset.s === key)); document.getElementById("arbCount").textContent = `Пары: ${rows.length} (монет на 2+ биржах: ${arb.rows.length})`; const cols = 14 + (tr ? 2 : 0); const html = []; for (const r of rows.slice(0, 300)) { html.push(` 0 ? "leadrow" : ""}" onclick="toggleArb('${r.coin}')"> ${r.coin}${r.suspect ? ' разные монеты?' : ""}${r.closed ? ' перевод закрыт' : ""} ${r.buy} ${price(r.buy_price)} ${r.sell} ${price(r.sell_price)} ${pct(r.gross)}${pct(r.net_now)} (−${r.round_cost.toFixed(2)}) ${pct(r.profit_pct, 2)}
    ${r.profit_usd >= 0 ? "+" : "−"}${Math.abs(r.profit_usd).toFixed(2)} $ ${pct(r.usual)}${pct(r.expected)} ${spot ? `${transferCell(r)}` : `${pct(r.carry_8h, 4)}`} ${usd(r.depth_usd)}${usd(r.volume_usd)} ${r.held_min == null ? '—' : r.held_min < 1 ? "<1 мин" : r.held_min.toFixed(0) + " мин"} ${tr ? `${r.history_ok ? pct(r.window_low) : `мало истории ${(r.history_have ?? 0).toFixed(0)} из ${val("afTMin", 15)} мин`} ${pct(r.net_transfer)}` : ""} ${r.exchanges.length}`); if (arbOpen.has(r.coin)) { const cells = Object.entries(r.prices).map(([e, p]) => `${e} bid ${price(p.bid)} / ask ${price(p.ask)}` + (spot ? "" : ` · funding/8ч ${pct(p.funding_8h, 4)}`)).join("
    "); html.push(`
    Что сделать (на сумму сделки, все комиссии): ${arbPlan(r)}
    Цены на всех биржах:
    ${cells}
    `); } } document.getElementById("arbRows").innerHTML = html.join("") || `Нет пар под фильтры`; } 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 () => { startApplication(); })();