From 78ba250c377a63f5e065e34ad5accd30f07434e9 Mon Sep 17 00:00:00 2001 From: workD12 Date: Wed, 30 Sep 2026 08:53:37 +0300 Subject: [PATCH] =?UTF-8?q?feat(positions):=20=D0=B8=D1=81=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=B8=D1=8F=20=D0=BE=D1=82=20=D0=BF=D0=BE=D1=81=D0=BB?= =?UTF-8?q?=D0=B5=D0=B4=D0=BD=D0=B5=D0=B3=D0=BE=20=D0=BE=D1=80=D0=B4=D0=B5?= =?UTF-8?q?=D1=80=D0=B0=20=D0=BD=D0=B0=D0=B7=D0=B0=D0=B4=20=D0=B4=D0=BE=20?= =?UTF-8?q?=D0=BD=D1=83=D0=BB=D1=8F=20=D0=BA=D0=B0=D0=BC=D0=BF=D0=B0=D0=BD?= =?UTF-8?q?=D0=B8=D0=B8=20(=D0=BF=D0=BE=D1=80=D1=82=D1=84=D0=B5=D0=BB?= =?UTF-8?q?=D1=8C=20+=20=D0=BE=D0=BA=D0=BD=D0=B0=20180=D0=B4,=20hasCampaig?= =?UTF-8?q?nBoundary)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 ++- backend/scripts/test-positions.ts | 34 ++++++++++++++- backend/src/main.ts | 51 +++++++++++++++++++++-- backend/src/positions.ts | 23 ++++++++++ backend/src/tinkoff.ts | 29 +++++++++++++ frontend/src/components/PriceChart.vue | 12 ++++++ frontend/src/components/RelationChart.vue | 1 + progress.md | 11 +++-- 8 files changed, 157 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 40162b3..f0c4b2b 100644 --- a/README.md +++ b/README.md @@ -33,8 +33,10 @@ npm run dev ## Как работает этап 1 -- `GET /api/positions?accountId=` — операции счёта (state=EXECUTED, только BUY/SELL) - с даты открытия счёта → позиции; считаются ДВЕ средние (как в API T-Invest): +- `GET /api/positions?accountId=` — открытые позиции берутся из портфеля, и для + каждого инструмента история читается **от последнего ордера назад до нуля** + (окнами по 180 дней, пока не встретится закрытие в ноль/переворот), а не от + открытия счёта. Считаются ДВЕ средние (как в API T-Invest): - FIFO (`avgPriceFifo`, основная, от неё P&L) — очередь лотов, продажа забирает ранние и МЕНЯЕТ среднюю остатка; именно её T-Invest показывает как `averagePositionPrice` для акций — проверено экспериментом в песочнице diff --git a/backend/scripts/test-positions.ts b/backend/scripts/test-positions.ts index d9df329..4ff9589 100644 --- a/backend/scripts/test-positions.ts +++ b/backend/scripts/test-positions.ts @@ -5,7 +5,7 @@ * Запуск (в backend/): npm run test — без сети, чистая функция. */ import assert from 'node:assert/strict'; -import { computePositions } from '../src/positions.js'; +import { computePositions, hasCampaignBoundary } from '../src/positions.js'; import type { ExecutedTrade } from '../src/tinkoff.js'; const t = ( @@ -235,3 +235,35 @@ test('история флипа: buy 10@100, sell 15@120 — закрытие л }); 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} тестов пройдено — лонги/шорты/флипы/границы кампаний`); diff --git a/backend/src/main.ts b/backend/src/main.ts index 82fab3d..2eb2fa0 100644 --- a/backend/src/main.ts +++ b/backend/src/main.ts @@ -23,14 +23,17 @@ import { getInstrumentMetaByFigi, listShares, } from './tinkoff.js'; -import { computePositions } from './positions.js'; +import { computePositions, hasCampaignBoundary } from './positions.js'; import { computeRelations, MAX_LAG } from './relations.js'; import type { Candle, CandleInterval } from './types.js'; +import type { ExecutedTrade } from './tinkoff.js'; const DAY_MS = 86_400_000; /** Нижняя граница истории операций, если у счёта нет даты открытия. */ const DEFAULT_HISTORY_MS = 3 * 365 * DAY_MS; +/** Шаг окна при движении назад по истории («до нуля» кампании). */ +const HISTORY_WINDOW_MS = 180 * DAY_MS; /** Лимиты окна графика (макс. дней) по интервалу; чанкование — в tinkoff.ts. */ const CANDLE_LIMITS: Record = { @@ -140,12 +143,54 @@ app.get('/api/positions', async (request, reply) => { } const toMs = Date.now(); - const fromMs = + const fromLimitMs = account.openedMs !== null && Number.isFinite(account.openedMs) ? Math.min(account.openedMs, toMs - DAY_MS) : toMs - DEFAULT_HISTORY_MS; - const trades = await getExecutedTrades(account.id, fromMs, toMs); + /** + * История «от последнего ордера назад до нуля»: берём открытые позиции + * из портфеля и для каждого инструмента идём окнами назад (180 дней), + * пока не найдём границу кампании (закрытие в ноль / переворот). + * Если портфель недоступен — фолбэк: вся история от открытия счёта. + */ + const WINDOW_MS = HISTORY_WINDOW_MS; + const loadFigiCampaign = async (figi: string): Promise => { + const merged = new Map(); + let cursorTo = toMs; + for (;;) { + const cursorFrom = Math.max(fromLimitMs, cursorTo - WINDOW_MS); + const batch = await getExecutedTrades(account.id, cursorFrom, cursorTo, figi); + for (const tr of batch) { + merged.set(`${tr.dateMs}|${tr.type}|${tr.qty}|${tr.price}`, tr); + } + // Достаточно ли: граница кампании видна в накопленной истории + const trades = [...merged.values()].sort((a, b) => a.dateMs - b.dateMs); + const [pos] = computePositions(trades); + if (pos !== undefined && hasCampaignBoundary(pos.history)) return trades; + if (cursorFrom <= fromLimitMs) return trades; // дошли до даты открытия + cursorTo = cursorFrom; + } + }; + + let figis: string[] | null = null; + try { + figis = await getOpenPositionFigis(account.id); + } catch { + figis = null; // портфель недоступен — фолбэк ниже + } + + let trades: ExecutedTrade[]; + if (figis === null) { + // Фолбэк: вся история от открытия счёта + trades = await getExecutedTrades(account.id, fromLimitMs, toMs); + } else if (figis.length === 0) { + trades = []; // открытых позиций нет — историю можно не читать + } else { + const perFigi = await Promise.all(figis.map((f) => loadFigiCampaign(f))); + trades = perFigi.flat(); + } + const raw = computePositions(trades); const metas = await Promise.all(raw.map((p) => getInstrumentMetaByFigi(p.figi))); const prices = await getLastPrices(raw.map((p) => p.figi)); diff --git a/backend/src/positions.ts b/backend/src/positions.ts index 30d47a0..75cea95 100644 --- a/backend/src/positions.ts +++ b/backend/src/positions.ts @@ -51,6 +51,29 @@ export interface HistoryEntry { const QTY_EPSILON = 1e-6; +/** + * Видна ли в истории ГРАНИЦА кампании (начало «захода») — сигнал, что более + * ранние сделки не нужны: позиция до этого была закрыта в ноль (сброс) или + * произошёл переворот через ноль (флип лонг↔шорт). + * + * Используется при загрузке истории «от последнего ордера назад до нуля»: + * как только граница найдена — ранние окна не запрашиваются. + */ +export function hasCampaignBoundary(history: HistoryEntry[]): boolean { + for (let i = 0; i < history.length; i++) { + const e = history[i]; + if (e === undefined) continue; + // Закрытие в ноль — сброс алгоритма (снапшот с qty=0) + if (e.qty === 0) return true; + // Переворот: знак позиции сменился между соседними сделками + const prev = history[i - 1]; + if (prev !== undefined && prev.qty !== 0) { + if ((prev.qty > 0 && e.qty < 0) || (prev.qty < 0 && e.qty > 0)) return true; + } + } + return false; +} + /** Состояние позиции по одному инструменту. */ interface State { /** Положительное — лонг, отрицательное — шорт. */ diff --git a/backend/src/tinkoff.ts b/backend/src/tinkoff.ts index 2a43451..4fa13b0 100644 --- a/backend/src/tinkoff.ts +++ b/backend/src/tinkoff.ts @@ -215,6 +215,8 @@ export async function getExecutedTrades( accountId: string, fromMs: number, toMs: number, + /** Опционально: только операции одного инструмента (фильтр на стороне API). */ + figiFilter?: string, ): Promise { const client = getClient(); const req = { @@ -222,6 +224,7 @@ export async function getExecutedTrades( from: toTimestamp(fromMs), to: toTimestamp(toMs), state: 'OPERATION_STATE_EXECUTED' as const, + ...(figiFilter === undefined ? {} : { figi: figiFilter }), }; // ВАЖНО: sandbox-счёт виден только через SandboxService — обычный // OperationsService отвечает UNAUTHENTICATED (16 40003). @@ -257,6 +260,32 @@ export async function getExecutedTrades( return trades; } +// ---------- Портфель: текущие открытые позиции ---------- + +/** + * FIGI инструментов, открытых СЕЙЧАС (по портфелю брокера), — отправная точка + * для загрузки истории «от последнего ордера назад до нуля»: кампании по + * инструментам вне этого списка всё равно закрыты и не интересуют. + */ +export async function getOpenPositionFigis(accountId: string): Promise { + const client = getClient(); + // sandbox-счёт виден только через SandboxService (см. грабли #1 в progress.md) + const res = (await request((cb) => + config.tinkoffSandbox + ? client.sandbox.getSandboxPortfolio({ accountId }, cb) + : client.operations.getPortfolio({ accountId }, cb), + )) as { + positions?: Array<{ figi?: unknown; quantity?: unknown }>; + }; + const figis = new Set(); + for (const p of res.positions ?? []) { + const qty = toNumber(p.quantity); + if (!p.figi || !Number.isFinite(qty) || Math.abs(qty) < 1e-6) continue; + figis.add(String(p.figi)); + } + return [...figis]; +} + // ---------- Последние цены ---------- /** Последние цены по списку FIGI одним запросом; недоступные пропускаются. */ diff --git a/frontend/src/components/PriceChart.vue b/frontend/src/components/PriceChart.vue index 8843b2d..50de278 100644 --- a/frontend/src/components/PriceChart.vue +++ b/frontend/src/components/PriceChart.vue @@ -130,6 +130,12 @@ function buildSeries(): Highcharts.SeriesOptionsType[] { radius: 7, lineColor: 'transparent', }, + // scatter по умолчанию показывает time как unix — форматируем в дату + tooltip: { + headerFormat: '\u25CF ' + + '{point.x:%d.%m.%Y %H:%M}
', + pointFormat: '{series.name}: {point.y:.2f}', + }, data: [], } as Highcharts.SeriesScatterOptions); list.push({ @@ -143,6 +149,11 @@ function buildSeries(): Highcharts.SeriesOptionsType[] { radius: 7, lineColor: 'transparent', }, + tooltip: { + headerFormat: '\u25CF ' + + '{point.x:%d.%m.%Y %H:%M}
', + pointFormat: '{series.name}: {point.y:.2f}', + }, data: [], } as Highcharts.SeriesScatterOptions); return list; @@ -231,6 +242,7 @@ function baseOptions(): Highcharts.Options { borderColor: 'rgba(148, 163, 184, 0.25)', borderRadius: 8, shadow: false, + valueDecimals: 2, }, series: buildSeries(), }; diff --git a/frontend/src/components/RelationChart.vue b/frontend/src/components/RelationChart.vue index 9de952f..aa8c68a 100644 --- a/frontend/src/components/RelationChart.vue +++ b/frontend/src/components/RelationChart.vue @@ -113,6 +113,7 @@ function render(): void { borderColor: 'rgba(148, 163, 184, 0.25)', borderRadius: 8, shadow: false, + valueDecimals: 2, }, series: props.series.map(toSeries), }); diff --git a/progress.md b/progress.md index 28e06cd..8e746eb 100644 --- a/progress.md +++ b/progress.md @@ -5,7 +5,7 @@ > > **Новому ассистенту / себе домой**: читать в порядке newPlan.md → README.md → этот файл. > Всё локализовано: движки — `backend/src/positions.ts`, `backend/src/relations.ts`; -> тесты — `backend/scripts/test-*.ts` (20+6); UI-вкладки — `frontend/src/components/*Tab.vue`. +> тесты — `backend/scripts/test-*.ts` (25+6); UI-вкладки — `frontend/src/components/*Tab.vue`. ## Статус этапов (newPlan.md) @@ -32,8 +32,11 @@ - **D7. Отношения**: свечи пары выравниваются по общим временам, корреляция ЛОГ-доходностей, corr(lag) = corr(rA[i], rB[i+lag]), лучший лаг = argmax|corr|; lag=0 → «лидера нет». maxLag: 1д=±15, 1ч=±24, 15м/5м=±16. -- **D8. Ступеньки**: движок снимает снапшот после каждой сделки (`history[]` в позиции): - время, тип, цена, qty, avgFifo, breakeven. UI: step-серии ('right') + scatter-маркеры. +- **D9. История «от последнего ордера назад до нуля»**: список инструментов — + из текущего портфеля (`getPortfolio` / `getSandboxPortfolio`), далее по каждому + FIGI окна назад (180 дней, фильтр figi в Operations API) до границы кампании + (`hasCampaignBoundary`: закрытие в ноль или переворот). Фолбэк при недоступности + портфеля — вся история от открытия счёта. Открытых позиций нет ⇒ история не читается. ## Грабли T-Invest API (выявлены живыми тестами — экономят часы) / @@ -71,7 +74,7 @@ cd backend && npm run dev # :8000 (tsx watch) cd frontend && npm run dev # :5173, прокси /api -> :8000; открывать http://localhost:5173 -# тесты движков (без сети): cd backend && npm run test # 20 позиционных + 6 отношений +# тесты движков (без сети): cd backend && npm run test # 25 позиционных + 6 отношений # типы/сборка: backend: npm run typecheck; frontend: npm run build # утилиты песочницы: npm run sandbox-demo | sandbox-diag # и: NODE_EXTRA_CA_CERTS=./certs/ca-all.pem npx tsx scripts/sandbox-avg-test.ts