Files

153 lines
6.0 KiB
TypeScript

/**
* Эмпирический тест средней цены (этап 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);
});