init: Market Assistant — этап 1 (позиции: FIFO-средняя, цена безубытка, ступеньки, маркеры ордеров) + этап 2 (отношения инструментов: лаг-корреляция)

This commit is contained in:
workD12 committed 2026-09-29 19:38:40 +03:00
commit 0af45d2902
46 files changed
+8105

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Market Assistant</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+1187
View File
File diff suppressed because it is too large. Load diff
+23
View File
@@ -0,0 +1,23 @@
{
"name": "market-assistant-frontend",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"highcharts": "^13.0.2",
"vue": "^3.5.40"
},
"devDependencies": {
"@types/node": "^24.13.3",
"@vitejs/plugin-vue": "^6.0.8",
"@vue/tsconfig": "^0.9.1",
"typescript": "~6.0.2",
"vite": "^8.2.0",
"vue-tsc": "^3.3.8"
}
}
+54
View File
@@ -0,0 +1,54 @@
<script setup lang="ts">
/**
* Каркас приложения: только шапка с вкладками и футер.
* Содержимое — во вкладках: «Позиции» (этап 1) и «Отношения
* инструментов» (этап 2). KeepAlive сохраняет состояние вкладок.
*/
import { onMounted, ref } from 'vue';
import { fetchHealth } from './api';
import PositionsTab from './components/PositionsTab.vue';
import RelationsTab from './components/RelationsTab.vue';
type Tab = 'positions' | 'relations';
const activeTab = ref<Tab>('positions');
const sandbox = ref(false);
const noToken = ref(false);
onMounted(async () => {
try {
const h = await fetchHealth();
sandbox.value = h.sandbox;
noToken.value = !h.token;
} catch {
// недоступность /api/health не блокируем — вкладки покажут свои ошибки
}
});
</script>
<template>
<div class="wrap">
<header>
<h1>Market Assistant<span v-if="sandbox" class="badge">sandbox</span></h1>
<nav class="tabs">
<button :class="{ on: activeTab === 'positions' }" @click="activeTab = 'positions'">
Позиции
</button>
<button :class="{ on: activeTab === 'relations' }" @click="activeTab = 'relations'">
Отношения инструментов
</button>
</nav>
</header>
<p v-if="noToken" class="error">TINKOFF_TOKEN не задан в .env — данные недоступны</p>
<KeepAlive>
<component :is="activeTab === 'positions' ? PositionsTab : RelationsTab" />
</KeepAlive>
<footer class="muted footer">
Этап 1: средняя цена позиции · Этап 2: отношение инструментов (сдвинутая
корреляция) · данные: T-Invest API
</footer>
</div>
</template>
+171
View File
@@ -0,0 +1,171 @@
/**
* Типы и вызовы REST backend (/api/*). Прокси настроен в vite.config.ts,
* поэтому здесь просто относительные пути.
*/
export interface AccountInfo {
id: string;
name: string;
type: string;
status: string;
}
export interface PositionRow {
figi: string;
ticker: string | null;
name: string | null;
lot: number | null;
currency: string | null;
/** Число инструментов в позиции, шт. */
qty: number;
/** Средняя по FIFO — основная, совпадает с показом брокера (averagePositionPrice). */
avgPriceFifo: number;
/** Взвешенная средняя (продажи не меняют) — справочно. */
avgPriceWeighted: number;
/** Накопленный реализованный P&L позиции с последнего сброса (по FIFO), руб. */
realizedPnl: number;
/** «Безубыток»: цена, при которой весь заход (включая реализованные сделки) выйдет в ноль. */
breakeven: number;
/** Последняя цена рынка (может отсутствовать). */
currentPrice: number | null;
/** P&L позиции: (last - avg) * qty. */
pnlAbs: number | null;
/** P&L позиции, %: (last / avg - 1) * 100. */
pnlPct: number | null;
operationsCount: number;
firstOperationAt: string | null;
lastOperationAt: string | null;
/** История сделок позиции: ступеньки средней/безубытка и маркеры на графике. */
history: TradeHistoryEntry[];
}
export interface TradeHistoryEntry {
timeMs: number;
type: 'buy' | 'sell';
price: number;
qtyTrade: number;
/** Позиция после сделки; 0 — закрыта в ноль (линия рвётся). */
qty: number;
avgPriceFifo: number | null;
breakeven: number | null;
}
export interface PositionsResponse {
account: { id: string; name: string; type: string; status: string } | null;
positions: PositionRow[];
note?: string;
}
export interface Candle {
time: string;
open: number;
high: number;
low: number;
close: number;
volume: number;
}
export type ChartInterval = '1m' | '5m' | '15m' | '1h' | '1d';
export interface CandlesResponse {
figi: string;
interval: ChartInterval;
candles: Candle[];
}
async function getJson<T>(url: string): Promise<T> {
const res = await fetch(url);
const body: unknown = await res.json().catch(() => null);
if (!res.ok) {
const message =
body !== null &&
typeof body === 'object' &&
'error' in body &&
typeof (body as { error: unknown }).error === 'string'
? (body as { error: string }).error
: `HTTP ${res.status}`;
throw new Error(message);
}
return body as T;
}
export function fetchAccounts(): Promise<{ sandbox: boolean; accounts: AccountInfo[] }> {
return getJson('/api/accounts');
}
export function fetchPositions(accountId?: string): Promise<PositionsResponse> {
const q = accountId ? `?accountId=${encodeURIComponent(accountId)}` : '';
return getJson(`/api/positions${q}`);
}
export function fetchCandles(
figi: string,
interval: ChartInterval,
days: number,
): Promise<CandlesResponse> {
const q = new URLSearchParams({ figi, interval, days: String(days) });
return getJson(`/api/candles?${q.toString()}`);
}
// ---------- Общие / этап 2 ----------
export interface HealthResponse {
status: string;
sandbox: boolean;
token: boolean;
}
export interface InstrumentInfo {
figi: string;
ticker: string;
name: string;
}
export interface LagCorr {
lag: number;
corr: number | null;
}
export interface NormPoint {
time: string;
/** Изменение от точки старта, %. */
value: number;
}
export interface RelationsResponse {
figiA: string;
figiB: string;
interval: ChartInterval;
days: number;
ok: boolean;
message?: string;
points: number;
maxLag: number;
pearson: number | null;
bestLag: number | null;
bestCorr: number | null;
leader: 'A' | 'B' | null;
lags: LagCorr[];
seriesA: NormPoint[];
seriesB: NormPoint[];
seriesBShifted: NormPoint[] | null;
}
export function fetchHealth(): Promise<HealthResponse> {
return getJson('/api/health');
}
export function fetchInstruments(): Promise<{ instruments: InstrumentInfo[] }> {
return getJson('/api/instruments');
}
export function fetchRelations(
figiA: string,
figiB: string,
interval: ChartInterval,
days: number,
): Promise<RelationsResponse> {
const q = new URLSearchParams({ figiA, figiB, interval, days: String(days) });
return getJson(`/api/relations?${q.toString()}`);
}
+221
View File
@@ -0,0 +1,221 @@
<script setup lang="ts">
/**
* Вкладка «Позиции» (этап 1): открытые позиции со средней ценой и P&L,
* график цены выбранного инструмента с линией средней.
* Работает внутри KeepAlive в App.vue — таймер останавливается,
* когда вкладка не активна.
*/
import {
computed,
onActivated,
onDeactivated,
onMounted,
onUnmounted,
ref,
watch,
} from 'vue';
import {
fetchAccounts,
fetchCandles,
fetchPositions,
type AccountInfo,
type Candle,
type ChartInterval,
type PositionRow,
} from '../api';
import PriceChart from './PriceChart.vue';
/** Автообновление позиций (текущая цена / P&L), мс. */
const REFRESH_MS = 20000;
const INTERVALS: Array<{ value: ChartInterval; label: string; days: number }> = [
{ value: '1d', label: 'Д', days: 365 },
{ value: '1h', label: 'Ч', days: 30 },
{ value: '15m', label: '15м', days: 7 },
];
const accounts = ref<AccountInfo[]>([]);
const accountId = ref('');
const positions = ref<PositionRow[]>([]);
const selectedFigi = ref<string | null>(null);
const interval = ref<ChartInterval>('1d');
const candles = ref<Candle[]>([]);
const error = ref('');
const loading = ref(false);
const updatedAt = ref('');
let timer: ReturnType<typeof setInterval> | undefined;
const selected = computed(
() => positions.value.find((p) => p.figi === selectedFigi.value) ?? null,
);
const sortedPositions = computed(
() => [...positions.value].sort((a, b) => (b.pnlPct ?? 0) - (a.pnlPct ?? 0)),
);
function fmt(v: number | null, digits = 2): string {
return v === null ? '—' : v.toLocaleString('ru-RU', { maximumFractionDigits: digits });
}
function fmtSigned(v: number | null, digits = 2): string {
return v === null ? '—' : `${v > 0 ? '+' : ''}${fmt(v, digits)}`;
}
function pnlClass(v: number | null): string {
return v === null ? '' : v > 0 ? 'pos' : v < 0 ? 'neg' : '';
}
async function loadAccounts(): Promise<void> {
const data = await fetchAccounts();
accounts.value = data.accounts;
if (!accountId.value && data.accounts[0]) accountId.value = data.accounts[0].id;
}
async function loadPositions(): Promise<void> {
loading.value = true;
try {
const data = await fetchPositions(accountId.value || undefined);
positions.value = data.positions;
updatedAt.value = new Date().toLocaleTimeString('ru-RU');
if (selectedFigi.value === null || !data.positions.some((p) => p.figi === selectedFigi.value)) {
selectedFigi.value = data.positions[0]?.figi ?? null;
}
error.value = '';
} catch (e) {
error.value = e instanceof Error ? e.message : String(e);
} finally {
loading.value = false;
}
}
/** Защита от гонки при быстром переключении тикера/интервала. */
let candleReq = 0;
async function loadCandles(): Promise<void> {
const figi = selectedFigi.value;
if (!figi) {
candles.value = [];
return;
}
const req = ++candleReq;
try {
const days = INTERVALS.find((i) => i.value === interval.value)?.days ?? 365;
const data = await fetchCandles(figi, interval.value, days);
if (req === candleReq) candles.value = data.candles;
} catch (e) {
if (req === candleReq) error.value = e instanceof Error ? e.message : String(e);
}
}
function ensureTimer(): void {
if (!timer) timer = setInterval(loadPositions, REFRESH_MS);
}
function stopTimer(): void {
if (timer) clearInterval(timer);
timer = undefined;
}
onMounted(async () => {
try {
await loadAccounts();
} catch (e) {
error.value = e instanceof Error ? e.message : String(e);
}
await loadPositions();
ensureTimer();
});
// KeepAlive: автообновление только пока вкладка видима
onActivated(ensureTimer);
onDeactivated(stopTimer);
onUnmounted(stopTimer);
watch([selectedFigi, interval], () => void loadCandles());
</script>
<template>
<div>
<div class="controls tab-head">
<select v-model="accountId" @change="loadPositions">
<option v-for="a in accounts" :key="a.id" :value="a.id">
{{ a.name || a.id }} ({{ a.type }})
</option>
</select>
<button :disabled="loading" @click="loadPositions">
{{ loading ? 'Обновляю…' : 'Обновить' }}
</button>
<span v-if="updatedAt" class="muted">обновлено {{ updatedAt }}</span>
</div>
<p v-if="error" class="error">{{ error }}</p>
<section v-if="positions.length" class="table-wrap">
<table>
<thead>
<tr>
<th>Тикер</th>
<th>Инструмент</th>
<th class="num">Кол-во</th>
<th class="num">Средняя цена</th>
<th class="num">Цена безубытка</th>
<th class="num">Текущая</th>
<th class="num">P&amp;L</th>
<th class="num">P&amp;L %</th>
</tr>
</thead>
<tbody>
<tr
v-for="p in sortedPositions"
:key="p.figi"
:class="{ active: p.figi === selectedFigi }"
@click="selectedFigi = p.figi"
>
<td class="ticker">{{ p.ticker ?? p.figi }}</td>
<td class="name">{{ p.name ?? '' }}</td>
<td class="num">{{ fmt(p.qty, 0) }}</td>
<td class="num">{{ fmt(p.avgPriceFifo) }}</td>
<td class="num">{{ fmt(p.breakeven) }}</td>
<td class="num">{{ fmt(p.currentPrice) }}</td>
<td class="num" :class="pnlClass(p.pnlAbs)">{{ fmtSigned(p.pnlAbs) }}</td>
<td class="num" :class="pnlClass(p.pnlPct)">{{ fmtSigned(p.pnlPct) }}</td>
</tr>
</tbody>
</table>
</section>
<p v-else-if="!error" class="muted empty">
Открытых позиций нет (закрытые в ноль не показываются). Для sandbox-токена можно
создать тестовые сделки: <code>cd backend &amp;&amp; npm run sandbox-demo</code>
</p>
<section v-if="selected" class="chart-block">
<div class="chart-head">
<h2>{{ selected.ticker ?? selected.figi }} — {{ selected.name ?? '' }}</h2>
<div class="intervals">
<button
v-for="i in INTERVALS"
:key="i.value"
:class="{ on: interval === i.value }"
@click="interval = i.value"
>
{{ i.label }}
</button>
</div>
</div>
<PriceChart
:candles="candles"
:avg-price="selected.avgPriceFifo"
:breakeven="selected.breakeven"
:current-price="selected.currentPrice"
:history="selected.history"
:ticker="selected.ticker ?? selected.figi"
/>
<p class="muted">
Средняя цена: {{ fmt(selected.avgPriceFifo) }} · Цена безубытка: {{
fmt(selected.breakeven)
}}{{ selected.currency === 'rub' ? ' ₽' : '' }} ·
сделок в расчёте: {{ selected.operationsCount }} · последняя сделка:
{{
selected.lastOperationAt
? new Date(selected.lastOperationAt).toLocaleString('ru-RU')
: '—'
}}
</p>
</section>
</div>
</template>
+290
View File
@@ -0,0 +1,290 @@
<script setup lang="ts">
/**
* Свечной график цены инструмента + горизонтальная линия средней цены позиции
* и пунктирная линия текущей цены. Highcharts/Highstock, тёмная тема —
* паттерн из legacy/StockChart.vue (masters-импорты).
*/
import Highcharts from 'highcharts/es-modules/masters/highstock.src.js';
import 'highcharts/es-modules/masters/modules/accessibility.src.js';
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
import type { Candle, TradeHistoryEntry } from '../api';
const props = defineProps<{
candles: Candle[];
/** Средняя цена позиции — горизонтальная линия. */
avgPrice: number | null;
/** Цена безубытка — вторая горизонтальная линия. */
breakeven?: number | null;
/** История сделок: ступеньки средней/безубытка + маркеры buy/sell. */
history?: TradeHistoryEntry[];
/** Последняя цена рынка — пунктирная линия. */
currentPrice: number | null;
ticker: string;
}>();
const root = ref<HTMLDivElement | null>(null);
let chart: Highcharts.Chart | null = null;
let observer: ResizeObserver | null = null;
function toOhlc(candles: Candle[]): Array<[number, number, number, number, number]> {
return candles
.map((c): [number, number, number, number, number] | null => {
const t = Date.parse(c.time);
return Number.isFinite(t) ? [t, c.open, c.high, c.low, c.close] : null;
})
.filter((p): p is [number, number, number, number, number] => p !== null)
.sort((a, b) => a[0] - b[0]);
}
function buildPlotLines(): Highcharts.YAxisPlotLinesOptions[] {
const lines: Highcharts.YAxisPlotLinesOptions[] = [];
if (!hasHistory() && props.avgPrice !== null) {
lines.push({
value: props.avgPrice,
color: '#f0b429',
width: 1.5,
dashStyle: 'Dash',
zIndex: 5,
label: {
text: `средняя ${props.avgPrice.toFixed(2)}`,
style: { color: '#f0b429', fontSize: '11px' },
},
});
}
if (!hasHistory() && props.breakeven !== undefined && props.breakeven !== null) {
lines.push({
value: props.breakeven,
color: '#3fd2c7',
width: 1.5,
dashStyle: 'LongDash',
zIndex: 5,
label: {
text: `безубыток ${props.breakeven.toFixed(2)}`,
style: { color: '#3fd2c7', fontSize: '11px' },
},
});
}
if (props.currentPrice !== null) {
lines.push({
value: props.currentPrice,
color: '#4f8fd9',
width: 1,
dashStyle: 'Dot',
zIndex: 4,
label: {
text: props.currentPrice.toFixed(2),
style: { color: '#4f8fd9', fontSize: '11px' },
},
});
}
return lines;
}
function hasHistory(): boolean {
return (props.history?.length ?? 0) > 0;
}
/** Серии: свечи + ступеньки средней/безубытка + маркеры buy/sell. */
function buildSeries(): Highcharts.SeriesOptionsType[] {
const list: Highcharts.SeriesOptionsType[] = [
{
type: 'candlestick',
id: 'candles',
name: props.ticker,
color: '#f85149',
upColor: '#3fb950',
data: [],
} as Highcharts.SeriesCandlestickOptions,
];
if (!hasHistory()) return list;
list.push({
type: 'line',
id: 'avg',
name: 'средняя',
color: '#f0b429',
lineWidth: 1.5,
dashStyle: 'Dash',
step: 'right',
marker: { enabled: false },
data: [],
} as Highcharts.SeriesLineOptions);
list.push({
type: 'line',
id: 'be',
name: 'безубыток',
color: '#3fd2c7',
lineWidth: 1.5,
dashStyle: 'LongDash',
step: 'right',
marker: { enabled: false },
data: [],
} as Highcharts.SeriesLineOptions);
list.push({
type: 'scatter',
id: 'buys',
name: 'buy',
color: '#3fb950',
marker: {
symbol: 'triangle',
fillColor: '#3fb950',
radius: 7,
lineColor: 'transparent',
},
data: [],
} as Highcharts.SeriesScatterOptions);
list.push({
type: 'scatter',
id: 'sells',
name: 'sell',
color: '#f85149',
marker: {
symbol: 'triangle-down',
fillColor: '#f85149',
radius: 7,
lineColor: 'transparent',
},
data: [],
} as Highcharts.SeriesScatterOptions);
return list;
}
/** Данные серий по id: свечи, ступеньки, маркеры. */
function dataSets(): Record<string, Highcharts.PointOptionsType[]> {
const sets: Record<string, Highcharts.PointOptionsType[]> = {
candles: toOhlc(props.candles),
};
const h = props.history;
if (h === undefined || h.length === 0) return sets;
const avg: Highcharts.PointOptionsType[] = [];
const be: Highcharts.PointOptionsType[] = [];
const buys: Highcharts.PointOptionsType[] = [];
const sells: Highcharts.PointOptionsType[] = [];
let lastAvg: number | null = null;
let lastBe: number | null = null;
for (const e of h) {
avg.push([e.timeMs, e.avgPriceFifo] as unknown as Highcharts.PointOptionsType);
be.push([e.timeMs, e.breakeven] as unknown as Highcharts.PointOptionsType);
if (e.type === 'buy') {
buys.push([e.timeMs, e.price] as unknown as Highcharts.PointOptionsType);
} else {
sells.push([e.timeMs, e.price] as unknown as Highcharts.PointOptionsType);
}
if (e.avgPriceFifo !== null) lastAvg = e.avgPriceFifo;
if (e.breakeven !== null) lastBe = e.breakeven;
}
// продлить последнюю ступеньку до правого края (актуальные значения)
const now = Date.now();
if (lastAvg !== null) avg.push([now, lastAvg] as unknown as Highcharts.PointOptionsType);
if (lastBe !== null) be.push([now, lastBe] as unknown as Highcharts.PointOptionsType);
sets.avg = avg;
sets.be = be;
sets.buys = buys;
sets.sells = sells;
return sets;
}
function baseOptions(): Highcharts.Options {
return {
chart: { backgroundColor: '#0f1724', height: 540, animation: false },
credits: { enabled: false },
title: { text: undefined },
legend: {
enabled: hasHistory(),
itemStyle: { color: '#b6c2d9', fontSize: '11px' },
},
rangeSelector: { enabled: false },
scrollbar: { enabled: false },
// «Карта по времени»: навигатор под графиком, границы двигаются мышью
// (стили — из legacy/StockChart.vue старого проекта)
navigator: {
enabled: true,
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' },
},
xAxis: {
type: 'datetime',
labels: { style: { color: '#8e9db8', fontSize: '10px' } },
gridLineColor: 'rgba(148, 163, 184, 0.08)',
},
yAxis: {
labels: { style: { color: '#8e9db8', fontSize: '10px' } },
gridLineColor: 'rgba(148, 163, 184, 0.08)',
plotLines: buildPlotLines(),
},
tooltip: {
backgroundColor: 'rgba(15, 23, 36, 0.95)',
style: { color: '#d3deef' },
borderColor: 'rgba(148, 163, 184, 0.25)',
borderRadius: 8,
shadow: false,
},
series: buildSeries(),
};
}
function render(): void {
chart?.destroy();
if (!root.value) return;
chart = Highcharts.stockChart(root.value, baseOptions());
update();
}
/** Обновление без пересоздания графика: свечи + линии средняя/текущая. */
function update(): void {
if (!chart) return;
const sets = dataSets();
for (const s of chart.series) {
const id = s.options.id;
if (id === undefined) continue;
const data = sets[id];
if (data !== undefined) s.setData(data, false);
}
chart.yAxis[0]?.update({ plotLines: buildPlotLines() } as Highcharts.YAxisOptions, false);
chart.redraw();
}
onMounted(() => {
render();
if (root.value) {
observer = new ResizeObserver(() => chart?.reflow());
observer.observe(root.value);
}
});
onBeforeUnmount(() => {
observer?.disconnect();
observer = null;
chart?.destroy();
chart = null;
});
watch(
() => [props.candles, props.avgPrice, props.breakeven, props.currentPrice, props.history],
() => (chart ? update() : render()),
);
</script>
<template>
<div ref="root" class="chart"></div>
</template>
<style scoped>
.chart {
width: 100%;
min-height: 320px;
}
</style>
+152
View File
@@ -0,0 +1,152 @@
<script lang="ts">
/** Типы графика отношений (используются и во вкладке RelationsTab). */
export interface ChartPoint {
x: number | string;
y: number | null;
color?: string;
}
export interface ChartSeriesSpec {
name: string;
kind: 'line' | 'column';
color?: string;
dashStyle?: 'Solid' | 'Dash' | 'Dot';
points: ChartPoint[];
}
</script>
<script setup lang="ts">
/**
* Универсальный мини-график для вкладки отношений: линии по datetime
* (относительное движение) или колонки по категориям (корреляция по лагам).
* Highcharts/Highstock, тёмная тема — паттерн PriceChart.vue.
*/
import Highcharts from 'highcharts/es-modules/masters/highstock.src.js';
import 'highcharts/es-modules/masters/modules/accessibility.src.js';
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
const props = withDefaults(
defineProps<{
series: ChartSeriesSpec[];
isDatetime?: boolean;
yTitle?: string;
height?: number;
/** «Карта по времени» — Highstock-навигатор с передвигаемыми границами. */
navigator?: boolean;
}>(),
{ isDatetime: true, yTitle: '', height: 420, navigator: false },
);
const root = ref<HTMLDivElement | null>(null);
let chart: Highcharts.Chart | null = null;
let observer: ResizeObserver | null = null;
function toSeries(s: ChartSeriesSpec): Highcharts.SeriesOptionsType {
const data = s.points.map((p) =>
p.color === undefined
? ([p.x, p.y] as unknown as Highcharts.PointOptionsType)
: ({ x: p.x, y: p.y, color: p.color } as unknown as Highcharts.PointOptionsType),
);
if (s.kind === 'column') {
return { type: 'column', name: s.name, color: s.color, data } as Highcharts.SeriesOptionsType;
}
return {
type: 'line',
name: s.name,
color: s.color,
dashStyle: s.dashStyle ?? 'Solid',
data,
} as Highcharts.SeriesOptionsType;
}
function render(): void {
chart?.destroy();
if (!root.value) return;
chart = Highcharts.stockChart(root.value, {
chart: { backgroundColor: '#0f1724', height: props.height, animation: false },
credits: { enabled: false },
title: { text: undefined },
legend: {
enabled: props.series.length > 1,
itemStyle: { color: '#b6c2d9', fontSize: '11px' },
},
rangeSelector: { enabled: false },
scrollbar: { enabled: false },
navigator: props.navigator
? ({
enabled: true,
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: 'line', lineWidth: 1, color: '#4f8fd9', fillOpacity: 0.1 },
} as Highcharts.NavigatorOptions)
: { enabled: false },
xAxis: {
type: props.isDatetime ? 'datetime' : 'category',
labels: { style: { color: '#8e9db8', fontSize: '10px' } },
gridLineColor: 'rgba(148, 163, 184, 0.08)',
},
yAxis: {
title: props.yTitle ? { text: props.yTitle, style: { color: '#8e9db8' } } : undefined,
labels: { style: { color: '#8e9db8', fontSize: '10px' } },
gridLineColor: 'rgba(148, 163, 184, 0.08)',
// нулевая линия полезна на баровом графике лагов
plotLines: props.isDatetime
? undefined
: [{ value: 0, color: 'rgba(148, 163, 184, 0.4)', width: 1, zIndex: 3 }],
},
tooltip: {
backgroundColor: 'rgba(15, 23, 36, 0.95)',
style: { color: '#d3deef' },
borderColor: 'rgba(148, 163, 184, 0.25)',
borderRadius: 8,
shadow: false,
},
series: props.series.map(toSeries),
});
}
onMounted(() => {
render();
if (root.value) {
observer = new ResizeObserver(() => chart?.reflow());
observer.observe(root.value);
}
});
onBeforeUnmount(() => {
observer?.disconnect();
observer = null;
chart?.destroy();
chart = null;
});
watch(
() => props.series,
render,
{ deep: true },
);
</script>
<template>
<div ref="root" class="chart"></div>
</template>
<style scoped>
.chart {
width: 100%;
min-height: 220px;
}
</style>
+249
View File
@@ -0,0 +1,249 @@
<script setup lang="ts">
/**
* Вкладка «Отношения инструментов» (этап 2): сдвинутая корреляция —
* есть ли связь «кто раньше» и с каким лагом.
*/
import { computed, onMounted, ref, watch } from 'vue';
import {
fetchInstruments,
fetchRelations,
type ChartInterval,
type InstrumentInfo,
type RelationsResponse,
} from '../api';
import RelationChart, { type ChartSeriesSpec } from './RelationChart.vue';
const WINDOWS: Array<{ value: ChartInterval; label: string; days: number }> = [
{ value: '1d', label: 'Д (год)', days: 365 },
{ value: '1h', label: 'Ч (30 дн)', days: 30 },
{ value: '15m', label: '15м (7 дн)', days: 7 },
{ value: '5m', label: '5м (3 дн)', days: 3 },
];
const instruments = ref<InstrumentInfo[]>([]);
const figiA = ref('');
const figiB = ref('');
const interval = ref<ChartInterval>('1d');
const loading = ref(false);
const error = ref('');
const result = ref<RelationsResponse | null>(null);
function tickerOf(figi: string): string {
return instruments.value.find((i) => i.figi === figi)?.ticker ?? figi;
}
function figiByTicker(ticker: string): string {
return instruments.value.find((i) => i.ticker === ticker)?.figi ?? '';
}
// ---------- Последний выбор пары (localStorage) ----------
const STORAGE_KEY = 'ma:relations';
interface SavedSelection {
figiA: string;
figiB: string;
interval: ChartInterval;
}
/** Сохранить выбранную пару и окно — вернуться к ним при следующем заходе. */
function persist(): void {
try {
const data: SavedSelection = {
figiA: figiA.value,
figiB: figiB.value,
interval: interval.value,
};
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
} catch {
// localStorage недоступен (приватный режим и т.п.) — молча пропускаем
}
}
/** Прочитать сохранённый выбор; null — если его нет или он повреждён. */
function restore(): SavedSelection | null {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as Partial<SavedSelection>;
if (typeof parsed.figiA !== 'string' || typeof parsed.figiB !== 'string') return null;
const known: ChartInterval[] = ['1d', '1h', '15m', '5m'];
const savedInterval = known.find((v) => v === parsed.interval) ?? '1d';
return { figiA: parsed.figiA, figiB: parsed.figiB, interval: savedInterval };
} catch {
return null;
}
}
async function compute(): Promise<void> {
if (!figiA.value || !figiB.value) return;
if (figiA.value === figiB.value) {
error.value = 'Выберите два разных инструмента';
return;
}
loading.value = true;
try {
const days = WINDOWS.find((w) => w.value === interval.value)?.days ?? 365;
result.value = await fetchRelations(figiA.value, figiB.value, interval.value, days);
error.value = '';
} catch (e) {
error.value = e instanceof Error ? e.message : String(e);
} finally {
loading.value = false;
}
}
watch([figiA, figiB, interval], () => {
persist();
void compute();
});
onMounted(async () => {
try {
const data = await fetchInstruments();
instruments.value = data.instruments;
// Прошлый выбор, если инструменты всё ещё существуют в справочнике
const saved = restore();
const exists = (figi: string): boolean =>
instruments.value.some((i) => i.figi === figi);
if (saved && exists(saved.figiA) && exists(saved.figiB) && saved.figiA !== saved.figiB) {
figiA.value = saved.figiA;
figiB.value = saved.figiB;
interval.value = saved.interval;
} else {
if (!figiA.value) figiA.value = figiByTicker('SBER');
if (!figiB.value) figiB.value = figiByTicker('LKOH');
}
await compute();
} catch (e) {
error.value = e instanceof Error ? e.message : String(e);
}
});
/** Итоговый вывод: кто кого опережает (или движутся синхронно). */
const verdict = computed<string>(() => {
const r = result.value;
if (!r) return '';
if (!r.ok) return r.message ?? 'Недостаточно данных';
if (r.bestLag === null || r.bestCorr === null) {
return 'Недостаточно данных для оценки сдвига — возьмите более длинное окно';
}
const fmt = (v: number): string => v.toFixed(2);
if (r.leader === null) {
return `Синхронное движение: максимум корреляции при lag=0 (corr=${fmt(r.bestCorr)}) — значимого лидера нет`;
}
const lead = r.leader === 'A' ? tickerOf(r.figiA) : tickerOf(r.figiB);
const follow = r.leader === 'A' ? tickerOf(r.figiB) : tickerOf(r.figiA);
return (
`${lead} движется РАНЬШЕ ${follow} примерно на ${Math.abs(r.bestLag)} шаг(ов) ` +
`(corr=${fmt(r.bestCorr)} против ${r.pearson === null ? '—' : fmt(r.pearson)} без сдвига)`
);
});
const stepWord = computed<string>(() => {
if (interval.value === '1d') return 'дней';
if (interval.value === '1h') return 'часов';
return interval.value === '5m' ? 'шагов 5м' : 'шагов 15м';
});
/** График 1: относительное движение (0% в точке старта) + сдвинутая кривая B. */
const moveSeries = computed<ChartSeriesSpec[]>(() => {
const r = result.value;
if (!r || !r.ok) return [];
const pts = (arr: Array<{ time: string; value: number }>) =>
arr.map((p) => ({ x: Date.parse(p.time), y: p.value }));
const series: ChartSeriesSpec[] = [
{ name: tickerOf(r.figiA), kind: 'line', color: '#4f8fd9', points: pts(r.seriesA) },
{ name: tickerOf(r.figiB), kind: 'line', color: '#f0b429', points: pts(r.seriesB) },
];
if (r.seriesBShifted && r.bestLag !== null && r.bestLag !== 0) {
series.push({
name: `${tickerOf(r.figiB)} (сдв. ${r.bestLag})`,
kind: 'line',
color: '#3fd2c7',
dashStyle: 'Dash',
points: pts(r.seriesBShifted),
});
}
return series;
});
/** График 2: корреляция по лагам; лучший лаг выделен янтарным. */
const corrSeries = computed<ChartSeriesSpec[]>(() => {
const r = result.value;
if (!r || !r.ok) return [];
return [
{
name: 'corr',
kind: 'column',
points: r.lags.map((l) => ({
x: String(l.lag),
y: l.corr,
color:
r.bestLag === l.lag
? '#f0b429'
: l.corr !== null && l.corr >= 0
? 'rgba(63, 185, 80, 0.55)'
: 'rgba(248, 81, 73, 0.55)',
})),
},
];
});
</script>
<template>
<div>
<div class="controls tab-head">
<select v-model="figiA">
<option v-for="i in instruments" :key="i.figi" :value="i.figi">{{ i.ticker }}</option>
</select>
<span class="muted">против</span>
<select v-model="figiB">
<option v-for="i in instruments" :key="i.figi" :value="i.figi">{{ i.ticker }}</option>
</select>
<div class="intervals">
<button
v-for="w in WINDOWS"
:key="w.value"
:class="{ on: interval === w.value }"
@click="interval = w.value"
>
{{ w.label }}
</button>
</div>
<button :disabled="loading" @click="compute()">
{{ loading ? 'Считаю…' : 'Пересчитать' }}
</button>
</div>
<p v-if="error" class="error">{{ error }}</p>
<template v-if="result && result.ok">
<p class="verdict">{{ verdict }}</p>
<section class="chart-block">
<h2>Относительное движение, % от точки старта</h2>
<RelationChart
:series="moveSeries"
:is-datetime="true"
y-title="%"
:navigator="true"
:height="480"
/>
<p v-if="result.seriesBShifted" class="muted">
Бирюзовый пунктир — {{ tickerOf(result.figiB) }}, сдвинутая на лучший лаг
({{ result.bestLag }}) для наложения на {{ tickerOf(result.figiA) }}.
</p>
</section>
<section class="chart-block">
<h2>Корреляция по сдвигам ({{ stepWord }})</h2>
<RelationChart :series="corrSeries" :is-datetime="false" y-title="corr" :height="300" />
<p class="muted">
Положительный лаг: первый инструмент опережает второй. Янтарным — лучший лаг.
Общих свечей: {{ result.points }}.
</p>
</section>
</template>
<p v-else-if="!error" class="muted empty">{{ verdict }}</p>
</div>
</template>
+5
View File
@@ -0,0 +1,5 @@
import { createApp } from 'vue';
import App from './App.vue';
import './style.css';
createApp(App).mount('#app');
+50
View File
@@ -0,0 +1,50 @@
/* Market Assistant — базовая тёмная тема (в духе графиков из legacy/StockChart.vue). */
:root { color-scheme: dark; }
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; }
body {
background: #0b1220;
color: #d3deef;
font-family: 'IBM Plex Sans', 'Segoe UI', system-ui, sans-serif;
font-size: 14px;
}
.wrap { max-width: 1100px; margin: 0 auto; padding: 20px; }
header { display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 18px; }
h1 { font-size: 20px; margin: 0; font-weight: 600; }
h2 { font-size: 15px; margin: 0; font-weight: 600; }
.badge { font-size: 11px; background: #3a2f10; color: #f0b429; border: 1px solid #6b5514; padding: 1px 7px; border-radius: 10px; vertical-align: middle; margin-left: 8px; }
.controls { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.muted { color: #8e9db8; }
.error { color: #f85149; margin: 0 0 12px; }
button { background: #1c2a42; color: #d3deef; border: 1px solid #2d4266; border-radius: 6px; padding: 6px 12px; cursor: pointer; font: inherit; }
button:hover { background: #26375a; }
button:disabled { opacity: 0.5; cursor: default; }
select { background: #1c2a42; color: #d3deef; border: 1px solid #2d4266; border-radius: 6px; padding: 6px 8px; font: inherit; }
code { background: #16233a; padding: 1px 5px; border-radius: 4px; }
.table-wrap { overflow-x: auto; margin-bottom: 22px; border: 1px solid #1d2c47; border-radius: 10px; }
table { width: 100%; border-collapse: collapse; }
th { text-align: left; color: #8e9db8; font-weight: 500; font-size: 12px; padding: 9px 12px; border-bottom: 1px solid #1d2c47; white-space: nowrap; }
th.num { text-align: right; }
td { padding: 9px 12px; border-bottom: 1px solid #16233a; white-space: nowrap; }
tbody tr { cursor: pointer; }
tbody tr:hover { background: #131f36; }
tbody tr.active { background: #1a2a4a; }
td.ticker { font-weight: 600; }
td.name { color: #8e9db8; max-width: 260px; overflow: hidden; text-overflow: ellipsis; }
.num { text-align: right; font-variant-numeric: tabular-nums; }
.pos { color: #3fb950; }
.neg { color: #f85149; }
.chart-block { border: 1px solid #1d2c47; border-radius: 10px; padding: 14px; }
.chart-head { display: flex; justify-content: space-between; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 10px; }
.intervals { display: flex; gap: 6px; }
.intervals button.on { background: #2d4266; border-color: #4f8fd9; }
.empty { margin: 30px 0; }
/* Вкладки и общий каркас (этап 2) */
.tabs { display: flex; gap: 6px; flex-wrap: wrap; }
.tabs button { padding: 7px 14px; }
.tabs button.on { background: #2d4266; border-color: #4f8fd9; }
.tab-head { margin-bottom: 14px; }
.footer { margin-top: 28px; padding-top: 12px; border-top: 1px solid #1d2c47; font-size: 12px; }
.verdict { font-size: 15px; margin: 0 0 14px; }
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["src/**/*", "src/**/*.vue"],
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"types": ["vite/client"]
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+9
View File
@@ -0,0 +1,9 @@
{
"include": ["vite.config.ts"],
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"module": "ESNext",
"moduleResolution": "Bundler",
"types": ["node"]
}
}
+15
View File
@@ -0,0 +1,15 @@
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
// Dev-сервер (:5173) с прокси /api -> backend Fastify (:8000), без CORS.
// host 127.0.0.1 — явно (иначе vite v8 биндится только на IPv6 ::1).
export default defineConfig({
plugins: [vue()],
server: {
host: '127.0.0.1',
port: 5173,
proxy: {
'/api': { target: 'http://127.0.0.1:8000' },
},
},
});