Files
Market_Assistant/backend/src/positions.ts
T

231 lines
9.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Этап 1 (newPlan.md): расчёт средней цены позиции в рынке по истории
* исполненных сделок — лонги И шорты.
*
* Две средние — как в API T-Invest (averagePositionPrice / averagePositionPriceFifo):
* - взвешенная: открывающая сторона смешивает цену, закрывающая — не меняет;
* - FIFO (основная): очередь лотов, закрытие забирает ранние — средняя
* остатка меняется.
*
* Логика зеркальна для лонгов и шортов:
* - Лонг (qty > 0): BUY открывает/добавляет, SELL закрывает (FIFO лотов покупки);
* - Шорт (qty < 0): SELL открывает/добавляет, BUY закрывает (FIFO лотов продажи);
* - Переворот (флип): при пересечении qty через ноль — кампания сбрасывается
* и начинается новая на противоположной стороне;
* - Сброс только при qty == 0 (закрытая позиция не интересует).
*/
import type { ExecutedTrade } from './tinkoff.js';
export interface RawPosition {
figi: string;
/** Число инструментов в позиции, шт. (отрицательное — шорт). */
qty: number;
/** Взвешенная средняя цена входа (закрывающие сделки не меняют). */
avgPrice: number;
/** Средняя остатка по FIFO (закрывающие сделки меняют) — основная, как у брокера. */
avgPriceFifo: number;
/** Накопленный реализованный P&L с последнего сброса (по FIFO), руб. */
realizedPnl: number;
/** «Безубыток»: цена, при которой весь заход выйдет в ноль с учётом
* реализованных сделок = avgPriceFifo − realizedPnl / |qty|. */
breakeven: number;
/** Сколько исполненных сделок учтено с последнего сброса. */
operationsCount: number;
firstOperationMs: number | null;
lastOperationMs: number | null;
/** Снимки состояния после каждой сделки — ступеньки на графике. */
history: HistoryEntry[];
}
/** Снимок позиции после одной сделки (для ступенек и маркеров на графике). */
export interface HistoryEntry {
timeMs: number;
type: 'buy' | 'sell';
price: number;
qtyTrade: number;
/** Позиция после сделки; 0 — закрыта в ноль (линия рвётся). */
qty: number;
avgPriceFifo: number | null;
breakeven: number | null;
}
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 {
/** Положительное — лонг, отрицательное — шорт. */
qty: number;
/** Взвешенная средняя цена входа. */
avg: number;
/** Очередь лотов для FIFO: при лонге — лоты покупки, при шорте — лоты продажи. */
lots: Array<{ qty: number; price: number }>;
/** Накопленный реализованный P&L (по FIFO), руб. */
realized: number;
count: number;
firstMs: number | null;
lastMs: number | null;
}
/** Снимок позиции после сделки — «ступеньки» средней/безубытка на графике. */
function snapshot(
historyMap: Map<string, HistoryEntry[]>,
t: ExecutedTrade,
s: State,
): void {
const open = Math.abs(s.qty) >= QTY_EPSILON;
const absQty = Math.abs(s.qty);
const avgNow = open
? s.lots.reduce((acc, l) => acc + l.qty * l.price, 0) / absQty
: null;
const beNow = avgNow !== null ? avgNow - s.realized / absQty : null;
const entries = historyMap.get(t.figi) ?? [];
entries.push({
timeMs: t.dateMs,
type: t.type,
price: t.price,
qtyTrade: t.qty,
qty: open ? Math.round(s.qty * 1e6) / 1e6 : 0,
avgPriceFifo: avgNow,
breakeven: beNow,
});
historyMap.set(t.figi, entries);
}
export function computePositions(trades: ExecutedTrade[]): RawPosition[] {
const sorted = [...trades].sort((a, b) => a.dateMs - b.dateMs);
const state = new Map<string, State>();
const historyMap = new Map<string, HistoryEntry[]>();
for (const t of sorted) {
const s: State = state.get(t.figi) ?? {
qty: 0,
avg: 0,
lots: [],
realized: 0,
count: 0,
firstMs: null,
lastMs: null,
};
s.count += 1;
if (s.firstMs === null) s.firstMs = t.dateMs;
s.lastMs = t.dateMs;
let deleted = false;
if (t.type === 'buy') {
if (s.qty >= -QTY_EPSILON) {
// Лонг или пусто: BUY открывает/добавляет позицию
s.avg =
s.qty > QTY_EPSILON
? (s.avg * s.qty + t.price * t.qty) / (s.qty + t.qty)
: t.price;
s.qty += t.qty;
s.lots.push({ qty: t.qty, price: t.price });
} else {
// Шорт: BUY закрывает короткую позицию (FIFO лотов продажи)
s.qty += t.qty;
let rest = t.qty;
while (rest > QTY_EPSILON && s.lots.length > 0) {
const head = s.lots[0];
if (!head) break;
const take = Math.min(head.qty, rest);
head.qty -= take;
rest -= take;
s.realized += take * (head.price - t.price);
if (head.qty <= QTY_EPSILON) s.lots.shift();
}
if (s.qty > QTY_EPSILON) {
// Переворот в лонг: остаток BUY открывает новую позицию
s.avg = t.price;
s.lots = [{ qty: rest, price: t.price }];
s.realized = 0;
s.count = 1;
} else if (Math.abs(s.qty) < QTY_EPSILON) {
deleted = true;
}
}
} else {
// sell
if (s.qty <= QTY_EPSILON) {
// Шорт или пусто: SELL открывает/добавляет короткую позицию
const absQty = Math.abs(s.qty);
s.avg =
s.qty < -QTY_EPSILON
? (s.avg * absQty + t.price * t.qty) / (absQty + t.qty)
: t.price;
s.qty -= t.qty;
s.lots.push({ qty: t.qty, price: t.price });
} else {
// Лонг: SELL закрывает длинную позицию (FIFO лотов покупки)
s.qty -= t.qty;
let rest = t.qty;
while (rest > QTY_EPSILON && s.lots.length > 0) {
const head = s.lots[0];
if (!head) break;
const take = Math.min(head.qty, rest);
head.qty -= take;
rest -= take;
s.realized += take * (t.price - head.price);
if (head.qty <= QTY_EPSILON) s.lots.shift();
}
if (s.qty < -QTY_EPSILON) {
// Переворот в шорт: остаток SELL открывает новую короткую позицию
s.avg = t.price;
s.lots = [{ qty: rest, price: t.price }];
s.realized = 0;
s.count = 1;
} else if (Math.abs(s.qty) < QTY_EPSILON) {
deleted = true;
}
}
}
snapshot(historyMap, t, s);
if (deleted) {
state.delete(t.figi);
} else {
state.set(t.figi, s);
}
}
return [...state.entries()].map(([figi, s]) => {
const absQty = Math.abs(s.qty);
const fifoSum = s.lots.reduce((acc, l) => acc + l.qty * l.price, 0);
return {
figi,
qty: Math.round(s.qty * 1e6) / 1e6,
avgPrice: s.avg,
avgPriceFifo: fifoSum / absQty,
realizedPnl: Math.round(s.realized * 100) / 100,
breakeven: fifoSum / absQty - s.realized / absQty,
operationsCount: s.count,
firstOperationMs: s.firstMs,
lastOperationMs: s.lastMs,
history: historyMap.get(figi) ?? [],
};
});
}