init: Market Assistant — этап 1 (позиции: FIFO-средняя, цена безубытка, ступеньки, маркеры ордеров) + этап 2 (отношения инструментов: лаг-корреляция)
This commit is contained in:
commit
0af45d2902
46 files changed
+8105
No files matched your search
@@ -0,0 +1,578 @@
|
||||
<script setup lang="ts">
|
||||
import Highcharts from 'highcharts/es-modules/masters/highstock.src.js';
|
||||
import 'highcharts/es-modules/masters/modules/accessibility.src.js';
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { useAppStore } from '../stores/appStore';
|
||||
import type { Candle } from '../api';
|
||||
|
||||
const store = useAppStore();
|
||||
const chartRoot = ref<HTMLDivElement | null>(null);
|
||||
let chart: Highcharts.Chart | null = null;
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
let suppressRangeHandler = false;
|
||||
|
||||
const baseOptions: Highcharts.Options = {
|
||||
chart: {
|
||||
backgroundColor: '#0f1724',
|
||||
style: { fontFamily: 'IBM Plex Sans, Segoe UI, sans-serif' },
|
||||
animation: false,
|
||||
},
|
||||
credits: { enabled: false },
|
||||
title: { text: undefined },
|
||||
legend: {
|
||||
enabled: true,
|
||||
itemStyle: { color: '#b6c2d9', fontSize: '11px' },
|
||||
itemHoverStyle: { color: '#ffffff' },
|
||||
},
|
||||
rangeSelector: { enabled: false },
|
||||
scrollbar: { enabled: false },
|
||||
navigator: {
|
||||
enabled: true,
|
||||
// Не синхронизировать данные навигатора с базовыми сериями:
|
||||
// данные полной истории кладём вручную через updateNavigator()
|
||||
adaptToUpdatedData: false,
|
||||
height: 70,
|
||||
margin: 6,
|
||||
maskFill: 'rgba(99, 179, 237, 0.2)',
|
||||
maskInside: true,
|
||||
outlineColor: 'rgba(148, 163, 184, 0.25)',
|
||||
handles: {
|
||||
backgroundColor: '#5b8dd9',
|
||||
borderColor: '#8ab4f8',
|
||||
width: 8,
|
||||
height: 20,
|
||||
},
|
||||
xAxis: {
|
||||
labels: { style: { color: '#8e9db8', fontSize: '10px' } },
|
||||
gridLineColor: 'rgba(148, 163, 184, 0.08)',
|
||||
},
|
||||
series: { type: 'candlestick', color: '#f85149', upColor: '#3fb950' },
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'rgba(15, 23, 36, 0.95)',
|
||||
style: { color: '#d3deef' },
|
||||
borderColor: 'rgba(148, 163, 184, 0.25)',
|
||||
borderRadius: 8,
|
||||
shadow: false,
|
||||
shared: true,
|
||||
split: false,
|
||||
xDateFormat: '%A, %b %e, %H:%M',
|
||||
},
|
||||
plotOptions: {
|
||||
series: {
|
||||
animation: false,
|
||||
dataGrouping: { enabled: false },
|
||||
states: { inactive: { opacity: 1 } },
|
||||
},
|
||||
candlestick: {
|
||||
color: '#f85149',
|
||||
upColor: '#3fb950',
|
||||
lineColor: '#ff7b72',
|
||||
upLineColor: '#58d26b',
|
||||
},
|
||||
},
|
||||
xAxis: {
|
||||
crosshair: {
|
||||
color: 'rgba(239, 68, 68, 0.35)',
|
||||
dashStyle: 'Dash',
|
||||
label: { enabled: false },
|
||||
},
|
||||
lineColor: 'rgba(148, 163, 184, 0.2)',
|
||||
tickColor: 'rgba(148, 163, 184, 0.2)',
|
||||
labels: { style: { color: '#8e9db8', fontSize: '11px' } },
|
||||
gridLineColor: 'rgba(148, 163, 184, 0.08)',
|
||||
events: {
|
||||
setExtremes(e: Highcharts.AxisSetExtremesEventObject) {
|
||||
if (suppressRangeHandler) return;
|
||||
if (e.min == null || e.max == null) return;
|
||||
// Пользователь двигает окно в навигаторе: фиксируем диапазон и подгружаем данные
|
||||
store.fromTime = new Date(e.min).toISOString().slice(0, 16);
|
||||
store.toTime = new Date(e.max).toISOString().slice(0, 16);
|
||||
scheduleWindowLoad();
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const visibleCandles = computed(() => {
|
||||
if (!store.fromTime || !store.toTime) return [];
|
||||
const fromMs = new Date(`${store.fromTime}:00Z`).getTime();
|
||||
const toMs = new Date(`${store.toTime}:00Z`).getTime();
|
||||
return store.replayCandles.filter((c) => {
|
||||
const ms = new Date(c.time).getTime();
|
||||
return ms >= fromMs && ms < toMs;
|
||||
});
|
||||
});
|
||||
|
||||
let rangeLoadTimer: number | null = null;
|
||||
let windowMoveTimer: number | null = null;
|
||||
|
||||
function clearRangeLoadTimer(): void {
|
||||
if (rangeLoadTimer != null) {
|
||||
window.clearTimeout(rangeLoadTimer);
|
||||
rangeLoadTimer = null;
|
||||
}
|
||||
if (windowMoveTimer != null) {
|
||||
window.clearTimeout(windowMoveTimer);
|
||||
windowMoveTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleWindowLoad(): void {
|
||||
clearRangeLoadTimer();
|
||||
rangeLoadTimer = window.setTimeout(() => {
|
||||
rangeLoadTimer = null;
|
||||
const fromMs = store.fromTime ? new Date(`${store.fromTime}:00Z`).getTime() : NaN;
|
||||
const toMs = store.toTime ? new Date(`${store.toTime}:00Z`).getTime() : NaN;
|
||||
if (!Number.isFinite(fromMs) || !Number.isFinite(toMs)) return;
|
||||
|
||||
// Диапазон уже полностью в загруженных данных — перезагрузка не нужна.
|
||||
// Сжатие ширины делает сам loadCandles (лимит бюджета), не здесь.
|
||||
const loaded = store.replayCandles;
|
||||
if (loaded.length > 0) {
|
||||
const firstMs = new Date(loaded[0].time).getTime();
|
||||
const lastMs = new Date(loaded[loaded.length - 1].time).getTime();
|
||||
if (fromMs >= firstMs && toMs <= lastMs) return;
|
||||
}
|
||||
void store.loadCandles();
|
||||
}, 350);
|
||||
}
|
||||
|
||||
function createChartIfNeeded(): void {
|
||||
if (!chartRoot.value || chart) return;
|
||||
|
||||
chart = Highcharts.stockChart(chartRoot.value, {
|
||||
...baseOptions,
|
||||
chart: { ...baseOptions.chart, height: 680 },
|
||||
yAxis: [
|
||||
{ height: '58%', lineWidth: 1, gridLineColor: 'rgba(148, 163, 184, 0.08)', labels: { style: { color: '#8e9db8', fontSize: '11px' } }, resize: { enabled: true } },
|
||||
{ top: '62%', height: '30%', offset: 0, lineWidth: 1, gridLineColor: 'rgba(148, 163, 184, 0.08)', labels: { style: { color: '#8e9db8', fontSize: '11px' } } },
|
||||
{ height: '58%', opposite: false, visible: false },
|
||||
],
|
||||
series: [
|
||||
{ type: 'candlestick', id: 'candles', name: store.selectedTicker, data: [] } as Highcharts.SeriesCandlestickOptions,
|
||||
{ type: 'line', id: 'equity', name: 'Депозит', data: [], yAxis: 1, color: '#46d7a4', lineWidth: 2, marker: { enabled: false }, showInLegend: true } as Highcharts.SeriesLineOptions,
|
||||
],
|
||||
});
|
||||
|
||||
resizeObserver = new ResizeObserver(() => chart?.reflow());
|
||||
resizeObserver.observe(chartRoot.value);
|
||||
}
|
||||
|
||||
function updateCandles(): void {
|
||||
if (!chart) return;
|
||||
const series = chart.get('candles') as Highcharts.Series | undefined;
|
||||
const data: [number, number, number, number, number][] = visibleCandles.value.map((c) => [
|
||||
new Date(c.time).getTime(),
|
||||
c.open,
|
||||
c.high,
|
||||
c.low,
|
||||
c.close,
|
||||
]);
|
||||
series?.setData(data, false);
|
||||
}
|
||||
|
||||
function updateNavigator(): void {
|
||||
if (!chart) return;
|
||||
const nav = chart.get('highcharts-navigator-series') as Highcharts.Series | undefined;
|
||||
const source = store.navigatorCandles.length > 0 ? store.navigatorCandles : store.replayCandles;
|
||||
// redraw=true обязателен: иначе ось навигатора не пересчитывает масштаб под новые данные
|
||||
nav?.setData(
|
||||
source.map((c) => [new Date(c.time).getTime(), c.open, c.high, c.low, c.close] as [number, number, number, number, number]),
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
function updateEquity(): void {
|
||||
if (!chart) return;
|
||||
const series = chart.get('equity') as Highcharts.Series | undefined;
|
||||
if (!series) return;
|
||||
|
||||
const bt = store.activeBtResult();
|
||||
if (bt) {
|
||||
series.update({ type: 'line', name: 'Эквити стратегии' }, false);
|
||||
// Highcharts ждёт [x, y] (или {x, y}); объекты {time, value} дают x=NaN →
|
||||
// точка улетает в эпоху 1970 и растягивает ось навигатора.
|
||||
const points = bt.equity
|
||||
.map((p) => ({ time: new Date(p.t).getTime(), value: p.equity }))
|
||||
.filter((p) => Number.isFinite(p.time) && Number.isFinite(p.value));
|
||||
const downsampled = downsample(points, 1200).map((p) => [p.time, p.value] as [number, number]);
|
||||
series.setData(downsampled, false);
|
||||
} else {
|
||||
series.update({ type: 'line', name: 'Депозит (ручной)' }, false);
|
||||
const timeline = computePortfolioTimeline(visibleCandles.value);
|
||||
store.portfolioSnapshot = timeline.snapshot;
|
||||
series.setData(timeline.equityPoints.map((p) => [p.time, p.value]), false);
|
||||
}
|
||||
}
|
||||
|
||||
function updateIndicators(): void {
|
||||
if (!chart) return;
|
||||
const firstMs = visibleCandles.value[0] ? new Date(visibleCandles.value[0].time).getTime() : 0;
|
||||
const lastMs = visibleCandles.value.at(-1) ? new Date(visibleCandles.value.at(-1)!.time).getTime() : Infinity;
|
||||
const clipFrom = firstMs;
|
||||
const clipTo = lastMs + 1;
|
||||
|
||||
store.indicators.forEach((indicator) => {
|
||||
const backendSeries = store.indicatorSeriesByKey[indicatorKey(indicator)];
|
||||
const points = backendSeries?.points ?? [];
|
||||
const data = points
|
||||
.filter((p) => {
|
||||
const ms = new Date(p.time).getTime();
|
||||
return ms >= clipFrom && ms < clipTo;
|
||||
})
|
||||
.map((p) => [new Date(p.time).getTime(), p.value] as [number, number]);
|
||||
let series = chart!.get(`ind-${indicator.id}`) as Highcharts.Series | undefined;
|
||||
if (!series) {
|
||||
chart!.addSeries(
|
||||
{
|
||||
type: 'line',
|
||||
id: `ind-${indicator.id}`,
|
||||
name: indicatorLabel(indicator),
|
||||
data: [],
|
||||
yAxis: indicator.kind === 'deviation' ? 2 : 0,
|
||||
color: indicatorColor(store.indicators.indexOf(indicator)),
|
||||
lineWidth: 2,
|
||||
marker: { enabled: false },
|
||||
enableMouseTracking: false,
|
||||
showInLegend: true,
|
||||
states: { hover: { enabled: false } },
|
||||
},
|
||||
false,
|
||||
);
|
||||
series = chart!.get(`ind-${indicator.id}`) as Highcharts.Series | undefined;
|
||||
}
|
||||
series?.setData(data, false);
|
||||
});
|
||||
|
||||
// Remove stale indicator series
|
||||
chart.series
|
||||
.filter((s) => String(s.options.id ?? '').startsWith('ind-'))
|
||||
.forEach((s) => {
|
||||
const id = Number(String(s.options.id).replace('ind-', ''));
|
||||
if (!store.indicators.some((i) => i.id === id)) {
|
||||
s.remove(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function updateBtIndicators(): void {
|
||||
if (!chart) return;
|
||||
const bt = store.activeBtResult();
|
||||
if (!bt || bt.indicators.length === 0) {
|
||||
chart.series
|
||||
.filter((s) => String(s.options.id ?? '').startsWith('bt-ind-'))
|
||||
.forEach((s) => s.remove(false));
|
||||
return;
|
||||
}
|
||||
|
||||
const firstMs = visibleCandles.value[0] ? new Date(visibleCandles.value[0].time).getTime() : 0;
|
||||
const lastMs = visibleCandles.value.at(-1) ? new Date(visibleCandles.value.at(-1)!.time).getTime() : Infinity;
|
||||
const palette = ['#f6c453', '#59c3c3', '#d879e8', '#84cc16'];
|
||||
|
||||
bt.indicators.forEach((ind, idx) => {
|
||||
let series = chart!.get(`bt-ind-${idx}`) as Highcharts.Series | undefined;
|
||||
if (!series) {
|
||||
chart!.addSeries(
|
||||
{
|
||||
type: 'line',
|
||||
id: `bt-ind-${idx}`,
|
||||
name: ind.label,
|
||||
data: [],
|
||||
yAxis: 0,
|
||||
color: palette[idx % palette.length],
|
||||
lineWidth: 2,
|
||||
marker: { enabled: false },
|
||||
enableMouseTracking: false,
|
||||
showInLegend: true,
|
||||
states: { hover: { enabled: false } },
|
||||
},
|
||||
false,
|
||||
);
|
||||
series = chart!.get(`bt-ind-${idx}`) as Highcharts.Series | undefined;
|
||||
}
|
||||
const data = ind.points
|
||||
.filter((p) => {
|
||||
const ms = new Date(p.t).getTime();
|
||||
return ms >= firstMs && ms < lastMs;
|
||||
})
|
||||
.map((p) => [new Date(p.t).getTime(), p.value] as [number, number]);
|
||||
series?.setData(data, false);
|
||||
});
|
||||
}
|
||||
|
||||
function updateTradeAnnotations(): void {
|
||||
if (!chart) return;
|
||||
|
||||
const candlesByMs = new Map<number, Candle>(
|
||||
visibleCandles.value.map((c) => [new Date(c.time).getTime(), c]),
|
||||
);
|
||||
const sortedEvents = [...store.tradeEvents]
|
||||
.sort((a, b) => a.timeMs - b.timeMs || a.id - b.id)
|
||||
.filter((e) => candlesByMs.has(e.timeMs));
|
||||
|
||||
const flags: { x: number; title: string; text: string }[] = [];
|
||||
const tradeLines: Array<[number, number, number, number]> = [];
|
||||
const openBySide: Partial<Record<'long' | 'short', { x: number; price: number }>> = {};
|
||||
|
||||
sortedEvents.forEach((event) => {
|
||||
const candle = candlesByMs.get(event.timeMs)!;
|
||||
const x = event.timeMs;
|
||||
const price = candle.close;
|
||||
if (event.side === 'long' && event.action === 'open') {
|
||||
flags.push({ x, title: 'L', text: 'Long open' });
|
||||
openBySide.long = { x, price };
|
||||
} else if (event.side === 'short' && event.action === 'open') {
|
||||
flags.push({ x, title: 'S', text: 'Short open' });
|
||||
openBySide.short = { x, price };
|
||||
} else if (event.side === 'long' && event.action === 'close') {
|
||||
flags.push({ x, title: 'X', text: 'Long close' });
|
||||
if (openBySide.long) {
|
||||
tradeLines.push([openBySide.long.x, openBySide.long.price, x, price]);
|
||||
delete openBySide.long;
|
||||
}
|
||||
} else if (event.side === 'short' && event.action === 'close') {
|
||||
flags.push({ x, title: 'X', text: 'Short close' });
|
||||
if (openBySide.short) {
|
||||
tradeLines.push([openBySide.short.x, openBySide.short.price, x, price]);
|
||||
delete openBySide.short;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const bt = store.activeBtResult();
|
||||
if (bt && store.fromTime && store.toTime) {
|
||||
const fromMs = new Date(`${store.fromTime}:00Z`).getTime();
|
||||
const toMs = new Date(`${store.toTime}:00Z`).getTime();
|
||||
bt.trades.forEach((trade) => {
|
||||
const entryMs = new Date(trade.entryTime).getTime();
|
||||
// exitTime может отсутствовать у незакрытой позиции — NaN отфильтруется ниже
|
||||
const exitMs = trade.exitTime ? new Date(trade.exitTime).getTime() : Number.NaN;
|
||||
if (!Number.isFinite(entryMs)) return;
|
||||
const entryInView = entryMs >= fromMs && entryMs < toMs && candlesByMs.has(entryMs);
|
||||
const exitInView = Number.isFinite(exitMs) && exitMs >= fromMs && exitMs < toMs && candlesByMs.has(exitMs);
|
||||
if (entryInView) flags.push({ x: entryMs, title: trade.side === 'long' ? 'bL' : 'bS', text: `${trade.side} entry` });
|
||||
if (exitInView) flags.push({ x: exitMs, title: 'bx', text: `${trade.side} exit` });
|
||||
if (entryInView && exitInView) tradeLines.push([entryMs, trade.entryPrice, exitMs, trade.exitPrice]);
|
||||
});
|
||||
}
|
||||
|
||||
chart.series
|
||||
.filter((s) => String(s.options.id ?? '').startsWith('trade-'))
|
||||
.forEach((s) => s.remove(false));
|
||||
|
||||
if (flags.length) {
|
||||
chart.addSeries(
|
||||
{
|
||||
type: 'flags',
|
||||
id: 'trade-flags',
|
||||
data: flags,
|
||||
yAxis: 0,
|
||||
onSeries: 'candles',
|
||||
shape: 'flag',
|
||||
color: '#0f1724',
|
||||
fillColor: 'rgba(15, 23, 36, 0.85)',
|
||||
style: { color: '#ffffff', fontSize: '10px' },
|
||||
states: { hover: { enabled: false } },
|
||||
},
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
tradeLines.forEach(([x1, y1, x2, y2], idx) => {
|
||||
chart!.addSeries(
|
||||
{
|
||||
type: 'line',
|
||||
id: `trade-line-${idx}`,
|
||||
data: [
|
||||
[x1, y1],
|
||||
[x2, y2],
|
||||
],
|
||||
yAxis: 0,
|
||||
color: '#f472b6',
|
||||
lineWidth: 1,
|
||||
dashStyle: 'Dash',
|
||||
marker: { enabled: false },
|
||||
enableMouseTracking: false,
|
||||
showInLegend: false,
|
||||
},
|
||||
false,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function indicatorKey(indicator: { kind: import('../stores/appStore').IndicatorKind; period: number }): string {
|
||||
return `${indicator.kind}:${indicator.period}`;
|
||||
}
|
||||
|
||||
function indicatorLabel(indicator: { kind: import('../stores/appStore').IndicatorKind; period: number }): string {
|
||||
return indicator.kind === 'sma' ? `SMA (${indicator.period})` : `Отклонение (${indicator.period})`;
|
||||
}
|
||||
|
||||
function indicatorColor(index: number): string {
|
||||
return ['#f6c453', '#59c3c3', '#d879e8', '#84cc16'][index % 4];
|
||||
}
|
||||
|
||||
function render(): void {
|
||||
if (!chart || visibleCandles.value.length === 0) return;
|
||||
const prev = chart.xAxis[0].getExtremes();
|
||||
|
||||
suppressRangeHandler = true;
|
||||
updateCandles();
|
||||
updateEquity();
|
||||
updateIndicators();
|
||||
updateBtIndicators();
|
||||
updateTradeAnnotations();
|
||||
updateNavigator();
|
||||
chart.redraw(false);
|
||||
|
||||
if (store.pendingVisibleRangeMs) {
|
||||
chart.xAxis[0].setExtremes(store.pendingVisibleRangeMs.from, store.pendingVisibleRangeMs.to, true);
|
||||
store.pendingVisibleRangeMs = null;
|
||||
} else if (store.forceFitNextRender) {
|
||||
chart.xAxis[0].setExtremes(undefined, undefined, true);
|
||||
store.forceFitNextRender = false;
|
||||
} else if (prev.min != null && prev.max != null) {
|
||||
chart.xAxis[0].setExtremes(prev.min, prev.max, true);
|
||||
}
|
||||
setTimeout(() => {
|
||||
suppressRangeHandler = false;
|
||||
}, 80);
|
||||
}
|
||||
|
||||
interface EquityPoint {
|
||||
time: number;
|
||||
value: number;
|
||||
}
|
||||
|
||||
function computePortfolioTimeline(candles: Candle[]): { equityPoints: EquityPoint[]; snapshot: import('../stores/appStore').PortfolioSnapshot } {
|
||||
let cash = Number(store.initialDeposit);
|
||||
let longPosition: import('../stores/appStore').ManualPosition | null = null;
|
||||
let shortPosition: import('../stores/appStore').ManualPosition | null = null;
|
||||
const feePct = Math.max(0, Number(store.brokerCommissionPct) || 0) / 100;
|
||||
const shortRate = Math.max(0, Number(store.shortRateAnnualPct) || 0);
|
||||
const longPct = Math.max(0, Math.min(100, Number(store.longAllocationPct) || 0));
|
||||
const shortPct = Math.max(0, Math.min(100, Number(store.shortAllocationPct) || 0));
|
||||
const sortedEvents = [...store.tradeEvents].sort((a, b) => a.timeMs - b.timeMs || a.id - b.id);
|
||||
let eventIndex = 0;
|
||||
const points: EquityPoint[] = [];
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
const shortBorrowFee = (notional: number, openedAtMs: number, nowMs: number): number => {
|
||||
const heldDays = Math.max(0, nowMs - openedAtMs) / DAY_MS;
|
||||
return notional * (shortRate / 100) * (heldDays / 365);
|
||||
};
|
||||
|
||||
const markToMarket = (price: number, nowMs: number): number => {
|
||||
const longValue = longPosition ? longPosition.qty * price : 0;
|
||||
const shortValue = shortPosition
|
||||
? shortPosition.entryNotional - shortPosition.qty * price - shortBorrowFee(shortPosition.entryNotional, shortPosition.openedAtMs, nowMs)
|
||||
: 0;
|
||||
return cash + longValue + shortValue;
|
||||
};
|
||||
|
||||
for (const candle of candles) {
|
||||
const candleMs = new Date(candle.time).getTime();
|
||||
const price = candle.close;
|
||||
while (eventIndex < sortedEvents.length && sortedEvents[eventIndex].timeMs <= candleMs) {
|
||||
const event = sortedEvents[eventIndex];
|
||||
const equityBefore = markToMarket(price, candleMs);
|
||||
if (event.side === 'long' && event.action === 'open' && !longPosition && longPct > 0) {
|
||||
const notional = equityBefore * (longPct / 100);
|
||||
const qty = notional > 0 ? notional / price : 0;
|
||||
const fee = notional * feePct;
|
||||
cash -= notional + fee;
|
||||
longPosition = { qty, entryPrice: price, entryNotional: notional, openedAtMs: candleMs };
|
||||
} else if (event.side === 'long' && event.action === 'close' && longPosition) {
|
||||
const proceeds = longPosition.qty * price;
|
||||
const fee = proceeds * feePct;
|
||||
cash += proceeds - fee;
|
||||
longPosition = null;
|
||||
} else if (event.side === 'short' && event.action === 'open' && !shortPosition && shortPct > 0) {
|
||||
const notional = equityBefore * (shortPct / 100);
|
||||
const qty = notional > 0 ? notional / price : 0;
|
||||
const fee = notional * feePct;
|
||||
cash += notional - fee;
|
||||
shortPosition = { qty, entryPrice: price, entryNotional: notional, openedAtMs: candleMs };
|
||||
} else if (event.side === 'short' && event.action === 'close' && shortPosition) {
|
||||
const coverCost = shortPosition.qty * price;
|
||||
const fee = coverCost * feePct;
|
||||
const borrow = shortBorrowFee(shortPosition.entryNotional, shortPosition.openedAtMs, candleMs);
|
||||
cash -= coverCost + fee + borrow;
|
||||
shortPosition = null;
|
||||
}
|
||||
eventIndex += 1;
|
||||
}
|
||||
points.push({ time: candleMs, value: markToMarket(price, candleMs) });
|
||||
}
|
||||
|
||||
const last = candles.at(-1);
|
||||
const snapshotEquity = last ? markToMarket(last.close, new Date(last.time).getTime()) : Number(store.initialDeposit);
|
||||
return { equityPoints: points, snapshot: { cash, equity: snapshotEquity, longPosition, shortPosition } };
|
||||
}
|
||||
|
||||
function downsample(points: EquityPoint[], buckets = 1200): EquityPoint[] {
|
||||
if (points.length <= buckets * 2) return points;
|
||||
const out: EquityPoint[] = [];
|
||||
const bucketSize = points.length / buckets;
|
||||
for (let b = 0; b < buckets; b += 1) {
|
||||
const start = Math.floor(b * bucketSize);
|
||||
const end = Math.min(points.length, Math.floor((b + 1) * bucketSize));
|
||||
if (end <= start) continue;
|
||||
let minIdx = start;
|
||||
let maxIdx = start;
|
||||
for (let i = start; i < end; i += 1) {
|
||||
if (points[i].value < points[minIdx].value) minIdx = i;
|
||||
if (points[i].value > points[maxIdx].value) maxIdx = i;
|
||||
}
|
||||
const picks = [...new Set([start, minIdx, maxIdx, end - 1])].sort((a, b) => a - b);
|
||||
for (const idx of picks) out.push(points[idx]);
|
||||
}
|
||||
if (out.length === 0 || out.at(-1)!.time !== points.at(-1)!.time) out.push(points.at(-1)!);
|
||||
return out;
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
createChartIfNeeded();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
clearRangeLoadTimer();
|
||||
resizeObserver?.disconnect();
|
||||
chart?.destroy();
|
||||
});
|
||||
|
||||
watch(() => store.replayCandles, render, { deep: true });
|
||||
watch(() => store.navigatorVersion, render);
|
||||
watch(() => store.tradeEvents, render, { deep: true });
|
||||
watch(() => store.btResult, render, { deep: true });
|
||||
watch([() => store.initialDeposit, () => store.longAllocationPct, () => store.shortAllocationPct, () => store.shortRateAnnualPct, () => store.brokerCommissionPct], render);
|
||||
|
||||
// Окно сдвинули в пределах загруженных данных (данные не менялись — другие watch
|
||||
// молчат): перерисовываем эквити/индикаторы под новое окно с debounce, чтобы
|
||||
// не ронять производительность при активном перетаскивании.
|
||||
watch(
|
||||
() => [store.fromTime, store.toTime],
|
||||
() => {
|
||||
if (windowMoveTimer != null) window.clearTimeout(windowMoveTimer);
|
||||
windowMoveTimer = window.setTimeout(() => {
|
||||
windowMoveTimer = null;
|
||||
render();
|
||||
}, 200);
|
||||
},
|
||||
);
|
||||
|
||||
// Цепочка довыгрузки: если во время загрузки пользователь перетащил окно дальше,
|
||||
// новая позиция могла не покрыться. После завершения каждой загрузки перепроверяем
|
||||
// покрытие; scheduleWindowLoad сам выйдет, если данные уже на месте.
|
||||
watch(
|
||||
() => store.isLoadingCandles,
|
||||
(loading, wasLoading) => {
|
||||
if (wasLoading && !loading) scheduleWindowLoad();
|
||||
},
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="chartRoot" class="chart"></div>
|
||||
</template>
|
||||
Reference in new issue
Block a user