`).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 || '
`).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))}
До ликвидации
Фьючерсы на 1 шорт
Фьючерсы на ${n} шорт.
${steps.map(x => `
+${x}%
${money(futFor(x))}
${money(n * futFor(x))}
`).join("")}
По текущей логике программы на каждой бирже: ${money(n * Math.max(pSpot, pFut))},
всего на ${ex}: ${money(n * Math.max(pSpot, pFut) * ex)}
Желаемые ${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]) => `
`;
};
const isOpen = j.action === "open", isClose = j.action === "close";
if (!isOpen && !isClose) return "";
return isOpen
? row("Решение открыть", j.decision_open_time, j.decision_spot_price, j.decision_futures_price, j.decision_open_price)
+ row("Исполнение открытия", j.actual_open_time, j.actual_spot_price, j.actual_futures_price, j.actual_open_price)
: row("Решение закрыть", j.decision_close_time, j.decision_spot_price, j.decision_futures_price, j.decision_close_price)
+ row("Исполнение закрытия", j.actual_close_time, j.actual_spot_price, j.actual_futures_price, j.actual_close_price);
}
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_entry_delay_ms", "Задержка открытия в симуляции, мс"],
["simulation_exit_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", "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 '