init: Market Assistant — этап 1 (позиции: FIFO-средняя, цена безубытка, ступеньки, маркеры ордеров) + этап 2 (отношения инструментов: лаг-корреляция)
This commit is contained in:
commit
0af45d2902
46 files changed
+8105
No files matched your search
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* Эмпирический тест средней цены (этап 1): несколько покупок по разным ценам +
|
||||
* частичная продажа — как меняются средние?
|
||||
*
|
||||
* Сравниваем:
|
||||
* - наш движок (взвешенная) — по нашей модели продажа НЕ меняет среднюю;
|
||||
* - T-Invest averagePositionPrice (взвешенная) — должно совпасть с движком;
|
||||
* - T-Invest averagePositionPriceFifo — меняется: уходят самые ранние лоты.
|
||||
*
|
||||
* Мультиблочную позицию набираем лимитами ниже рынка (если песочница
|
||||
* исполняет их по цене заявки). Только TINKOFF_SANDBOX=true!
|
||||
* Запуск: NODE_EXTRA_CA_CERTS=./certs/ca-all.pem npx tsx scripts/sandbox-avg-test.ts
|
||||
*/
|
||||
import { config, hasTinkoffToken } from '../src/config.js';
|
||||
import {
|
||||
findShareByTicker,
|
||||
getAccounts,
|
||||
getExecutedTrades,
|
||||
getLastPrices,
|
||||
getSandboxPortfolio,
|
||||
sandboxCancelOrder,
|
||||
sandboxPostOrder,
|
||||
} from '../src/tinkoff.js';
|
||||
import type { ExecutedTrade } from '../src/tinkoff.js';
|
||||
import { computePositions } from '../src/positions.js';
|
||||
|
||||
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
/** FIFO-средняя остатка: очередь лотов, продажа забирает с начала очереди. */
|
||||
function fifoAverage(trades: ExecutedTrade[]): number | null {
|
||||
const lots: Array<{ qty: number; price: number }> = [];
|
||||
for (const t of [...trades].sort((a, b) => a.dateMs - b.dateMs)) {
|
||||
if (t.type === 'buy') {
|
||||
lots.push({ qty: t.qty, price: t.price });
|
||||
continue;
|
||||
}
|
||||
let rest = t.qty;
|
||||
while (rest > 1e-9 && lots.length > 0) {
|
||||
const head = lots[0]!;
|
||||
const take = Math.min(head.qty, rest);
|
||||
head.qty -= take;
|
||||
rest -= take;
|
||||
if (head.qty <= 1e-9) lots.shift();
|
||||
}
|
||||
}
|
||||
const total = lots.reduce((s, l) => s + l.qty, 0);
|
||||
if (total <= 1e-9) return null;
|
||||
return lots.reduce((s, l) => s + l.qty * l.price, 0) / total;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
if (!hasTinkoffToken()) throw new Error('TINKOFF_TOKEN не задан в .env');
|
||||
if (!config.tinkoffSandbox) throw new Error('Скрипт только для песочницы');
|
||||
|
||||
const account = (await getAccounts())[0];
|
||||
if (!account) throw new Error('Нет sandbox-счётов');
|
||||
const sber = await findShareByTicker('SBER');
|
||||
if (!sber) throw new Error('SBER не найден');
|
||||
const last = (await getLastPrices([sber.figi])).get(sber.figi);
|
||||
if (!last) throw new Error('Нет последней цены SBER');
|
||||
const step = sber.minPriceIncrement || 0.01;
|
||||
// Песочница НЕ исполняет лимиты НИЖЕ рынка (status NEW) — пробуем ВЫШЕ рынка
|
||||
// (marketable limit): если исполняет по цене заявки, получим разные блоки.
|
||||
const p1 = Math.ceil((last * 1.02) / step) * step;
|
||||
const p2 = Math.ceil((last * 1.05) / step) * step;
|
||||
console.log(`SBER last=${last}, шаг=${step}; лимиты выше рынка: ${p1} и ${p2}`);
|
||||
|
||||
const filled = (r: { lotsExecuted: number | null }): boolean =>
|
||||
r.lotsExecuted !== null && r.lotsExecuted > 0;
|
||||
|
||||
const r1 = await sandboxPostOrder({
|
||||
accountId: account.id,
|
||||
figi: sber.figi,
|
||||
quantity: 1,
|
||||
direction: 'buy',
|
||||
limitPrice: p1,
|
||||
});
|
||||
console.log(
|
||||
`limit buy 1 @ ${p1}: status=${r1.executionReportStatus}, lots=${r1.lotsExecuted}, msg="${r1.message}"`,
|
||||
);
|
||||
if (!filled(r1)) {
|
||||
try {
|
||||
await sandboxCancelOrder(account.id, r1.orderId);
|
||||
} catch {
|
||||
/* уже не активен */
|
||||
}
|
||||
throw new Error('Песочница не исполнила лимитный ордер — мультиблок так не создать');
|
||||
}
|
||||
|
||||
const r2 = await sandboxPostOrder({
|
||||
accountId: account.id,
|
||||
figi: sber.figi,
|
||||
quantity: 1,
|
||||
direction: 'buy',
|
||||
limitPrice: p2,
|
||||
});
|
||||
console.log(
|
||||
`limit buy 1 @ ${p2}: status=${r2.executionReportStatus}, lots=${r2.lotsExecuted}, msg="${r2.message}"`,
|
||||
);
|
||||
if (!filled(r2)) {
|
||||
try {
|
||||
await sandboxCancelOrder(account.id, r2.orderId);
|
||||
} catch {
|
||||
/* уже не активен */
|
||||
}
|
||||
}
|
||||
|
||||
const sell = await sandboxPostOrder({
|
||||
accountId: account.id,
|
||||
figi: sber.figi,
|
||||
quantity: 1,
|
||||
direction: 'sell',
|
||||
});
|
||||
console.log(
|
||||
`market sell 1: status=${sell.executionReportStatus}, lots=${sell.lotsExecuted}`,
|
||||
);
|
||||
await sleep(1500);
|
||||
|
||||
// Что говорит сам T-Invest
|
||||
const portfolio = (await getSandboxPortfolio(account.id)) as {
|
||||
positions?: Array<{
|
||||
figi?: string;
|
||||
quantity?: unknown;
|
||||
averagePositionPrice?: unknown;
|
||||
averagePositionPriceFifo?: unknown;
|
||||
}>;
|
||||
};
|
||||
const pos = portfolio.positions?.find((p) => p.figi === sber.figi);
|
||||
console.log('\n=== Портфель T-Invest по SBER ===');
|
||||
console.log(' quantity =', JSON.stringify(pos?.quantity));
|
||||
console.log(' averagePositionPrice =', JSON.stringify(pos?.averagePositionPrice));
|
||||
console.log(' averagePositionPriceFifo=', JSON.stringify(pos?.averagePositionPriceFifo));
|
||||
|
||||
// Наш движок + локальный FIFO
|
||||
const toMs = Date.now();
|
||||
const trades = (
|
||||
await getExecutedTrades(account.id, account.openedMs ?? toMs - 90 * 86_400_000, toMs)
|
||||
).filter((t) => t.figi === sber.figi);
|
||||
console.log(`\nСделок по SBER учтено: ${trades.length}`);
|
||||
for (const t of trades) console.log(` ${t.type.toUpperCase()} ${t.qty} @ ${t.price}`);
|
||||
|
||||
const [engine] = computePositions(trades);
|
||||
console.log('\n=== Наш движок ===');
|
||||
if (engine) console.log(` qty=${engine.qty}, avg(взвешенная)=${engine.avgPrice.toFixed(2)}`);
|
||||
const fifo = fifoAverage(trades);
|
||||
console.log(` avg(FIFO)=${fifo === null ? '—' : fifo.toFixed(2)}`);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err instanceof Error ? err.message : err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Демо для этапа 1 на sandbox-токене: наполняет sandbox-счёт виртуальными
|
||||
* деньгами, выставляет тестовые ордера SBER (buy 10 лотов, затем sell 3)
|
||||
* и печатает позиции, рассчитанные тем же движком, что и /api/positions.
|
||||
*
|
||||
* Запуск (из backend/): npm run sandbox-demo
|
||||
* Только для TINKOFF_SANDBOX=true!
|
||||
*/
|
||||
import { config, hasTinkoffToken } from '../src/config.js';
|
||||
import {
|
||||
findShareByTicker,
|
||||
getAccounts,
|
||||
getExecutedTrades,
|
||||
getLastPrices,
|
||||
sandboxOpenAccount,
|
||||
sandboxPayIn,
|
||||
sandboxPostOrder,
|
||||
} from '../src/tinkoff.js';
|
||||
import { computePositions } from '../src/positions.js';
|
||||
|
||||
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
async function main(): Promise<void> {
|
||||
if (!hasTinkoffToken()) throw new Error('TINKOFF_TOKEN не задан в .env');
|
||||
if (!config.tinkoffSandbox) {
|
||||
throw new Error('Скрипт только для песочницы: TINKOFF_SANDBOX=true в .env');
|
||||
}
|
||||
|
||||
let accounts = await getAccounts();
|
||||
if (accounts.length === 0) {
|
||||
console.log('Sandbox-счётов нет — открываю новый...');
|
||||
await sandboxOpenAccount();
|
||||
accounts = await getAccounts();
|
||||
}
|
||||
const account = accounts[0];
|
||||
if (!account) throw new Error('Не удалось получить sandbox-счёт');
|
||||
console.log(`Счёт: ${account.id} (${account.name || account.type})`);
|
||||
|
||||
console.log('Пополнение sandbox-счёта на 1 000 000 ₽ (виртуальные)...');
|
||||
await sandboxPayIn(account.id, 1_000_000);
|
||||
|
||||
const sber = await findShareByTicker('SBER');
|
||||
if (!sber) throw new Error('SBER не найден в справочнике T-Invest');
|
||||
const last = (await getLastPrices([sber.figi])).get(sber.figi) ?? null;
|
||||
console.log(`SBER: figi=${sber.figi}, лот=${sber.lot}, последняя цена=${last ?? 'н/д'}`);
|
||||
|
||||
console.log('Выставляю MARKET-ордера: buy 10 лотов, затем sell 3 лота...');
|
||||
const buy = await sandboxPostOrder({
|
||||
accountId: account.id,
|
||||
figi: sber.figi,
|
||||
quantity: 10,
|
||||
direction: 'buy',
|
||||
});
|
||||
console.log(
|
||||
` buy: orderId=${buy.orderId}, status=${buy.executionReportStatus}, ` +
|
||||
`lotsExecuted=${buy.lotsExecuted ?? '—'}, msg="${buy.message}"`,
|
||||
);
|
||||
await sleep(1500);
|
||||
const sell = await sandboxPostOrder({
|
||||
accountId: account.id,
|
||||
figi: sber.figi,
|
||||
quantity: 3,
|
||||
direction: 'sell',
|
||||
});
|
||||
console.log(
|
||||
` sell: orderId=${sell.orderId}, status=${sell.executionReportStatus}, ` +
|
||||
`lotsExecuted=${sell.lotsExecuted ?? '—'}, msg="${sell.message}"`,
|
||||
);
|
||||
await sleep(1500);
|
||||
|
||||
const toMs = Date.now();
|
||||
const fromMs = account.openedMs ?? toMs - 30 * 86_400_000;
|
||||
const trades = await getExecutedTrades(account.id, fromMs, toMs);
|
||||
console.log(`\nИсполненных сделок в истории: ${trades.length}`);
|
||||
for (const t of trades) {
|
||||
console.log(
|
||||
` ${new Date(t.dateMs).toISOString()} ${t.type.toUpperCase()} ${t.qty} @ ${t.price}`,
|
||||
);
|
||||
}
|
||||
|
||||
const positions = computePositions(trades);
|
||||
if (positions.length === 0) {
|
||||
console.log('\nОткрытых позиций нет (всё закрыто в ноль).');
|
||||
return;
|
||||
}
|
||||
console.log('\nОткрытые позиции (тот же расчёт, что в /api/positions):');
|
||||
for (const p of positions) {
|
||||
const last2 = (await getLastPrices([p.figi])).get(p.figi) ?? null;
|
||||
const pnl = last2 === null ? null : (last2 - p.avgPrice) * p.qty;
|
||||
console.log(
|
||||
` ${p.figi} qty=${p.qty}, avg=${p.avgPrice.toFixed(2)}, ` +
|
||||
`last=${last2 ?? 'н/д'}, P&L=${pnl === null ? '—' : pnl.toFixed(2)}`,
|
||||
);
|
||||
}
|
||||
console.log('\nГотово. Открой http://localhost:5173 (npm run dev в frontend/).');
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err instanceof Error ? err.message : err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Диагностика sandbox-счёта: активные ордера, портфель, все операции.
|
||||
*
|
||||
* Запуск (из backend/): npm run sandbox-diag
|
||||
* Только для TINKOFF_SANDBOX=true!
|
||||
*/
|
||||
import { config, hasTinkoffToken } from '../src/config.js';
|
||||
import {
|
||||
getAccounts,
|
||||
getSandboxOperationsRaw,
|
||||
getSandboxOrders,
|
||||
getSandboxPortfolio,
|
||||
} from '../src/tinkoff.js';
|
||||
|
||||
function short(value: unknown): string {
|
||||
return JSON.stringify(value, null, 0).slice(0, 500);
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
if (!hasTinkoffToken()) throw new Error('TINKOFF_TOKEN не задан в .env');
|
||||
if (!config.tinkoffSandbox) throw new Error('Скрипт только для песочницы');
|
||||
|
||||
const account = (await getAccounts())[0];
|
||||
if (!account) throw new Error('Нет sandbox-счётов');
|
||||
console.log(`Счёт: ${account.id} (${account.name || account.type})`);
|
||||
|
||||
const orders = await getSandboxOrders(account.id);
|
||||
console.log(`\nАктивные ордера: ${orders.length}`);
|
||||
for (const o of orders) console.log(' ', short(o));
|
||||
|
||||
const portfolio = (await getSandboxPortfolio(account.id)) as {
|
||||
positions?: unknown[];
|
||||
totalAmountCurrencies?: unknown;
|
||||
};
|
||||
console.log(`\nПозиции портфеля: ${portfolio.positions?.length ?? 0}`);
|
||||
for (const p of portfolio.positions ?? []) console.log(' ', short(p));
|
||||
console.log('Деньги (totalAmountCurrencies):', short(portfolio.totalAmountCurrencies));
|
||||
|
||||
const toMs = Date.now();
|
||||
const fromMs = account.openedMs ?? toMs - 30 * 86_400_000;
|
||||
const ops = await getSandboxOperationsRaw(account.id, fromMs, toMs);
|
||||
console.log(`\nВсе операции (без фильтра по статусу): ${ops.length}`);
|
||||
for (const o of ops.slice(0, 30)) console.log(' ', short(o));
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err instanceof Error ? err.message : err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* Тесты движка средней цены позиции (src/positions.ts) — сценарии
|
||||
* частичного открытия/закрытия по одному инструменту (newPlan.md, этап 1).
|
||||
*
|
||||
* Запуск (в backend/): npm run test — без сети, чистая функция.
|
||||
*/
|
||||
import assert from 'node:assert/strict';
|
||||
import { computePositions } from '../src/positions.js';
|
||||
import type { ExecutedTrade } from '../src/tinkoff.js';
|
||||
|
||||
const t = (
|
||||
type: 'buy' | 'sell',
|
||||
qty: number,
|
||||
price: number,
|
||||
ms: number,
|
||||
figi = 'TEST',
|
||||
): ExecutedTrade => ({ figi, type, qty, price, dateMs: ms, currency: 'rub' });
|
||||
|
||||
/** Единственная открытая позиция по figi (с проверкой, что она есть). */
|
||||
function pos(trades: ExecutedTrade[], figi = 'TEST') {
|
||||
const all = computePositions(trades);
|
||||
const p = all.find((x) => x.figi === figi);
|
||||
assert.ok(p, 'ожидалась открытая позиция');
|
||||
return p;
|
||||
}
|
||||
|
||||
let passed = 0;
|
||||
function test(name: string, fn: () => void): void {
|
||||
fn();
|
||||
passed += 1;
|
||||
console.log(` ok — ${name}`);
|
||||
}
|
||||
|
||||
// --- Частичное ОТКРЫТИЕ (докупки) ---
|
||||
|
||||
test('одна покупка: qty=10, avg=100', () => {
|
||||
const p = pos([t('buy', 10, 100, 1)]);
|
||||
assert.equal(p.qty, 10);
|
||||
assert.equal(p.avgPrice, 100);
|
||||
});
|
||||
|
||||
test('докупка по другой цене: взвешенная средняя (10@100 + 10@200 -> 20 @ 150)', () => {
|
||||
const p = pos([t('buy', 10, 100, 1), t('buy', 10, 200, 2)]);
|
||||
assert.equal(p.qty, 20);
|
||||
assert.equal(p.avgPrice, 150);
|
||||
});
|
||||
|
||||
// --- Частичное ЗАКРЫТИЕ ---
|
||||
|
||||
test('частичное закрытие: средняя НЕ меняется, только qty (брокерская модель)', () => {
|
||||
const p = pos([t('buy', 10, 100, 1), t('buy', 10, 200, 2), t('sell', 5, 300, 3)]);
|
||||
assert.equal(p.qty, 15);
|
||||
assert.equal(p.avgPrice, 150); // не 140 и не 166.67 — продажи не влияют на среднюю
|
||||
assert.equal(p.operationsCount, 3);
|
||||
});
|
||||
|
||||
test('после частичного закрытия докупка пересчитывает среднюю', () => {
|
||||
const p = pos([
|
||||
t('buy', 10, 100, 1),
|
||||
t('sell', 5, 120, 2), // qty=5, avg=100
|
||||
t('buy', 10, 280, 3), // (100*5 + 280*10) / 15 = 220
|
||||
]);
|
||||
assert.equal(p.qty, 15);
|
||||
assert.equal(p.avgPrice, 220);
|
||||
});
|
||||
|
||||
test('закрытие в ноль ПО ЧАСТЯМ: позиция исчезает (сброс алгоритма)', () => {
|
||||
const all = computePositions([
|
||||
t('buy', 20, 100, 1),
|
||||
t('sell', 5, 110, 2),
|
||||
t('sell', 5, 105, 3),
|
||||
t('sell', 10, 120, 4),
|
||||
]);
|
||||
assert.equal(all.length, 0); // «полностью закрытая позиция больше не интересует»
|
||||
});
|
||||
|
||||
// --- Сброс и повторное открытие ---
|
||||
|
||||
test('после закрытия в ноль новая позиция не помнит старую историю', () => {
|
||||
const p = pos([
|
||||
t('buy', 10, 100, 1),
|
||||
t('sell', 10, 150, 2), // закрыто в ноль — сброс
|
||||
t('buy', 5, 200, 3), // новая позиция
|
||||
]);
|
||||
assert.equal(p.qty, 5);
|
||||
assert.equal(p.avgPrice, 200);
|
||||
assert.equal(p.operationsCount, 1); // старые сделки в расчёт не входят
|
||||
});
|
||||
|
||||
// --- Граничные случаи ---
|
||||
|
||||
test('продажа БЕЗ позиции (дыра в истории / шорт): игнорируется, не ломает расчёт', () => {
|
||||
const p = pos([t('sell', 10, 100, 1), t('buy', 5, 50, 2)]);
|
||||
assert.equal(p.qty, 5);
|
||||
assert.equal(p.avgPrice, 50);
|
||||
});
|
||||
|
||||
test('sell больше остатка: позиция сбрасывается (шорт не моделируем — решение этапа 1)', () => {
|
||||
const all = computePositions([t('buy', 10, 100, 1), t('sell', 15, 120, 2)]);
|
||||
assert.equal(all.length, 0);
|
||||
});
|
||||
|
||||
test('движок сортирует по времени сам (порядок в массиве не важен)', () => {
|
||||
const p = pos([t('buy', 10, 200, 2), t('sell', 5, 300, 1)]);
|
||||
// по времени: сначала sell(ms=1) без позиции — игнор, потом buy(ms=2)
|
||||
assert.equal(p.qty, 10);
|
||||
assert.equal(p.avgPrice, 200);
|
||||
assert.equal(p.operationsCount, 1);
|
||||
});
|
||||
|
||||
test('несколько инструментов считаются независимо', () => {
|
||||
const all = computePositions([
|
||||
t('buy', 10, 100, 1, 'F1'),
|
||||
t('buy', 3, 50, 2, 'F2'),
|
||||
t('sell', 4, 110, 3, 'F1'),
|
||||
]);
|
||||
const f1 = all.find((x) => x.figi === 'F1');
|
||||
const f2 = all.find((x) => x.figi === 'F2');
|
||||
assert.ok(f1 && f2);
|
||||
assert.equal(f1.qty, 6);
|
||||
assert.equal(f1.avgPrice, 100);
|
||||
assert.equal(f2.qty, 3);
|
||||
assert.equal(f2.avgPrice, 50);
|
||||
});
|
||||
|
||||
test('кейс из обсуждения: 10@100 + 20@90, продали 25@110 -> остаток 5 @ 93.33', () => {
|
||||
const p = pos([
|
||||
t('buy', 10, 100, 1),
|
||||
t('buy', 20, 90, 2), // средняя = (100*10 + 90*20) / 30 = 2800/30 = 93.333…
|
||||
t('sell', 25, 110, 3), // частичное закрытие — средняя остатка НЕ меняется
|
||||
]);
|
||||
assert.equal(p.qty, 5);
|
||||
assert.ok(Math.abs(p.avgPrice - 2800 / 30) < 1e-9); // взвешенная
|
||||
assert.ok(Math.abs(p.avgPriceFifo - 90) < 1e-9); // FIFO: ушли 10@100 и 15@90 -> 5@90
|
||||
assert.equal(p.operationsCount, 3);
|
||||
});
|
||||
|
||||
test('мультиблок: 100@100 + 100@90 + 100@80 + 100@70, продали 100@110: взвеш. 85, FIFO 80', () => {
|
||||
const p = pos([
|
||||
t('buy', 100, 100, 1),
|
||||
t('buy', 100, 90, 2),
|
||||
t('buy', 100, 80, 3),
|
||||
t('buy', 100, 70, 4), // средняя = 34000/400 = 85
|
||||
t('sell', 100, 110, 5), // FIFO: ушёл блок 100@100 -> остаток 300 @ 80
|
||||
]);
|
||||
assert.equal(p.qty, 300);
|
||||
assert.ok(Math.abs(p.avgPrice - 85) < 1e-9);
|
||||
assert.ok(Math.abs(p.avgPriceFifo - 80) < 1e-9);
|
||||
});
|
||||
|
||||
test('безубыток: 100@100+100@90+100@80+100@70, продали 100@80: FIFO 80, реализ. -2000, безубыток 86.67', () => {
|
||||
const p = pos([
|
||||
t('buy', 100, 100, 1),
|
||||
t('buy', 100, 90, 2),
|
||||
t('buy', 100, 80, 3),
|
||||
t('buy', 100, 70, 4),
|
||||
t('sell', 100, 80, 5), // (80-100)*100 = -2000 реализовано
|
||||
]);
|
||||
assert.equal(p.qty, 300);
|
||||
assert.ok(Math.abs(p.avgPriceFifo - 80) < 1e-9);
|
||||
assert.ok(Math.abs(p.realizedPnl + 2000) < 1e-9);
|
||||
assert.ok(Math.abs(p.breakeven - 26000 / 300) < 1e-9); // (34000-8000)/300
|
||||
});
|
||||
|
||||
test('безубыток при продаже с прибылью: buy 100@100, sell 50@120 -> реализ. +1000, безубыток 80', () => {
|
||||
const p = pos([t('buy', 100, 100, 1), t('sell', 50, 120, 2)]);
|
||||
assert.equal(p.qty, 50);
|
||||
assert.ok(Math.abs(p.avgPriceFifo - 100) < 1e-9);
|
||||
assert.ok(Math.abs(p.realizedPnl - 1000) < 1e-9);
|
||||
assert.ok(Math.abs(p.breakeven - 80) < 1e-9);
|
||||
});
|
||||
|
||||
test('history: ступеньки средней/безубытка, сброс и разрыв линии при нуле', () => {
|
||||
const p = pos([
|
||||
t('buy', 100, 100, 1),
|
||||
t('sell', 100, 150, 2), // закрыто в ноль — сброс
|
||||
t('buy', 50, 200, 3), // новая позиция
|
||||
]);
|
||||
assert.equal(p.history.length, 3);
|
||||
assert.equal(p.history[0]!.qty, 100);
|
||||
assert.ok(Math.abs(p.history[0]!.avgPriceFifo! - 100) < 1e-9);
|
||||
assert.equal(p.history[1]!.qty, 0);
|
||||
assert.equal(p.history[1]!.avgPriceFifo, null); // линия рвётся
|
||||
assert.ok(Math.abs(p.history[2]!.avgPriceFifo! - 200) < 1e-9);
|
||||
assert.ok(Math.abs(p.history[2]!.breakeven! - 200) < 1e-9); // реализ. сброшен
|
||||
});
|
||||
|
||||
console.log(`\n${passed}/15 тестов пройдено — частичные открытия/закрытия считаются корректно`);
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Тесты этапа 2: сдвинутая корреляция (src/relations.ts).
|
||||
* Синтетические ряды с ЗАРАНЕЕ известным лагом: движок обязан найти, кто
|
||||
* ведёт и на сколько. Запуск: npm run test (в backend/).
|
||||
*/
|
||||
import assert from 'node:assert/strict';
|
||||
import { computeRelations } from '../src/relations.js';
|
||||
import type { Candle } from '../src/types.js';
|
||||
|
||||
/** Детерминированный PRNG — одинаковый результат между запусками. */
|
||||
function mulberry32(seed: number): () => number {
|
||||
let a = seed >>> 0;
|
||||
return () => {
|
||||
a |= 0;
|
||||
a = (a + 0x6d2b79f5) | 0;
|
||||
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
|
||||
function candles(closes: number[], startMs: number): Candle[] {
|
||||
return closes.map((close, i) => ({
|
||||
time: new Date(startMs + i * DAY_MS).toISOString(),
|
||||
open: close,
|
||||
high: close,
|
||||
low: close,
|
||||
close,
|
||||
volume: 0,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Цены из AR(1)-доходностей: r[i] = k*r[i-1] + шум — сигнал с убывающей автокорреляцией. */
|
||||
function arCloses(n: number, k: number, sigma: number, seed: number): number[] {
|
||||
const rnd = mulberry32(seed);
|
||||
const closes: number[] = [100];
|
||||
let r = 0;
|
||||
for (let i = 1; i < n; i++) {
|
||||
r = k * r + (rnd() * 2 - 1) * sigma;
|
||||
closes.push(closes[i - 1]! * Math.exp(r));
|
||||
}
|
||||
return closes;
|
||||
}
|
||||
|
||||
let passed = 0;
|
||||
function test(name: string, fn: () => void): void {
|
||||
fn();
|
||||
passed += 1;
|
||||
console.log(` ok — ${name}`);
|
||||
}
|
||||
|
||||
test('A ведёт B на 3 шага: bestLag=+3, leader=A', () => {
|
||||
const closesA = arCloses(200, 0.5, 0.02, 42);
|
||||
// B повторяет A с опозданием 3: closesB[i] = closesA[i-3]
|
||||
const closesB = closesA.map((_, i) => closesA[Math.max(0, i - 3)]!);
|
||||
const res = computeRelations(candles(closesA, 0), candles(closesB, 0), 15);
|
||||
assert.equal(res.ok, true);
|
||||
assert.equal(res.bestLag, 3);
|
||||
assert.equal(res.leader, 'A');
|
||||
assert.ok(Math.abs((res.bestCorr ?? 0) - 1) < 5e-3); // на идеальном сдвиге corr ~ 1
|
||||
assert.ok(res.pearson !== null && res.pearson < 0.99); // без сдвига связь слабее
|
||||
});
|
||||
|
||||
test('B ведёт A на 2 шага: bestLag=-2, leader=B', () => {
|
||||
const closesB = arCloses(200, 0.5, 0.02, 7);
|
||||
const closesA = closesB.map((_, i) => closesB[Math.max(0, i - 2)]!);
|
||||
const res = computeRelations(candles(closesA, 0), candles(closesB, 0), 15);
|
||||
assert.equal(res.bestLag, -2);
|
||||
assert.equal(res.leader, 'B');
|
||||
});
|
||||
|
||||
test('синхронное движение: bestLag=0, лидера нет', () => {
|
||||
const closesA = arCloses(200, 0.5, 0.02, 11);
|
||||
const res = computeRelations(candles(closesA, 0), candles(closesA, 0), 15);
|
||||
assert.equal(res.bestLag, 0);
|
||||
assert.equal(res.leader, null);
|
||||
assert.ok(Math.abs((res.bestCorr ?? 0) - 1) < 1e-6);
|
||||
});
|
||||
|
||||
test('мало общих свечей -> ok=false с сообщением', () => {
|
||||
const closesA = arCloses(20, 0.5, 0.02, 3);
|
||||
const res = computeRelations(candles(closesA, 0), candles(closesA, 0), 15);
|
||||
assert.equal(res.ok, false);
|
||||
assert.ok(res.message !== undefined);
|
||||
});
|
||||
|
||||
test('выравнивание по времени: дыры в одном ряду не ломают расчёт', () => {
|
||||
const closesA = arCloses(200, 0.5, 0.02, 5);
|
||||
const full = candles(closesA, 0);
|
||||
const sparse = full.filter((_, i) => i % 5 !== 3); // выкинули каждый пятый день
|
||||
const res = computeRelations(full, sparse, 15);
|
||||
assert.equal(res.ok, true);
|
||||
assert.equal(res.points, sparse.length);
|
||||
assert.equal(res.bestLag, 0); // ряды одинаковы на общих датах
|
||||
assert.equal(res.leader, null);
|
||||
});
|
||||
|
||||
test('seriesBShifted: длина меньше на |lag|, значения сдвинуты', () => {
|
||||
const closesA = arCloses(200, 0.5, 0.02, 42);
|
||||
const closesB = closesA.map((_, i) => closesA[Math.max(0, i - 3)]!);
|
||||
const res = computeRelations(candles(closesA, 0), candles(closesB, 0), 15);
|
||||
assert.ok(res.seriesBShifted);
|
||||
assert.equal(res.seriesBShifted!.length, res.seriesB.length - 3);
|
||||
assert.equal(res.seriesBShifted![0]!.value, res.seriesB[3]!.value);
|
||||
});
|
||||
|
||||
console.log(`\n${passed}/6 тестов отношений пройдено`);
|
||||
Reference in new issue
Block a user