feat: добавить общий виртуальный счёт, справку и восстановление позиций
This commit is contained in:
1 parent
6aa76064dc
commit
c5aed5b970
29 files changed
+3600
-224
No files matched your search
+236
-5
@@ -10,17 +10,19 @@ function page() {
|
||||
source = source.replace(/^\(function (calcInit|restoreArbSettings)\(\) \{[\s\S]*?^\}\)\(\);/gm, '');
|
||||
source = source.slice(0, source.indexOf('\n(async () => {'));
|
||||
const elements = new Map();
|
||||
const intervals = [];
|
||||
const context = vm.createContext({
|
||||
console, Intl, localStorage: {getItem: () => null, setItem() {}},
|
||||
AbortController, setTimeout, clearTimeout, setInterval(fn, ms) { intervals.push({fn, ms}); },
|
||||
document: {getElementById(id) {
|
||||
if (!elements.has(id)) elements.set(id, {textContent: '', innerHTML: '', classList: {toggle() {}}});
|
||||
if (!elements.has(id)) elements.set(id, {textContent: '', innerHTML: '', value: '', dataset: {}, style: {}, disabled: false, classList: {toggle() {}}, addEventListener() {}, getAttribute() { return ''; }});
|
||||
return elements.get(id);
|
||||
}, querySelectorAll: () => []},
|
||||
}, querySelectorAll: () => [], querySelector: () => null},
|
||||
window: {addEventListener() {}}, confirm: () => true,
|
||||
});
|
||||
vm.runInContext(source, context);
|
||||
vm.runInContext(`
|
||||
var pending = [], commands = [], rendered = [];
|
||||
var originalApi = api, pending = [], commands = [], rendered = [];
|
||||
api = (url, body) => body === undefined
|
||||
? new Promise(resolve => pending.push({url, resolve}))
|
||||
: (commands.push(url), Promise.resolve({ok: true, message: 'ok'}));
|
||||
@@ -29,7 +31,7 @@ function page() {
|
||||
renderTiles = () => {};
|
||||
tab = 'basis'; bxVenue = 'cross';
|
||||
`, context);
|
||||
return {context, run: code => vm.runInContext(code, context)};
|
||||
return {context, elements, intervals, run: code => vm.runInContext(code, context)};
|
||||
}
|
||||
const tick = () => new Promise(resolve => setImmediate(resolve));
|
||||
|
||||
@@ -73,7 +75,7 @@ test('older poll cannot overwrite a newer completed poll', async () => {
|
||||
|
||||
test('coin switch rejects stale details and stale row actions', async () => {
|
||||
const {context: c, run} = page();
|
||||
run("selected = 'A'; detail = {key: 'A'}");
|
||||
run("tab = 'sim'; selected = 'A'; detail = {key: 'A'}");
|
||||
const old = run('loadDetail()');
|
||||
run("selectCoin('B')");
|
||||
await run("closePos(1, 'A'); trade('start')");
|
||||
@@ -87,3 +89,232 @@ test('coin switch rejects stale details and stale row actions', async () => {
|
||||
await run("closePos(1, 'B')");
|
||||
assert.equal(c.commands[0], '/api/coin/B/close/1');
|
||||
});
|
||||
|
||||
test('a failed first state request still schedules retries and can recover', async () => {
|
||||
const {run, intervals} = page();
|
||||
run(`
|
||||
var attempts = 0, recovered = false;
|
||||
loadState = async () => { if (++attempts === 1) throw new Error('offline'); recovered = true; };
|
||||
loadDetail = loadBasis = loadReal = loadAccount = async () => {};
|
||||
refreshCenter = showTab = () => {};
|
||||
startApplication();
|
||||
`);
|
||||
await tick();
|
||||
assert.equal(intervals.length, 7);
|
||||
assert.equal(run('attempts'), 1);
|
||||
await intervals.find(t => t.ms === 2000).fn();
|
||||
assert.equal(run('recovered'), true);
|
||||
});
|
||||
|
||||
test('late scanner refresh never replaces a selected coin', async () => {
|
||||
const {run, context: c} = page();
|
||||
run(`
|
||||
tab = 'sim'; selected = 'BTC'; var skeletons = 0;
|
||||
scannerSkeleton = () => skeletons++;
|
||||
document.getElementById = () => null;
|
||||
`);
|
||||
await run('loadScanner()');
|
||||
assert.equal(run('skeletons'), 0);
|
||||
assert.equal(c.pending.length, 0);
|
||||
});
|
||||
|
||||
test('late scanner response from an earlier visit is discarded', async () => {
|
||||
const {run, context: c, elements} = page();
|
||||
run("tab = 'sim'; selected = SCANNER;");
|
||||
const old = run('loadScanner()');
|
||||
run('detailEpoch += 2'); // Leaving and returning is a new visit, even to the same scanner.
|
||||
c.pending[0].resolve({running: false, auto_add: false, cycles: 1, log: [], coins: []});
|
||||
await old;
|
||||
assert.equal(elements.has('scState'), false);
|
||||
});
|
||||
|
||||
test('HTTP errors surface their message, with no automatic POST retry', async () => {
|
||||
const {run, context: c, elements} = page();
|
||||
c.fetch = async () => ({ok: false, status: 503, json: async () => ({error: 'maintenance'})});
|
||||
run("api = originalApi; readHealth.set('/api/state', {time: Date.now(), error: ''});");
|
||||
await assert.rejects(run("api('/api/settings', {})"), /maintenance/);
|
||||
assert.match(elements.get('commandNotice').textContent, /не подтверждён/);
|
||||
let calls = 0;
|
||||
c.fetch = async () => { calls++; throw new Error('connection lost'); };
|
||||
await assert.rejects(run("api('/api/settings', {})"), /connection lost/);
|
||||
assert.equal(calls, 1);
|
||||
assert.equal(run('pendingCommands.size'), 0);
|
||||
});
|
||||
|
||||
test('stale controls block commands until a fresh read succeeds', async () => {
|
||||
const {run, context: c} = page();
|
||||
const control = {dataset: {command: 'state'}, disabled: false};
|
||||
c.document.querySelectorAll = selector => selector === '[data-command]' ? [control] : [];
|
||||
let calls = 0;
|
||||
c.fetch = async () => { calls++; return {ok: true, status: 200, json: async () => ({ok: true})}; };
|
||||
run("api = originalApi; tab = 'sim'; selected = null; readHealth.set('/api/state', {time: Date.now() - 11000, error: ''}); refreshConnection();");
|
||||
assert.equal(control.disabled, true);
|
||||
await assert.rejects(run("api('/api/settings', {})"), /не отправлена/);
|
||||
assert.equal(calls, 0);
|
||||
await run("api('/api/state')");
|
||||
assert.equal(control.disabled, false);
|
||||
await run("api('/api/settings', {})");
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
|
||||
test('concurrent polling for the same endpoint makes one GET', async () => {
|
||||
const {run, context: c} = page();
|
||||
let calls = 0, resolve;
|
||||
c.fetch = () => { calls++; return new Promise(done => { resolve = done; }); };
|
||||
run('api = originalApi');
|
||||
const first = run("api('/api/state')"), second = run("api('/api/state')");
|
||||
assert.equal(calls, 1);
|
||||
resolve({ok: true, status: 200, json: async () => ({coins: []})});
|
||||
await Promise.all([first, second]);
|
||||
assert.equal(run('pendingReads.size'), 0);
|
||||
});
|
||||
|
||||
test('slow poll tasks do not accumulate duplicate render work', async () => {
|
||||
const {run} = page();
|
||||
run('var pollCalls = 0, finishPoll; var slowTask = () => { pollCalls++; return new Promise(resolve => finishPoll = resolve); };');
|
||||
const first = run('poll(slowTask)'), second = run('poll(slowTask)');
|
||||
assert.equal(run('pollCalls'), 1);
|
||||
run('finishPoll()');
|
||||
await Promise.all([first, second]);
|
||||
assert.equal(run('pendingPolls.size'), 0);
|
||||
});
|
||||
|
||||
test('context invalidation starts a fresh GET and ignores old connection failures', async () => {
|
||||
const {run, context: c} = page();
|
||||
const fetches = [];
|
||||
c.fetch = () => new Promise((resolve, reject) => fetches.push({resolve, reject}));
|
||||
run('api = originalApi');
|
||||
const old = run("api('/api/basis?ex=cross')");
|
||||
const oldRejected = assert.rejects(old, /old request failed/);
|
||||
run("invalidateRead('/api/basis?ex=cross')");
|
||||
const fresh = run("api('/api/basis?ex=cross')");
|
||||
assert.equal(fetches.length, 2);
|
||||
fetches[1].resolve({ok: true, status: 200, json: async () => ({settings: {}})});
|
||||
await fresh;
|
||||
fetches[0].reject(new Error('old request failed'));
|
||||
await oldRejected;
|
||||
assert.equal(run("freshRead('/api/basis?ex=cross')"), true);
|
||||
});
|
||||
|
||||
test('reset refusal is visible instead of silently discarded', async () => {
|
||||
const {run, elements} = page();
|
||||
run(`
|
||||
bx = {settings: {}}; bxDataVenue = 'cross';
|
||||
api = async () => ({ok: false, error: 'Сначала закройте открытые позиции'});
|
||||
loadBasis = async () => {};
|
||||
`);
|
||||
await run('basisReset()');
|
||||
assert.match(elements.get('bxMsg').textContent, /закройте открытые позиции/);
|
||||
});
|
||||
|
||||
test('account snapshot ordering prevents an older poll from undoing a deposit', () => {
|
||||
const {run, elements} = page();
|
||||
run(`
|
||||
renderAccount({version: 2, updated_at: 20, balance: 400, equity: 400, reserved: 0, free: 400, journal: []});
|
||||
renderAccount({version: 1, updated_at: 21, balance: 300, journal: []});
|
||||
renderAccount({version: 2, updated_at: 19, balance: 350, journal: []});
|
||||
`);
|
||||
assert.equal(elements.get('account-balance').textContent, '400.00 $');
|
||||
});
|
||||
|
||||
test('uncertain account adjustment reuses its identifier on explicit retry', async () => {
|
||||
const {run, elements} = page();
|
||||
run(`
|
||||
var adjustments = [];
|
||||
readHealth.set('/api/account', {time: Date.now(), error: ''});
|
||||
loadAccount = async () => {};
|
||||
api = async (url, body) => {
|
||||
adjustments.push({...body});
|
||||
if (adjustments.length === 1) throw new Error('response lost');
|
||||
return {ok: true, account: {version: 2, balance: 325, equity: 325, reserved: 0, free: 325, journal: []}};
|
||||
};
|
||||
`);
|
||||
elements.set('accountDelta', {value: '25,00'});
|
||||
await run('adjustAccount(1)');
|
||||
assert.match(elements.get('accountMsg').textContent, /Ответ не получен/);
|
||||
await run('adjustAccount(1)');
|
||||
assert.equal(run('adjustments.length'), 2);
|
||||
assert.equal(run('adjustments[0].amount'), '25');
|
||||
assert.equal(run('adjustments[0].request_id === adjustments[1].request_id'), true);
|
||||
assert.equal(elements.get('account-balance').textContent, '325.00 $');
|
||||
});
|
||||
|
||||
test('account does not send invalid amounts or stale withdrawals', async () => {
|
||||
const {run, context: c, elements} = page();
|
||||
run("readHealth.set('/api/account', {time: Date.now(), error: ''});");
|
||||
elements.set('accountDelta', {value: '-10'});
|
||||
await run('adjustAccount(-1)');
|
||||
assert.equal(c.commands.length, 0);
|
||||
elements.get('accountDelta').value = '10';
|
||||
run("accountData = {stale: ['coin:BTC']}");
|
||||
await run('adjustAccount(-1)');
|
||||
assert.equal(c.commands.length, 0);
|
||||
assert.match(elements.get('accountMsg').textContent, /устарела/);
|
||||
});
|
||||
|
||||
test('account controls send signed withdrawals and hide in real arbitrage', async () => {
|
||||
const {run, elements} = page();
|
||||
run(`
|
||||
var savedAdjustment;
|
||||
accountData = {stale: [], error: ''};
|
||||
readHealth.set('/api/account', {time: Date.now(), error: ''});
|
||||
loadAccount = async () => {};
|
||||
api = async (url, body) => { savedAdjustment = body; return {ok: true}; };
|
||||
`);
|
||||
elements.set('accountDelta', {value: '15.50'});
|
||||
await run('adjustAccount(-1)');
|
||||
assert.equal(run('savedAdjustment.amount'), '-15.5');
|
||||
run("tab = 'basis'; bxVenue = 'cross_real'; updateAccountVisibility();");
|
||||
assert.equal(elements.get('paperAccount').hidden, true);
|
||||
run("bxVenue = 'cross'; updateAccountVisibility();");
|
||||
assert.equal(elements.get('paperAccount').hidden, false);
|
||||
});
|
||||
|
||||
test('account journal preserves the server newest-first order and stale owner semantics', () => {
|
||||
const {run, elements} = page();
|
||||
run(`renderAccount({balance: 300, equity: 300, reserved: 0, free: 300, stale: [], error: '', journal: [
|
||||
{time: 200, amount: 10, balance: 300, reason: 'Newest'},
|
||||
{time: 100, amount: -10, balance: 290, reason: 'Older'}
|
||||
]});`);
|
||||
const html = elements.get('accountJournal').innerHTML;
|
||||
assert.ok(html.indexOf('Newest') < html.indexOf('Older'));
|
||||
assert.equal(run('accountIsStale(accountData)'), false);
|
||||
assert.equal(run("accountIsStale({stale: ['coin:BTC']})"), true);
|
||||
});
|
||||
|
||||
test('saving main arbitrage settings preserves separately unsaved fee edits', async () => {
|
||||
const {run, context: c} = page();
|
||||
const main = {dataset: {bx: 'amount'}, type: 'text', value: '25'};
|
||||
const fee = {dataset: {cxfee: 'Bybit|spot', dirty: '1'}, type: 'text', value: '0.123'};
|
||||
c.document.querySelectorAll = selector => selector === '#bxSettings input' ? [main]
|
||||
: selector.includes('#cxBal input[data-cxfee]') ? [main, fee] : [];
|
||||
run("bx = {settings: {}}; bxDataVenue = 'cross'; bxBuilt = true; bxDirty = true; loadBasis = async () => {};");
|
||||
await run('basisSave()');
|
||||
assert.equal(run("basisDrafts.get('cross')['fee:Bybit|spot']"), '0.123');
|
||||
assert.equal(run("'bx:amount' in basisDrafts.get('cross')"), false);
|
||||
});
|
||||
|
||||
test('scanner rejects invalid cycle inputs before sending any command', async () => {
|
||||
const {run, elements, context: c} = page();
|
||||
elements.set('scMin', {value: '15'}); elements.set('scCoins', {value: '14'});
|
||||
await run("scanner('start')");
|
||||
assert.equal(c.commands.length, 0);
|
||||
assert.match(elements.get('scMsg').textContent, /от 1 до 13/);
|
||||
});
|
||||
|
||||
test('help covers every declared setting, all modes and account controls', () => {
|
||||
const {run, context: c} = page();
|
||||
vm.runInContext(fs.readFileSync(path.join(__dirname, '../web/help-data.js'), 'utf8'), c);
|
||||
vm.runInContext(fs.readFileSync(path.join(__dirname, '../web/help.js'), 'utf8'), c);
|
||||
const missing = run(`[
|
||||
...[...MAIN_FIELDS, ...MORE_FIELDS].filter(([k]) => !HELP_SETTINGS.sim[k]).map(([k]) => 'sim.' + k),
|
||||
...[...CX_FIELDS, ...CX_CHECKS].filter(([k]) => !HELP_SETTINGS.cross[k]).map(([k]) => 'cross.' + k),
|
||||
...[...BX_FIELDS, ...BX_CHECKS].filter(([k]) => !HELP_SETTINGS.basis[k]).map(([k]) => 'basis.' + k),
|
||||
...['lead', 'vector', 'basis'].filter(k => !HELP_MODES[k]),
|
||||
...[...CALC_IDS, 'scMin', 'scCoins', 'scAuto', 'simRealTpsl', 'simRealTransfer', 'simRealSl', 'simRealPing', 'accountDelta'].filter(k => !HELP_EXTRA.some(row => row[1] === k))
|
||||
]`);
|
||||
assert.equal(missing.length, 0, `Missing help: ${missing.join(', ')}`);
|
||||
assert.equal(run("MAIN_FIELDS.concat(MORE_FIELDS).some(([k]) => k === 'budget')"), false);
|
||||
assert.ok(run("filterHelp(helpEntries(), 'свободно').some(e => e.key === 'free')"));
|
||||
assert.ok(run("filterHelp(helpEntries(), 'stop_loss_pct').length") > 0);
|
||||
});
|
||||
Reference in new issue
Block a user