102 lines
3.9 KiB
TypeScript
102 lines
3.9 KiB
TypeScript
/**
|
|
* Демо для этапа 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);
|
|
});
|