Files
Market_Assistant/backend/scripts/test-positions.ts
T

270 lines
12 KiB
TypeScript

/**
* Тесты движка средней цены позиции (src/positions.ts) — сценарии
* частичного открытия/закрытия по одному инструменту (newPlan.md, этап 1).
*
* Запуск (в backend/): npm run test — без сети, чистая функция.
*/
import assert from 'node:assert/strict';
import { computePositions, hasCampaignBoundary } 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); // старые сделки в расчёт не входят
});
// --- Шорты (этап 1, поддержка отрицательных позиций) ---
test('чистый шорт: две продажи — qty=-15, avg=146.67 (взвешенная)', () => {
const p = pos([t('sell', 10, 150, 1), t('sell', 5, 140, 2)]);
assert.equal(p.qty, -15);
assert.ok(Math.abs(p.avgPrice - (150 * 10 + 140 * 5) / 15) < 1e-9);
assert.ok(Math.abs(p.avgPriceFifo - (150 * 10 + 140 * 5) / 15) < 1e-9);
});
test('шорт + частичное закрытие: sell 10@150, sell 5@140, buy 3@130 → qty=-12, прибыль 60', () => {
const p = pos([t('sell', 10, 150, 1), t('sell', 5, 140, 2), t('buy', 3, 130, 3)]);
assert.equal(p.qty, -12);
// FIFO: первые 3 из 10@150 закрыты buy 3@130 → прибыль 3*(150-130)=60
assert.ok(Math.abs(p.realizedPnl - 60) < 1e-9);
// Остаток: 7@150 + 5@140 → FIFO = (7*150+5*140)/12 = 146.67 (округлённо)
const expectedFifo = (7 * 150 + 5 * 140) / 12;
assert.ok(Math.abs(p.avgPriceFifo - expectedFifo) < 1e-9);
});
test('шорт + полное закрытие: sell 10@150, buy 10@130 → прибыль 200, позиции нет', () => {
const all = computePositions([t('sell', 10, 150, 1), t('buy', 10, 130, 2)]);
assert.equal(all.length, 0);
});
test('лонг → шорт (флип): buy 10@100, sell 15@120 → qty=-5, short@120, сброс кампании', () => {
const p = pos([t('buy', 10, 100, 1), t('sell', 15, 120, 2)]);
assert.equal(p.qty, -5);
assert.equal(p.avgPrice, 120);
assert.equal(p.avgPriceFifo, 120);
assert.equal(p.realizedPnl, 0); // кампания сброшена при флипе
assert.equal(p.operationsCount, 1); // только сделки новой кампании
});
test('шорт → лонг (флип): sell 10@150, buy 15@130 → qty=5, long@130, сброс кампании', () => {
const p = pos([t('sell', 10, 150, 1), t('buy', 15, 130, 2)]);
assert.equal(p.qty, 5);
assert.equal(p.avgPrice, 130);
assert.equal(p.avgPriceFifo, 130);
assert.equal(p.realizedPnl, 0);
assert.equal(p.operationsCount, 1);
});
test('безубыток для шорта: sell 10@150, buy 3@140 → прибыль 30, безубыток 145.71', () => {
const p = pos([t('sell', 10, 150, 1), t('buy', 3, 140, 2)]);
assert.equal(p.qty, -7);
// FIFO: 3@150 закрыто, остаток 7@150; прибыль = 3*(150-140) = 30
assert.ok(Math.abs(p.realizedPnl - 30) < 1e-9);
// breakeven = 150 - 30/7 ≈ 145.714...
assert.ok(Math.abs(p.breakeven - (150 - 30 / 7)) < 1e-9);
});
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); // реализ. сброшен
});
test('движок сортирует по времени сам (порядок в массиве не важен)', () => {
// sell(ms=1) без позиции → шорт qty=-5, buy(ms=2) → закрытие шорта и флип в лонг
const p = pos([t('buy', 10, 200, 2), t('sell', 5, 300, 1)]);
assert.equal(p.qty, 5);
assert.equal(p.avgPrice, 200);
assert.equal(p.operationsCount, 1);
});
test('история флипа: buy 10@100, sell 15@120 — закрытие лонга, затем шорт', () => {
const p = pos([t('buy', 10, 100, 1), t('sell', 15, 120, 2)]);
assert.equal(p.history.length, 2);
// Первая сделка — buy, открыт лонг
assert.equal(p.history[0]!.qty, 10);
assert.ok(Math.abs(p.history[0]!.avgPriceFifo! - 100) < 1e-9);
// Вторая сделка — sell 15: лонг закрыт, флип в шорт qty=-5
assert.equal(p.history[1]!.qty, -5);
assert.ok(Math.abs(p.history[1]!.avgPriceFifo! - 120) < 1e-9);
});
console.log(`\n${passed}/20 тестов пройдено — лонги/шорты/флипы считаются корректно`);
// --- Граница кампании (hasCampaignBoundary: «назад до нуля» при загрузке) ---
test('граница НЕ видна: позиция открыта и не закрывалась — история неполна', () => {
const h = pos([t('buy', 10, 100, 1), t('buy', 5, 110, 2)]).history;
assert.equal(hasCampaignBoundary(h), false);
});
test('граница видна: закрытие в ноль (сброс) — раньше можно не читать', () => {
const h = pos([
t('buy', 10, 100, 1),
t('sell', 10, 150, 2), // закрыто в ноль
t('buy', 5, 200, 3), // новая кампания
]).history;
assert.equal(hasCampaignBoundary(h), true);
});
test('граница видна: переворот лонг→шорт через ноль', () => {
const h = pos([t('buy', 10, 100, 1), t('sell', 15, 120, 2)]).history;
assert.equal(hasCampaignBoundary(h), true); // qty: +10 → -5
});
test('граница видна: переворот шорт→лонг через ноль', () => {
const h = pos([t('sell', 10, 150, 1), t('buy', 15, 130, 2)]).history;
assert.equal(hasCampaignBoundary(h), true); // qty: -10 → +5
});
test('пустая история — граница не видна (грузим дальше)', () => {
assert.equal(hasCampaignBoundary([]), false);
});
console.log(`\n${passed} тестов пройдено — лонги/шорты/флипы/границы кампаний`);