Files
Crypto_Scam/web/app.js
T

1225 lines
102 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 = [
["budget", "Бюджет, $"], ["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;
// 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";
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();
}
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", `<label class="check"><input type="checkbox" data-k="${key}" ${s[key] ? "checked" : ""}>${label}</label>`);
} else if (kind === "select") {
const opts = Object.entries(state.modes).map(([k, v]) => `<option value="${k}" ${k === s[key] ? "selected" : ""}>${v}</option>`).join("");
box.insertAdjacentHTML("beforeend", `<div class="field"><label>${label}</label><select data-k="${key}">${opts}</select></div>`);
} else {
box.insertAdjacentHTML("beforeend", `<div class="field"><label>${label}</label><input data-k="${key}" value="${s[key]}"></div>`);
}
}
};
make(document.getElementById("settingsMain"), MAIN_FIELDS);
make(document.getElementById("settingsMore"), MORE_FIELDS);
document.querySelectorAll("header [data-k]").forEach(el => el.addEventListener("input", () => settingsDirty = true));
}
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 '<span class="mut">проверяется…</span>';
const edge = l.edge, who = edge >= 0 ? c.leader : c.follower;
const ok = !c.leader_block;
return `<span class="${ok ? "pos" : "neg"}" title="${c.leader}→${c.follower} ${l.lead.toFixed(2)} / ${c.follower}→${c.leader} ${l.follow.toFixed(2)}">${who} ${ok ? "✓" : "✗"} (${Math.abs(l.pct ?? 0).toFixed(0)}%)</span>`;
}
// 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 ? `<div class="fit fit-no">⏸ ${c.auto_stop}</div>` : "";
return {level, html: `<div class="fit fit-${level}" title="${tip}">${text}</div>${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 `<div class="tile ${c.key === selected ? "active" : ""} fit-${fit.level}" onclick="selectCoin('${c.key}')">
${realOn ? '<span class="realtag" style="position:absolute;top:10px;right:52px" title="реальная торговля: цифры плитки — с биржи">РЕАЛ</span>' : ""}
<span class="dot ${c.running ? "run" : ""}" title="${c.running ? "сделки открываются" : "остановлено"}"></span>
<button class="del" title="Удалить пару и остановить сбор данных" onclick="event.stopPropagation(); removeCoin('${c.key}')">×</button>
<div class="sym">${c.symbol} <span class="cex" title="фьючерс торгуется на ${c.follower}">${c.follower}</span>
${c.open ? `<span class="badge">${c.open} откр.</span>` : ""}</div>
<div class="route">сигнал: ${c.leader} → фьючерс ${c.follower} ${c.follow_ticker}${c.live ? "" : " · нет данных"}</div>
${suitability(c).html}
<div class="row"><span class="mut">цена</span><span>${price(c.price)}</span></div>
<div class="row"><span class="mut">сделок ${c.trades}</span><span class="${cls(pnl)}">${money(pnl)}</span></div>
<div class="row"><span class="mut">винрейт</span>${c.trades
? `<span class="${c.wins / c.trades >= 0.5 ? "pos" : "neg"}">${(c.wins / c.trades * 100).toFixed(0)}% · ${c.wins} из ${c.trades}</span>`
: '<span class="mut">—</span>'}</div>
</div>`;
}).join("") + `<div class="tile plus ${selected === SCANNER ? "active" : ""}" onclick="selectCoin(SCANNER)">
<div class="plusicon">+</div><div class="route" style="text-align:center">сканер новых монет</div></div>`;
}
async function loadState(rebuild) {
state = await api("/api/state");
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;
renderTiles();
}
function selectCoin(key) {
detailEpoch++;
selected = key; localStorage.setItem("sim.coin", key);
seenOpen = new Set(); seenClosed = 0; detail = null;
document.getElementById("center").textContent = "Загрузка выбранной монеты…";
renderTiles(); refreshCenter();
}
function refreshCenter() { if (selected === SCANNER) loadScanner(); else loadDetail(); }
// --- scanner panel -------------------------------------------------------------------------------
const SCANNER = "__scanner__";
let scannerBuilt = false;
function scannerSkeleton() {
document.getElementById("center").innerHTML = `
<div class="card coinhead"><div><span class="name">Сканер новых монет</span></div>
<div class="feeds">ищет монеты, где цена на DEX опережает фьючерсы (запись 15 мин на цикл, по кругу)</div></div>
<div class="card">
<div class="controls">
<div class="field"><label>Минут на цикл</label><input id="scMin" value="15"></div>
<div class="field"><label>Монет за цикл (до 13)</label><input id="scCoins" value="12"></div>
<button class="start" id="scStart" onclick="scanner('start')">▶ Запустить сканер</button>
<button class="stop" id="scStop" onclick="scanner('stop')">■ Остановить</button>
<label class="check"><input type="checkbox" id="scAuto" onchange="scanner('config')">Добавлять найденные в левую панель автоматически</label>
<span class="statusline" id="scState"></span>
</div>
<div class="statusline" id="scMsg" style="margin-top:8px"></div>
</div>
<div class="card">
<h2>Проверенные монеты — «Добавить» переносит монету в левую панель (остановленной); зелёные — где DEX опережал</h2>
<div class="tablewrap"><table>
<thead><tr><th>Монета</th><th>Проверок</th><th>DEX опережал</th><th>Последний вывод</th><th>Фьючерс</th><th>Пул DEX</th>
<th>Лаг, с</th><th>t+1→t+5</th><th>Попад.</th><th>t</th><th>Когда</th><th></th></tr></thead>
<tbody id="scRows"></tbody></table></div>
</div>
<div class="card"><h2>Журнал сканера</h2><pre id="scLog" class="statusline" style="white-space:pre-wrap;margin:0"></pre></div>`;
scannerBuilt = true;
}
async function loadScanner() {
if (!document.getElementById("scRows")) scannerSkeleton();
const s = await api("/api/scanner");
if (selected !== SCANNER || !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;
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}`;
document.getElementById("scLog").textContent = s.log.join("\n");
document.getElementById("scRows").innerHTML = s.coins.map(c => {
let action;
if (c.in_list) action = '<span class="mut">в левой панели</span>';
else if (c.addable && c.leads) action = `<button class="add" onclick="addCoin('${c.symbol}')">+ Добавить</button>`;
else if (c.addable) action = `<button onclick="addCoin('${c.symbol}')" title="DEX пока не опережал — для наблюдения и теста">+ Добавить для теста</button>`;
else action = `<span class="mut">${c.unsupported || "нельзя добавить"}</span>`;
return `<tr class="${c.leads ? "leadrow" : ""}"><td><b>${c.symbol}</b></td><td>${c.checks}</td>
<td class="${c.leads ? "pos" : "mut"}">${c.leads}</td><td>${c.verdict}</td><td>${c.futures} ${c.futures_symbol}</td>
<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>';
}
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);
}
async function addCoin(symbol) {
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();
}
function centerSkeleton() {
document.getElementById("center").innerHTML = `
<div class="card coinhead"><div><span class="name" id="cName"></span><div class="links" id="cLinks"></div></div>
<div class="feeds" id="cFeeds"></div></div>
<div class="card">
<div class="chartbar">
<div class="legend"><span><i style="background:var(--lead)"></i><span id="lgLead"></span></span>
<span><i style="background:var(--follow)"></i><span id="lgFollow"></span></span></div>
<div class="range">${[60, 300, 600].map(s => `<button data-r="${s}" onclick="setRange(${s})">${s / 60} мин</button>`).join(" ")}</div>
</div>
<canvas id="chart"></canvas>
<div class="statusline" style="margin-top:4px">изменение цены в % от начала окна · ▲▼ — входы, ● — выходы</div>
</div>
<div class="card">
<div class="stats" id="stats"></div>
<div class="controls" style="margin-top:10px">
<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 id="btnReal" onclick="coinReal()" title="Настоящие ордера по этой монете с API-ключами её биржи">…</button>
<span class="statusline" id="cMsg"></span>
</div>
<div class="statusline" id="cStatus" style="margin-top:8px"></div>
</div>
<div class="card">
<h2>Сделки — открытые сверху (жёлтым), ✕ закрывает по текущей цене</h2>
<div class="tablewrap"><table>
<thead><tr><th>Время (МСК)</th><th>Напр.</th><th>Объём, $</th><th>Вход</th><th>Выход / сейчас</th><th>%</th><th>Итог, $</th>
<th>Комиссия</th><th>Причина</th><th>Сек.</th><th>Почему вошли</th><th></th></tr></thead>
<tbody id="rows"></tbody></table></div>
</div>`;
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`, {});
document.getElementById("cMsg").textContent = r.message || "";
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.message || "";
loadDetail();
}
async function loadDetail() {
if (!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 = `<div class="empty">${d.error}</div>`; return; }
if (!document.getElementById("chart") || !detail || detail.key !== d.key) centerSkeleton();
detail = d;
document.getElementById("cName").innerHTML = `${d.symbol} <span class="cex">фьючерс на ${d.follower}</span>
<span class="mut" style="font-size:13px;font-weight:400">сигнал: ${d.leader} → ставки: ${d.follower} ${d.follow_ticker}</span>`;
const lat = v => v == null ? "" : ` · ~${v.toFixed(0)} мс`;
const linksBox = document.getElementById("cLinks");
const linksHtml = (d.links || []).map(l => `<a href="${l.url}" target="_blank" rel="noopener noreferrer">${l.label} ↗</a>`).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 ? `<span class="neg" style="font-size:12px">${bal.error}</span>`
: Object.entries(bal.values).map(([k, v]) => `<div style="font-size:13px">${k}: ${typeof v === "number" ? v.toFixed(4) : v}</div>`).join("")
+ `<div class="mut" style="font-size:11px">${bal.error ? '<span class="neg">не обновился: ' + bal.error + "</span> · " : ""}${age} с назад</div>`;
const stateText = {"": "нет", opening: "открывается…", open: "открыта", closing: "закрывается…", check: "проверка закрытия…"}[r.state] || r.state;
const src = r.source === "биржа" ? `история биржи, ${Math.round(Date.now() / 1000 - r.synced)} с назад` +
(r.sync_error ? ` · <span class="neg">${r.sync_error}</span>` : "") : `<span class="neg">жду историю биржи${r.sync_error ? ": " + r.sync_error : ""}</span>`;
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 ? `<div class="neg" style="font-size:11px">${r.problem}</div>` : "")
+ (r.paused_s > 0 ? `<div class="neg" style="font-size:11px">пауза ${Math.ceil(r.paused_s / 60)} мин: ${r.last_error}</div>` : ""),
r.state || r.paused_s > 0 ? "neg" : ""],
["Откуда цифры", `<span style="font-size:12px">${src}</span>`, ""],
];
} else {
stats = [
["Баланс", d.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]) => `<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;
document.getElementById("cStatus").textContent = (d.running ? "● сделки открываются · " : "■ новые сделки остановлены (цены и прогноз работают) · ") + d.status;
if (d.message) document.getElementById("cMsg").textContent = d.message;
renderRows(d);
drawChart();
}
function renderRows(d) {
const t = mskFull;
const open = d.positions.map(p => {
const fresh = !seenOpen.has(p.uid); seenOpen.add(p.uid);
return `<tr class="open ${fresh ? "flash" : ""}"><td>${t(p.opened)}${p.real ? ' <span class="realtag">РЕАЛ</span>' : ""}</td><td>${p.side}</td><td>${p.usd.toFixed(2)}</td>
<td>${price(p.entry)}</td><td>${price(p.side === "LONG" ? d.bid : d.ask)}</td><td class="${cls(p.pct)}">${p.pct.toFixed(3)}%</td>
<td class="${cls(p.pnl)}">${money(p.pnl)}</td><td class="mut">тейк ${price(p.target)} · стоп ${price(p.stop)}</td>
<td class="mut">открыта</td><td>${p.age.toFixed(0)}</td><td class="why">${p.why}</td>
<td><button class="x" title="Закрыть по текущей цене" onclick="closePos(${p.uid}, '${d.key}')">✕</button></td></tr>`;
}).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 => `<tr>
<td>${mskFull(c.closed)} <span class="realtag">РЕАЛ</span></td><td>${c.side}</td><td>${(c.entry * c.coins).toFixed(2)}</td>
<td>${price(c.entry)}</td><td>${price(c.exit)}</td><td class="${cls(c.pct)}">${c.pct.toFixed(3)}%</td>
<td class="${cls(c.net)}" title="PNL биржи ${money(c.gross)} − комиссии ${c.fees.toFixed(4)} $">${money(c.net)}</td>
<td>${c.fees.toFixed(4)}${c.exact ? "" : ' <span class="neg" title="биржа не вернула точные данные">≈</span>'}</td>
<td>PNL биржи ${money(c.gross)}</td><td>${(c.closed - c.opened).toFixed(0)}</td><td class="why">${c.reason}</td><td></td></tr>`).join("");
document.getElementById("rows").innerHTML = open + rows || '<tr><td colspan="12" class="empty">Реальных сделок пока нет</td></tr>';
return;
}
const freshClosed = d.closed.length - seenClosed; seenClosed = d.closed.length;
const closed = d.closed.map((c, i) => `<tr class="${i < freshClosed && freshClosed < d.closed.length ? "flash" : ""}">
<td>${mskFull(Date.parse(c.closed) / 1000)}</td><td>${c.side}</td><td>${c.usd.toFixed(2)}</td><td>${price(c.entry)}</td><td>${price(c.exit)}</td>
<td class="${cls(c.pct)}">${c.pct.toFixed(3)}%</td><td class="${cls(c.net)}">${money(c.net)}</td><td>${c.fee.toFixed(4)}</td>
<td>${c.reason}</td><td>${c.hold.toFixed(0)}</td><td class="why">${c.why}</td><td></td></tr>`).join("");
document.getElementById("rows").innerHTML = open + closed || '<tr><td colspan="12" class="empty">Сделок пока нет</td></tr>';
}
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 = '<div class="neg">Заполните поля положительными числами</div>'; 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 = `
<div class="big">Цена может вырасти на <b style="color:var(--yellow)">${liq}%</b> до ликвидации шорта — для этого на счетах каждой биржи:
<div class="row2" style="margin-top:6px"><span>Фьючерсный счёт (${n} шорт.)</span><b>${money(n * fut)}</b></div>
<div class="row2"><span>Спотовый счёт (${n} покупок монет)</span><b>${money(n * spot)}</b></div>
<div class="row2"><span>С автопереводом между спотом и фьючерсами биржи</span><b>${money(n * Math.max(spot, fut))}</b></div>
<div class="note">Под шорты: ${n} × ${money(fut)}; ликвидация при росте монеты на ${liq}% (шорт теряет ≈ ${money(back)} на сделку).
Сделки одной биржи: шорты на её фьючерсах, покупки — на её споте.</div></div>
<div class="big">Всего на ${ex} ${ex === 1 ? "бирже" : "биржах"}: <b>${money(n * Math.max(spot, fut) * ex)}</b>
<div class="note">чтобы каждая биржа могла быть и стороной спота, и стороной шорта в ${n} сделках. Минимум, если
все ${trades} сделок в одну сторону (спот на одних биржах, шорт на других): ${money(trades * (spot + fut))}</div></div>
<div class="row2"><span>Одна сделка: спот / фьючерсы / обе ноги</span><b>${money(spot)} / ${money(fut)} / ${money(spot + fut)}</b></div>
<div class="row2"><span>Спот-фьюч на одной бирже (обе ноги там же), ${n} сделок</span><b>${money(n * (spot + fut))}</b></div>
<table style="margin-top:4px;font-size:12px"><thead><tr><th>До ликвидации</th><th>Фьючерсы на 1 шорт</th><th>Фьючерсы на ${n} шорт.</th></tr></thead><tbody>
${steps.map(x => `<tr${x === Math.round(liq) ? ' style="color:var(--yellow);font-weight:600"' : ""}><td>+${x}%</td>
<td>${money(futFor(x))}</td><td>${money(n * futFor(x))}</td></tr>`).join("")}</tbody></table>
<div class="big" style="border:1px solid var(--accent)">По текущей логике программы на каждой бирже: <b>${money(n * Math.max(pSpot, pFut))}</b>,
всего на ${ex}: <b>${money(n * Math.max(pSpot, pFut) * ex)}</b>
<div class="row2" style="margin-top:4px"><span>Фьючерсный / спотовый счёт</span><b>${money(n * pFut)} / ${money(n * pSpot)}</b></div>
${liq < progLiq - 0.5 ? `<div class="note" style="color:var(--yellow)">Желаемые ${liq}% меньше, чем держит программа:
на фьючерсах будет ${money(n * pFut)} и ликвидация ≈ +${progLiq.toFixed(0)}% — дальше, чем вы просили.</div>` : ""}
<div class="note">Перед входом программа требует на споте биржи A 101% ставки, а на фьючерсах биржи B — не меньше
103% ставки (ликвидация ≈ +${progLiq.toFixed(0)}%) или больше, если «Мин. запас до ликвидации» выше. Меньше — биржа
краснеет и не участвует в поиске.</div></div>`;
}
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") loadBasis();
if (name === "real") { realBuilt = false; loadReal(); }
}
// --- real trading: keys, switches, journal -------------------------------------------------------
let real = null, realBuilt = false;
async function loadReal() {
real = await api("/api/real");
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
? `<span class="neg"><b>РЕАЛЬНАЯ ТОРГОВЛЯ:</b> ${realCoins.join(", ")}</span> · остальные монеты — виртуальные сделки`
: "виртуальные сделки, ордера на биржи не отправляются";
if (tab !== "real") return;
if (!realBuilt) {
document.getElementById("keyCards").innerHTML = Object.entries(real.keys).map(([ex, k]) => `<div class="keycard">
<b>${k.name}</b><span class="statusline" id="kst-${ex}"></span>
<input id="kk-${ex}" placeholder="API key" autocomplete="off" spellcheck="false">
<input id="ks-${ex}" type="password" placeholder="API secret" autocomplete="new-password" spellcheck="false">
<div class="controls"><button class="primary" onclick="keySave('${ex}')">Сохранить</button>
<button onclick="keyCheck('${ex}')">Проверить (баланс)</button>
<button onclick="keyDelete('${ex}')">Удалить</button></div>
<span class="statusline" id="kmsg-${ex}"></span></div>`).join("");
realBuilt = true;
}
for (const [ex, k] of Object.entries(real.keys)) {
document.getElementById(`kst-${ex}`).innerHTML = k.set ? `<span class="pos">ключ сохранён: ${k.key}</span>` : '<span class="mut">ключей нет</span>';
}
document.getElementById("realJournal").innerHTML = real.journal.map(j => `<tr>
<td>${mskFull(j.time)}</td><td>${j.tab === "basis" ? "Арбитраж" : "Симулятор"}</td><td>${j.exchange}</td><td><b>${j.coin}</b></td>
<td>${{open: "открытие", close: "закрытие", orphan: "закрытие осиротевшей", transfer: "перевод USDT"}[j.action] || j.action}</td>
<td class="${j.ok ? "pos" : "neg"}" style="white-space:normal">${j.text}</td></tr>`).join("")
|| '<tr><td colspan="6" class="empty">Реальных ордеров ещё не было</td></tr>';
}
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 ? '<span class="pos">сохранено</span>' : `<span class="neg">${r.error}</span>`;
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 ? '<span class="pos">ключи работают: ' + Object.entries(r.balances).map(([k, v]) =>
`${k} ${typeof v === "number" ? v.toFixed(2) : v}`).join(" · ") + "</span>" : `<span class="neg">${r.error}</span>`;
}
async function keyDelete(ex) {
if (!confirm("Удалить сохранённые ключи этой биржи?")) return;
await api(`/api/real/keys/${ex}/delete`, {});
document.getElementById(`kmsg-${ex}`).textContent = "удалены";
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", "Лимитный вход: ждать, с"],
["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 выключен)"],
["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 => `<tr id="cxrow-${e}">
<td><b>${e}</b><div class="mut" style="font-size:10px" id="cxk-${e}"></div></td>
<td><label class="check"><input type="checkbox" id="cxon-${e}" onchange="crossToggle('${e}', this.checked)"> вкл</label></td>
<td id="cxs-${e}">—</td><td id="cxf-${e}">—</td><td id="cxc-${e}">—</td><td id="cxt-${e}"><b>—</b></td><td id="cxd-${e}">—</td>
<td style="white-space:nowrap"><span id="cxo-${e}">0</span> / <input data-cxlimit="${e}" style="width:44px"></td>
<td><input data-cxfee="${e}|spot" style="width:70px"><div class="mut" style="font-size:10px" id="cxsrc-${e}-spot"></div></td>
<td><input data-cxfee="${e}|fut" style="width:70px"><div class="mut" style="font-size:10px" id="cxsrc-${e}-fut"></div>${e === "Bybit"
? `<div style="margin-top:4px"><span class="mut" style="font-size:10px">зона инноваций:</span><br>
<input data-cxfee="${e}|fut_innovation" style="width:70px"><div class="mut" style="font-size:10px" id="cxsrc-${e}-fut_innovation"></div></div>` : ""}</td></tr>`).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 ? '<span class="mut">—</span>'
: `<span class="${cls(p)}">${pct(p, 2)}${usd != null ? ` <span style="font-size:11px">(${dollars(usd)} $)</span>` : ""}</span>`;
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
? `<span class="neg" style="white-space:normal">${r.low_funds} — не участвует в поиске, вернётся сама после пополнения</span><br>` : "") +
(!r.keys ? "нет API-ключей"
: r.error ? `<span class="neg" title="${r.error.replace(/"/g, "'")}">ошибка чтения</span>`
: r.age != null ? `${r.age.toFixed(0)} с назад` : "");
document.getElementById(`cxs-${e}`).innerHTML = r.unified ? `${money(r.spot)} <span class="mut" style="font-size:10px">единый счёт</span>` : 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 = `<b>${money(r.total)}</b>`;
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 = `<tr><td colspan="5"><b>Всего на всех биржах с ключами</b>` +
(b.start_time ? ` <span class="mut">· отсчёт с запуска ${mskFull(b.start_time)} МСК${b.start_total != null ? ` (было ${money(b.start_total)} $)` : " — жду первые балансы после запуска"}</span>`
: ' <span class="mut">· изменение считается с момента запуска реальной торговли (кнопка «Старт»)</span>') +
`</td><td><b>${money(b.total)}</b></td><td>${chg(b.change_pct, b.change_usd)}</td><td colspan="3"></td></tr>`;
}
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 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});
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);
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>
<th data-b="spot_ask">Покупка (ask)</th><th data-b="fut_bid">Продажа (bid)</th><th data-b="entry_gap">Разница для входа</th>
<th data-b="usual" title="Средняя разница этой связки за ~30 мин наблюдения">Обычная</th>
<th data-b="excess" title="Насколько разница сейчас выше обычной — это и есть то, что вернётся при схождении">Выше обычной</th>
<th data-b="net_pct" title="Чистая прибыль от суммы сделки, если разница вернётся к обычной: (разница − обычная) − запас выхода − 4 комиссии двух бирж. Бот входит по этому параметру">Чистая прибыль, %</th>
<th data-b="history">Наблюдаем, мин</th><th data-b="funding_pct">Funding (шорт)</th><th data-b="depth">Объём по ценам, $</th>
<th data-b="min_entry" title="Минимальная сумма сделки, которую примут обе ноги: покупка на споте биржи A и шорт на фьючерсе биржи B (мин. ордер, мин. лот). Если «Сумма сделки» меньше — связка не торгуется ни на бумаге, ни реально">Мин. вход, $</th>
<th data-b="turnover">Оборот 24ч</th><th></th></tr>`;
const CX_POS_HEAD = `<tr><th>Время (МСК)</th><th>Монета</th><th>Тип · биржи</th><th>Монет</th><th>Куплено (A)</th><th>Продано / шорт (B)</th>
<th>Разница при входе</th><th>Обычная (цель)</th><th>Разница сейчас</th>
<th title="На сколько % должна вырасти цена фьючерса, чтобы биржа B ликвидировала шорт (спот на A его не прикрывает). Реальные позиции — цифра биржи, обновляется каждые 30 с">До ликвидации, %</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;
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", "Вход лимитным шортом по цене сигнала, потом спот (реальный режим)"]];
function bxTabs() {
document.getElementById("bxTabs").innerHTML = BX_VENUES.map(([k, n]) => BX_READY.has(k)
? `<button class="${k === bxVenue ? "on" : ""}" onclick="bxSelect('${k}')">${n}</button>`
: `<button disabled title="пока не подключена">${n} · скоро</button>`).join(" ");
}
function bxSelect(k) {
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();
}
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 =
"Связки трёх типов (включаются галочками ниже): <b>спот → фьючерс между биржами</b> (покупка на споте A, шорт на фьючерсе B), " +
"<b>спот → фьючерс внутри биржи</b> (обе ноги на одной бирже) и <b>спот → спот</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]) => `<div class="field"><label>${l}</label><input data-bx="${k}" style="width:110px" value="${s[k]}"></div>`).join("") +
checks.map(([k, l]) => `<label class="check"><input type="checkbox" data-bx="${k}" ${s[k] ? "checked" : ""}>${l}</label>`).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;
}
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);
document.getElementById("bxMsg").textContent = r.ok ? "сохранено" : r.error;
if (r.ok) { bxBuilt = false; 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.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 = `<span class="${r.ok ? "pos" : "neg"}">${r.message || r.error}</span>`;
loadBasis();
}
async function basisReset() {
if (!basisReady()) return;
if (!confirm("Сбросить статистику спот-фьюч? Сделки и открытые позиции будут удалены.")) return;
await api(`/api/basis/${bxVenue}/reset`, {}); 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;
});
}
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;
if (!bxBuilt) bxBuild(bx.settings);
renderBasis();
setBasisReady(true);
}
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 ? '<div class="mut" style="font-size:10px">жду быстрые цены…</div>'
: `<div class="mut" style="font-size:10px">цены ${(p.price_age * 1000).toFixed(0)} мс назад · опрос ${p.fast_ms} мс</div>`;
// 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 '<td class="mut" title="правила биржи ещё не загружены">?</td>';
const parts = [r.min_spot != null ? `спот ≥ ${r.min_spot.toFixed(2)} $` : "", r.min_fut != null ? `фьюч ≥ ${r.min_fut.toFixed(2)} $` : ""]
.filter(Boolean).join(", ");
return `<td class="${s.amount < r.min_entry ? "neg" : ""}" title="${parts}">${r.min_entry.toFixed(2)}</td>`;
}
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 => `<tr class="open">
<td>${mskFull(p.opened)}${p.real ? ' <span class="realtag">РЕАЛ</span>' : ""}${p.error ? `<br><span class="neg" style="white-space:normal">${p.error}</span>` : ""}</td><td><b>${p.base}</b> <a href="${p.spot_url}" target="_blank" rel="noopener">спот</a> · <a href="${p.fut_url}" target="_blank" rel="noopener">фьюч</a></td>
<td>${p.spot_ex} → ${p.fut_ex}<div class="mut" style="font-size:10px">${p.kind_name}</div></td><td>${p.qty.toPrecision(5)}</td>
<td>${price(p.spot_entry)}${p.spot_now ? ` <span class="mut">→ ${price(p.spot_now)}</span>` : ""}</td>
<td>${price(p.fut_entry)}${p.fut_now ? ` <span class="mut">→ ${price(p.fut_now)}</span>` : ""}</td>
<td>${pct(p.entry_gap)}</td><td class="mut">${p.exit_level != null && p.exit_level > p.usual
? `<b style="color:var(--text)">${pct(p.exit_level)}</b> (+${s.exit_over_usual_pct})<div style="font-size:10px">сместилась: при входе ${pct(p.usual)}</div>`
: `${pct(p.usual)} (+${s.exit_over_usual_pct})${p.usual_now != null ? `<div style="font-size:10px">сейчас обычная ${pct(p.usual_now)}</div>` : ""}`}</td>
<td class="${p.gap_now != null && p.exit_target != null && p.gap_now <= p.exit_target ? "pos" : ""}">${pct(p.gap_now)}${freshness(p)}${p.exit_held != null
? `<div class="pos" style="font-size:10px">у обычной ${p.exit_held.toFixed(1)} из ${s.exit_hold_s} с — закрытие, если удержится</div>` : ""}</td>
<td class="${p.liq_pct == null ? "mut" : p.liq_pct < s.liq_close_pct * 1.5 ? "neg" : ""}">${p.liq_pct == null ? "—"
: `<b>${p.liq_pct.toFixed(1)}%</b><div class="mut" style="font-size:10px">${price(p.liq_price)} · ${p.liq_src}${
p.liq_src === "биржа" && p.liq_calc ? ` (расчёт ${price(p.liq_calc)})` : ""}</div>`}</td>
<td class="${cls(p.funding)}">${dollars(p.funding)}</td><td>${(p.fees_total ?? p.fees).toFixed(3)}</td>
<td class="${cls(p.net ?? 0)}"><b>${dollars(p.net)}</b></td>
<td><button class="x" title="Закрыть обе ноги по текущим ценам" onclick="basisClose(${p.uid}, '${bxDataVenue}')">×</button></td></tr>`).join("")
|| '<tr><td colspan="14" class="empty">Нет открытых позиций</td></tr>';
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 => `<tr class="${r.fits ? "leadrow" : ""}">
<td><b>${r.base}</b></td><td class="mut">${r.kind_name}</td><td>${r.spot_ex}</td>
<td>${r.fut_ex}${r.innovation ? ' <span class="mut" style="font-size:10px" title="фьючерс зоны инноваций — своя, более высокая комиссия">иннов.</span>' : ""}</td>
<td><a href="${r.spot_url}" target="_blank" rel="noopener">${price(r.spot_ask)}</a></td>
<td><a href="${r.fut_url}" target="_blank" rel="noopener">${price(r.fut_bid)}</a></td>
<td><b>${pct(r.entry_gap)}</b></td><td class="mut">${r.usual == null ? "—" : pct(r.usual)}</td>
<td>${r.excess == null ? "—" : pct(r.excess)}</td>
<td class="${cls(r.net_pct ?? 0)}" title="комиссии 4 сделок: ${r.fees_pct.toFixed(3)}%"><b>${r.net_pct == null ? "—" : pct(r.net_pct)}</b>${r.hot
? `<div class="pos" style="font-size:10px" title="в плюсе: цены этой связки обновляются каждые 0.5 с и вход проверяется сразу">⚡ ${r.price_age == null ? "" : (r.price_age < 1 ? (r.price_age * 1000).toFixed(0) + " мс" : r.price_age.toFixed(1) + " с")}</div>` : ""}</td>
<td class="${r.history >= s.history_min ? "" : "mut"}">${r.history.toFixed(0)}</td>
<td class="${cls(r.funding_pct)}">${pct(r.funding_pct, 4)} / ${r.interval_h} ч</td>
<td>${r.depth == null ? '<span class="mut" title="биржа не сообщает объём по лучшей цене">?</span>' : kusd(r.depth)}</td>
${minEntryCell(r, s)}<td>${kusd(r.turnover)}</td>
<td style="white-space:normal;max-width:260px">${open.has(r.base) ? '<span class="badge">в позиции</span>'
: r.fits && !r.why ? '<span class="pos">подходит</span>'
: r.fits ? `<span class="pos">подходит</span> <span class="mut">— но ${r.why}</span>` : `<span class="mut">${r.why}</span>`}</td></tr>`).join("")
|| '<tr><td colspan="16" class="empty">Нет связок под фильтры</td></tr>';
document.getElementById("bxTrades").innerHTML = bx.trades.map(t => `<tr>
<td>${mskFull(t.closed)}</td><td><b>${t.base}</b> <span class="mut">${t.spot_ex} → ${t.fut_ex} · ${({sf: "спот → фьюч", in: "внутри биржи", ss: "спот → спот"})[t.kind] || ""}</span></td><td>${hold(t.closed - t.opened)}</td>
<td>${pct(t.entry_gap)} → ${pct(t.exit_gap)} <span class="mut">(обычная ${pct(t.usual)})</span></td><td class="${cls(t.spot_pnl)}">${dollars(t.spot_pnl)}</td>
<td class="${cls(t.fut_pnl)}">${dollars(t.fut_pnl)}</td><td>${t.fees.toFixed(3)}</td><td class="${cls(t.funding)}">${dollars(t.funding)}</td>
<td class="${cls(t.net)}"><b>${dollars(t.net)}</b></td><td class="${cls(t.net)}">${t.amount ? pct(t.net / t.amount * 100, 2) : "—"}</td>
<td class="mut">${t.reason}</td></tr>`).join("") || '<tr><td colspan="11" class="empty">Сделок пока нет</td></tr>';
}
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 ? '<span class="mut" style="font-size:13px">жду балансы</span>'
: `${pct(b.change_pct, 2)} <span style="font-size:13px">(${dollars(b.change_usd)} $)</span>`, cls(b.change_pct || 0)]);
if (!st.exact) tiles.push(["Внимание", '<span style="font-size:12px">часть цифр оценочная — биржа не вернула данные</span>', "neg"]);
} else if (st.real) {
const bal = real && real.balances && real.balances[bxVenue];
tiles.unshift(["Баланс на бирже", !bal ? "нет ключей" : bal.error ? `<span class="neg" style="font-size:12px">${bal.error}</span>`
: Object.entries(bal.values).map(([k, v]) => `<div style="font-size:13px">${k}: ${typeof v === "number" ? v.toFixed(2) : v}</div>`).join(""), ""]);
if (!st.exact) tiles.push(["Внимание", '<span style="font-size:12px">часть цифр оценочная — биржа не вернула данные</span>', "neg"]);
}
document.getElementById("bxStats").innerHTML = tiles
.map(([k, v, c]) => `<div class="stat"><div class="k">${k}</div><div class="v ${c}">${v}</div></div>`).join("");
if (bx.mode === "cross") { renderCross(); return; }
document.getElementById("bxPos").innerHTML = bx.positions.map(p => `<tr class="open">
<td>${mskFull(p.opened)}${p.real ? ' <span class="realtag">РЕАЛ</span>' : ""}${p.tp_order ? `<br><span class="pos">TP на бирже: ${price(p.tp_price)}</span>` : ""}${p.error ? `<br><span class="neg" style="white-space:normal">${p.error}</span>` : ""}</td><td><b>${p.base}</b> <a href="${p.spot_url}" target="_blank" rel="noopener">спот</a> · <a href="${p.fut_url}" target="_blank" rel="noopener">фьюч</a></td>
<td>${p.qty.toPrecision(5)}</td><td>${price(p.spot_entry)}${p.spot_now ? ` <span class="mut">→ ${price(p.spot_now)}</span>` : ""}</td>
<td>${price(p.fut_entry)}${p.fut_now ? ` <span class="mut">→ ${price(p.fut_now)}</span>` : ""}</td>
<td>${pct(p.entry_gap)}</td><td class="${p.gap_now <= s.exit_gap_pct ? "pos" : ""}">${pct(p.gap_now)}${freshness(p)}</td>
<td class="${cls(p.funding)}">${dollars(p.funding)}</td><td>${(p.fees_total ?? p.fees).toFixed(3)}</td>
<td class="${cls(p.net ?? 0)}"><b>${dollars(p.net)}</b></td>
<td><button class="x" title="Закрыть обе ноги по текущим ценам" onclick="basisClose(${p.uid}, '${bxDataVenue}')">×</button></td></tr>`).join("")
|| '<tr><td colspan="11" class="empty">Нет открытых позиций</td></tr>';
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 `<tr class="${r.fits ? "leadrow" : ""}">
<td><b>${r.base}</b>${r.mult > 1 ? ` <span class="mut">фьюч ×${r.mult}</span>` : ""}</td>
<td><a href="${r.spot_url}" target="_blank" rel="noopener">${price(r.spot_ask)}</a></td>
<td><a href="${r.fut_url}" target="_blank" rel="noopener">${price(r.fut_bid)}</a></td>
<td class="${r.entry_gap >= s.min_gap_pct ? "pos" : ""}"><b>${pct(r.entry_gap)}</b></td><td class="mut">${pct(r.exit_gap)}</td>
<td class="${cls(r.net_if_closed_pct)}">${pct(r.net_if_closed_pct)}</td>
<td class="${cls(r.funding_pct)}">${pct(r.funding_pct, 4)} / ${r.interval_h} ч</td>
<td>${r.depth == null ? '<span class="mut" title="биржа не сообщает объём по лучшей цене — не проверяется">?</span>' : kusd(r.depth)}</td>
${minEntryCell(r, s)}<td>${kusd(Math.min(r.spot_turnover, r.fut_turnover))}</td>
<td>${r.age_days == null ? "—" : r.age_days.toFixed(0)}</td><td class="mut">${groups}</td>
<td style="white-space:normal;max-width:260px">${open.has(r.base) ? '<span class="badge">в позиции</span>'
: r.real_block ? `<span class="neg" title="реальная сделка невозможна">реально нельзя: ${r.real_block}</span>`
: r.fits && !r.why ? '<span class="pos">подходит</span>'
: r.fits ? `<span class="pos">подходит</span> <span class="mut">— но ${r.why}</span>`
: `<span class="mut">${r.why || ""}</span>`}</td></tr>`;
}).join("") || '<tr><td colspan="13" class="empty">Нет монет под фильтры</td></tr>';
document.getElementById("bxTrades").innerHTML = bx.trades.map(t => `<tr>
<td>${mskFull(t.closed)}</td><td><b>${t.base}</b></td><td>${hold(t.closed - t.opened)}</td>
<td>${pct(t.entry_gap)} → ${pct(t.exit_gap)}</td><td class="${cls(t.spot_pnl)}">${dollars(t.spot_pnl)}</td>
<td class="${cls(t.fut_pnl)}">${dollars(t.fut_pnl)}</td><td>${t.fees.toFixed(3)}</td><td class="${cls(t.funding)}">${dollars(t.funding)}</td>
<td class="${cls(t.net)}"><b>${dollars(t.net)}</b></td><td class="${cls(t.net)}">${t.amount ? pct(t.net / t.amount * 100, 2) : "—"}</td>
<td class="mut">${t.reason}</td></tr>`).join("") || '<tr><td colspan="11" class="empty">Сделок пока нет</td></tr>';
}
function setMarket(m) {
arbMarket = m; localStorage.setItem("arb.market", m); arb = null; feesFor = null; arbOpen.clear();
document.getElementById("arbRows").innerHTML = '<tr><td colspan="16" class="empty">загружаю цены…</td></tr>';
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 = `<span class="mut">Комиссия по рынку (${isSpot() ? "спот" : "фьючерсы"}), %:</span>` +
Object.keys(arb.taker).map(e => `<div class="field"><label>${e}</label><input data-fee="${e}" style="width:70px"
value="${saved[e] ?? arb.taker[e]}"></div>`).join("") +
'<span class="mut">базовый уровень без скидок — поправьте под свой</span>';
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 = '<span class="mut">Биржи:</span>' + Object.keys(arb.taker).map(e =>
`<label class="check"><input type="checkbox" data-ex="${e}" ${!saved || saved.includes(e) ? "checked" : ""}>${e}</label>`).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 ? `<span class="pos">${yes}</span>` : v === false ? `<span class="neg">${no}</span>` : '<span class="mut">неизвестно</span>';
function transferCell(r) {
const t = r.transfer;
if (!t) return '<span class="mut">—</span>';
const nets = t.networks.length ? t.networks.slice(0, 4).join(", ") : '<span class="mut">сеть не известна</span>';
return `вывод ${r.buy}: ${yesno(t.withdraw, "открыт", "закрыт")}<br>ввод ${r.sell}: ${yesno(t.deposit, "открыт", "закрыт")}<br>` +
`сети: ${nets}${t.fee_usd != null ? `<br>комиссия вывода ≈ ${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
? `<li class="neg">По лучшим ценам доступно только ${r.depth_usd.toFixed(0)} $ из ${amount} $ — остальное исполнится хуже, уменьшите сумму</li>` : "";
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)}.`
: ` <span class="neg">Сканер видит связку меньше ${tmin} мин — неизвестно, продержится ли разница весь перевод.</span>`) : "";
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(`На <b>${r.buy}</b> иметь ${amount} USDT на спотовом счёте; на <b>${r.sell}</b> узнать адрес пополнения ${r.coin} (сеть: ${nets}).` +
(t.withdraw === false || t.deposit === false ? ' <span class="neg">Сейчас ввод или вывод закрыт — перевод невозможен.</span>'
: (t.withdraw == null || t.deposit == null ? ' <span class="mut">Статус ввода/вывода этой биржи не публикуется — проверьте на сайте.</span>' : "")));
steps.push(`<b>${r.buy}</b> ${r.pa.symbol}: <b class="pos">купить</b> по рынку ≈ ${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(`<b>${r.sell}</b> ${r.pb.symbol}: <b class="neg">продать</b> по рынку ≈ ${price(r.sell_price)} → ≈ ${money(sellValue)}, комиссия ${money(feeSell)} (${r.fee_b}%).`);
steps.push(`Итог по текущим ценам: ${money(sellValue - feeSell)} − ${money(amount)} = <b class="${cls(result$)}">${money(result$)}</b>` +
(tr && r.history_ok ? `; если разница сожмётся до минимума за ${tmin} мин: <b class="${cls(resultAtLow$)}">${money(resultAtLow$)}</b>` : "") +
`. Все расходы: ${money(feeBuy + r.tfee + feeSell)}, безубыток при разнице ≥ ${((feeBuy + r.tfee + feeSell) / amount * 100).toFixed(3)}%.`);
return `<ol class="plan">${steps.map(s => `<li>${s}</li>`).join("")}${depthWarn}</ol>`;
}
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(`<b>${r.buy}</b> ${r.pa.symbol}: открыть <b class="pos">LONG</b> по рынку ≈ ${price(r.buy_price)}, ${qty(unitsA, r.pa.mult || 1)} на ${amount} $. Комиссия ${money(feeInA)} (${r.fee_a}%).`);
steps.push(`Сразу же <b>${r.sell}</b> ${r.pb.symbol}: открыть <b class="neg">SHORT</b> по рынку ≈ ${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 ? " и перевода" : ""} = <b class="${cls(result$)}">${money(result$)}</b>` +
(r.usual != null ? `; к обычной: <b class="${cls(toUsual$ - fees)}">${money(toUsual$ - fees)}</b>` : "") + `. Безубыток при разнице ≥ ${(fees / amount * 100).toFixed(3)}%.`);
return `<ol class="plan">${steps.map(s => `<li>${s}</li>`).join("")}${depthWarn}</ol>`;
}
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(`<tr class="${r.suspect || r.closed ? "" : r.net_now > 0 ? "leadrow" : ""}" onclick="toggleArb('${r.coin}')">
<td><button class="planbtn">${arbOpen.has(r.coin) ? "▾ скрыть" : "▸ план"}</button></td>
<td><b>${r.coin}</b>${r.suspect ? ' <span class="neg" title="разница больше 10% или адреса контрактов не совпадают — скорее всего это разные токены">разные монеты?</span>' : ""}${r.closed ? ' <span class="neg">перевод закрыт</span>' : ""}</td>
<td><a href="${r.buy_url}" target="_blank" rel="noopener" onclick="event.stopPropagation()"><span class="exname">${r.buy}</span></a> ${price(r.buy_price)}</td>
<td><a href="${r.sell_url}" target="_blank" rel="noopener" onclick="event.stopPropagation()"><span class="exname">${r.sell}</span></a> ${price(r.sell_price)}</td>
<td class="${cls(r.gross)}"><b>${pct(r.gross)}</b></td><td class="${cls(r.net_now)}">${pct(r.net_now)}<span class="mut"> (−${r.round_cost.toFixed(2)})</span></td>
<td class="${cls(r.profit_pct)}" title="${r.profit_usd >= 0 ? "+" : "−"}${Math.abs(r.profit_usd).toFixed(2)} $ с ${val("afAmount", 1000)} $ после всех комиссий${transferOn() ? " и перевода " + r.tfee.toFixed(2) + " $" : ""}"><b>${pct(r.profit_pct, 2)}</b><br><span class="mut">${r.profit_usd >= 0 ? "+" : "−"}${Math.abs(r.profit_usd).toFixed(2)} $</span></td>
<td class="mut">${pct(r.usual)}</td><td class="${cls(r.expected ?? 0)}">${pct(r.expected)}</td>
${spot ? `<td class="plancell" style="min-width:200px">${transferCell(r)}</td>`
: `<td class="${cls(r.carry_8h ?? 0)}" title="лонг ${r.buy}: ${pct(r.funding_buy, 4)} · шорт ${r.sell}: ${pct(r.funding_sell, 4)}">${pct(r.carry_8h, 4)}</td>`}
<td>${usd(r.depth_usd)}</td><td>${usd(r.volume_usd)}</td>
<td>${r.held_min == null ? '<span class="mut">—</span>' : r.held_min < 1 ? "&lt;1 мин" : r.held_min.toFixed(0) + " мин"}</td>
${tr ? `<td class="${cls(r.window_low ?? 0)}">${r.history_ok ? pct(r.window_low) : `<span class="mut" title="сканер видит эту связку недостаточно долго">мало истории ${(r.history_have ?? 0).toFixed(0)} из ${val("afTMin", 15)} мин</span>`}</td>
<td class="${cls(r.net_transfer ?? 0)}"><b>${pct(r.net_transfer)}</b></td>` : ""}
<td class="mut">${r.exchanges.length}</td></tr>`);
if (arbOpen.has(r.coin)) {
const cells = Object.entries(r.prices).map(([e, p]) =>
`<a href="${p.url}" target="_blank" rel="noopener">${e}</a> bid ${price(p.bid)} / ask ${price(p.ask)}` +
(spot ? "" : ` · funding/8ч ${pct(p.funding_8h, 4)}`)).join("<br>");
html.push(`<tr class="detail"><td colspan="${cols}"><div class="plancell"><b>Что сделать (на сумму сделки, все комиссии):</b>
${arbPlan(r)}<div class="mut" style="margin-top:4px">Цены на всех биржах:<br>${cells}</div></div></td></tr>`);
}
}
document.getElementById("arbRows").innerHTML = html.join("") || `<tr><td colspan="${cols}" class="empty">Нет пар под фильтры</td></tr>`;
}
function toggleArb(coin) { arbOpen.has(coin) ? arbOpen.delete(coin) : arbOpen.add(coin); renderArb(); }
window.addEventListener("resize", drawChart);
(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);
})();