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,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>
|
||||
Reference in new issue
Block a user