看股功能更新

This commit is contained in:
2026-08-15 15:36:11 +08:00
parent c1c43d2ff7
commit 9cce670b74
26 changed files with 957 additions and 427 deletions

View File

@@ -1,13 +1,38 @@
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { dispose, init, registerIndicator, type Chart, type KLineData } from 'klinecharts';
import { useSettingsStore } from '@/stores/settings';
import type { Candle } from '@/api/types';
import {
dispose, init, registerIndicator, registerOverlay,
type Chart, type KLineData, type Point,
} from 'klinecharts';
// 官方画线扩展preview.klinecharts.com 同款工具集rect/circle 沿用 v10 内置版,不注册扩展的重名模板
import {
abcd, anyWaves, arrow, eightWaves, fibonacciCircle, fibonacciExtension, fibonacciSegment,
fibonacciSpeedResistanceFan, fibonacciSpiral, fiveWaves, gannBox, measure, parallelogram,
threeWaves, triangle, xabcd,
} from '@klinecharts/extension';
import { useSettingsStore, TOOLTIP_FIELDS, DEFAULT_TOOLTIP_FIELDS } from '@/stores/settings';
import type { Candle, TooltipField } from '@/api/types';
// 扩展画线模板一次性全局注册registerOverlay 是全局的,模块加载时执行一次即可)
for (const t of [
abcd, xabcd, threeWaves, fiveWaves, eightWaves, anyWaves, arrow, triangle, parallelogram,
fibonacciCircle, fibonacciExtension, fibonacciSegment, fibonacciSpeedResistanceFan,
fibonacciSpiral, gannBox, measure,
]) {
registerOverlay(t);
}
const props = defineProps<{
ticker: string;
candles: Candle[];
indicators: Record<string, Record<string, (number | null)[]>>;
/** 服务端在首屏窗口之前是否还有更早历史(决定左滑是否继续翻页) */
hasMore: boolean;
/** 向左翻页:取某日期(不含)之前 count 根历史,父组件保证口径一致;返回 null 表示无更多/已失效 */
loadOlder: (
end: string,
count: number,
) => Promise<{ candles: Candle[]; indicators: Record<string, Record<string, (number | null)[]>>; hasMore: boolean } | null>;
/** 副图指标及顺序('vol' 用内置;其余为后端序列) */
subPanes: string[];
/** 主图 MA 周期(可配置,随用户偏好持久化) */
@@ -18,17 +43,35 @@ const props = defineProps<{
showBoll: boolean;
/** K线周期标签仅用于 MA 指标名缓存 key */
timeframe: string;
/** 浮层显示的指标(可选;缺省=目录全开,空数组=仅日期头) */
tooltipFields?: TooltipField[];
}>();
// A股语义色浅色UP/DOWN 跟随设置中的涨跌配色
// A股语义色黑底高对比UP/DOWN 跟随设置中的涨跌配色
const settings = useSettingsStore();
let UP = '#dc2626';
let DOWN = '#16a34a';
const MA_COLORS = ['#2563eb', '#f59e0b', '#a855f7', '#10b981', '#ec4899', '#0ea5e9', '#84cc16', '#f97316'];
let UP = '#FE354B';
let DOWN = '#1EBE72';
const MA_COLORS = ['#F5C518', '#4DA3FF', '#C77DFF', '#4DD0E1', '#FF8A3D', '#FF6E9C', '#A3E635', '#94A8FF'];
// ---------- 后端序列注入(单一事实源,按索引对齐) ----------
// ---------- 后端序列注入(单一事实源,与 allData 按索引对齐) ----------
// allData 会随向左翻页不断前插,图表只持有其中的后缀窗口——指标取值必须按时间戳
// 定位到 allData 索引,绝不能用图表相对索引(否则翻页后整体错位)。
let PV: Record<string, (number | null)[]> = {};
const g = (k: string) => (i: number) => PV[k]?.[i] ?? undefined;
let allData: KLineData[] = [];
function idxOfTs(ts: number): number {
let lo = 0, hi = allData.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (allData[mid].timestamp === ts) return mid;
if (allData[mid].timestamp < ts) lo = mid + 1; else hi = mid - 1;
}
return -1;
}
const g = (k: string) => (ts: number) => {
const i = idxOfTs(ts);
return i >= 0 ? PV[k]?.[i] ?? undefined : undefined;
};
// 动态 MA按周期组合注册一次figures 的 key 必须静态,故按签名建缓存)
const _maReg = new Set<string>();
@@ -42,9 +85,9 @@ function ensureMaIndicator(periods: number[]) {
key: `ma${p}`, title: `MA${p}`, type: 'line',
styles: () => ({ color: MA_COLORS[i % MA_COLORS.length] }),
})),
calc: (d: KLineData[]) => d.map((_, i) => {
calc: (d: KLineData[]) => d.map((bar) => {
const row: Record<string, number | undefined> = {};
for (const p of periods) row[`ma${p}`] = g(`ma${p}`)(i);
for (const p of periods) row[`ma${p}`] = g(`ma${p}`)(bar.timestamp);
return row;
}),
});
@@ -56,19 +99,19 @@ registerIndicator({
name: 'pv-boll',
shortName: 'BOLL',
figures: [
{ key: 'upper', title: 'UP', type: 'line', styles: () => ({ color: '#a855f7' }) },
{ key: 'mid', title: 'MB', type: 'line', styles: () => ({ color: '#f59e0b' }) },
{ key: 'lower', title: 'DN', type: 'line', styles: () => ({ color: '#a855f7' }) },
{ key: 'upper', title: 'UP', type: 'line', styles: () => ({ color: '#C77DFF' }) },
{ key: 'mid', title: 'MB', type: 'line', styles: () => ({ color: '#F5C518' }) },
{ key: 'lower', title: 'DN', type: 'line', styles: () => ({ color: '#C77DFF' }) },
],
calc: (d: KLineData[]) => d.map((_, i) => ({ upper: g('upper')(i), mid: g('mid')(i), lower: g('lower')(i) })),
calc: (d: KLineData[]) => d.map((bar) => ({ upper: g('upper')(bar.timestamp), mid: g('mid')(bar.timestamp), lower: g('lower')(bar.timestamp) })),
});
registerIndicator({
name: 'pv-macd',
shortName: 'MACD',
figures: [
{ key: 'dif', title: 'DIF', type: 'line', styles: () => ({ color: '#2563eb' }) },
{ key: 'dea', title: 'DEA', type: 'line', styles: () => ({ color: '#f59e0b' }) },
{ key: 'dif', title: 'DIF', type: 'line', styles: () => ({ color: '#4DA3FF' }) },
{ key: 'dea', title: 'DEA', type: 'line', styles: () => ({ color: '#F5C518' }) },
{
key: 'hist', title: 'HIST', type: 'bar', baseValue: 0, // 零轴柱,缺省会从面板底部画起
styles: (p) => {
@@ -77,42 +120,115 @@ registerIndicator({
},
},
],
calc: (d: KLineData[]) => d.map((_, i) => ({ dif: g('dif')(i), dea: g('dea')(i), hist: g('hist')(i) })),
calc: (d: KLineData[]) => d.map((bar) => ({ dif: g('dif')(bar.timestamp), dea: g('dea')(bar.timestamp), hist: g('hist')(bar.timestamp) })),
});
registerIndicator({
name: 'pv-kdj',
shortName: 'KDJ',
figures: [
{ key: 'k', title: 'K', type: 'line', styles: () => ({ color: '#2563eb' }) },
{ key: 'd', title: 'D', type: 'line', styles: () => ({ color: '#f59e0b' }) },
{ key: 'j', title: 'J', type: 'line', styles: () => ({ color: '#dc2626' }) },
{ key: 'k', title: 'K', type: 'line', styles: () => ({ color: '#4DA3FF' }) },
{ key: 'd', title: 'D', type: 'line', styles: () => ({ color: '#F5C518' }) },
{ key: 'j', title: 'J', type: 'line', styles: () => ({ color: '#FF6E9C' }) },
],
calc: (d: KLineData[]) => d.map((_, i) => ({ k: g('k')(i), d: g('d')(i), j: g('j')(i) })),
calc: (d: KLineData[]) => d.map((bar) => ({ k: g('k')(bar.timestamp), d: g('d')(bar.timestamp), j: g('j')(bar.timestamp) })),
});
registerIndicator({
name: 'pv-rsi',
shortName: 'RSI',
figures: [
{ key: 'rsi6', title: 'RSI6', type: 'line', styles: () => ({ color: '#2563eb' }) },
{ key: 'rsi12', title: 'RSI12', type: 'line', styles: () => ({ color: '#f59e0b' }) },
{ key: 'rsi24', title: 'RSI24', type: 'line', styles: () => ({ color: '#a855f7' }) },
{ key: 'rsi6', title: 'RSI6', type: 'line', styles: () => ({ color: '#4DA3FF' }) },
{ key: 'rsi12', title: 'RSI12', type: 'line', styles: () => ({ color: '#F5C518' }) },
{ key: 'rsi24', title: 'RSI24', type: 'line', styles: () => ({ color: '#C77DFF' }) },
],
calc: (d: KLineData[]) => d.map((_, i) => ({ rsi6: g('rsi6')(i), rsi12: g('rsi12')(i), rsi24: g('rsi24')(i) })),
calc: (d: KLineData[]) => d.map((bar) => ({ rsi6: g('rsi6')(bar.timestamp), rsi12: g('rsi12')(bar.timestamp), rsi24: g('rsi24')(bar.timestamp) })),
});
const container = ref<HTMLDivElement | null>(null);
let chart: Chart | null = null;
let allData: KLineData[] = [];
let served = 0; // 已交给图表的 bar 数从尾部计backward 分页用
const INIT_BARS = 240; // 初始展示根数(约一年日线)
const PAGE_BARS = 500; // 每次向左滚动追加的历史根数
// ---------- 向左滚动按需加载(首屏 INIT_BARS 根,滚到左缘自动向前翻页 + 预取缓冲) ----------
const INIT_BARS = 240; // 初始展示根数(约一年日线)
const SERVE_BARS = 500; // 每次 backward 回调向图表吐出的根数
const FETCH_BARS = 800; // 每次网络翻页拉取的根数(后端含预热计算指标)
const PREFETCH_LEFT = 300; // 本地未吐出的剩余根数低于该值时提前预取下一页
function lightStyles() {
let served = 0; // 已交给图表的 bar 数(从尾部计)
let hasMore = false; // 服务端可能还有更早历史
let fetching: Promise<void> | null = null; // 进行中的向前翻页请求
let epoch = 0; // 本轮 build 生命周期标记(重建后丢弃过期回调/数据)
let failCount = 0; // 连续翻页失败次数(超过 3 次才放弃,避免瞬时网络错误永久截断历史)
const canBack = () => allData.length > served || hasMore;
/** 用本地时区把 timestamp 格式化为 YYYY-MM-DDDB 里是 naive 日期toISOString 会因 UTC 偏移提前一天,导致翻页缺一根)。 */
const toDateStr = (ms: number) => {
const d = new Date(ms);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
};
/** 拉取下一页更早历史并前插到 allData / PV索引保持对齐。 */
async function ensureOlder(myEpoch: number): Promise<void> {
if (fetching) return fetching;
if (!hasMore || allData.length === 0) return Promise.resolve();
const end = toDateStr(allData[0].timestamp);
const p = (async () => {
try {
const page = await props.loadOlder(end, FETCH_BARS);
if (myEpoch !== epoch) return; // 期间已切股/切口径/重建,丢弃
if (!page || page.candles.length === 0) { hasMore = false; return; }
recordExtra(page.candles); // 额/换手随翻页累积EX 全局 Map重建时清
const firstTs = allData[0].timestamp;
const keep = page.candles.filter((c) => new Date(c.ts).getTime() < firstTs);
// 同戳边界K周/月K的窗口边界可能切出半周期用服务端完整聚合替换本端首根
const boundary = page.candles.find((c) => new Date(c.ts).getTime() === firstTs);
if (keep.length === 0 && !boundary) { hasMore = false; return; } // 防御:服务端窗口与本端重叠
const head = keep.map((k) => ({
timestamp: new Date(k.ts).getTime(),
open: k.open, high: k.high, low: k.low, close: k.close, volume: k.volume,
}));
allData = boundary
? [...head, { timestamp: firstTs, open: boundary.open, high: boundary.high, low: boundary.low, close: boundary.close, volume: boundary.volume }, ...allData.slice(1)]
: [...head, ...allData];
for (const series of Object.values(page.indicators)) {
for (const [key, arr] of Object.entries(series)) {
// keep 是 page.candles 的前缀(全页严格早于 firstTs指标按前缀对齐
const cut = arr.slice(0, keep.length);
if (boundary) {
const rep = arr[keep.length] ?? null; // 同戳边界K的指标值keep 之后紧邻一根)
PV[key] = [...cut, rep, ...(PV[key] ?? []).slice(1)];
} else {
PV[key] = [...cut, ...(PV[key] ?? [])];
}
}
}
// 注klinecharts v10 数据只经 dataLoader 流入、无 updateData
// 已渲染的半周期首K无法原地刷新替换 allData/PV 保证后续翻页与重建使用完整聚合。
hasMore = page.hasMore;
failCount = 0;
} catch {
// 网络失败:保留 hasMore下次左缘触发时重试连续 3 次失败才放弃
failCount += 1;
if (failCount >= 3) hasMore = false;
}
})();
fetching = p.finally(() => { fetching = null; });
return fetching;
}
/** 缓冲预取:本地剩余不足时提前拉下一页,用户滚到左缘时数据已就位、零等待。 */
function maybePrefetch(myEpoch: number) {
if (hasMore && !fetching && allData.length - served < PREFETCH_LEFT) void ensureOlder(myEpoch);
}
function darkStyles() {
return {
grid: { horizontal: { color: '#eef2f7' }, vertical: { color: '#eef2f7' } },
grid: { horizontal: { color: '#1C1E24' }, vertical: { color: '#1C1E24' } },
// 内建 VOL 等指标柱的涨跌色缺省是库默认绿涨红跌,与全站语义相反;
// bars[0] 与库默认项深合并init 时 merge 到 getDefaultStyles只覆盖三个颜色键
// UP/DOWN 在 build() 里随 settings 刷新,故切「绿涨红跌」重建后同样生效
indicator: { bars: [{ upColor: UP, downColor: DOWN, noChangeColor: '#7A818C' }] },
candle: {
bar: {
upColor: UP, downColor: DOWN,
@@ -120,17 +236,17 @@ function lightStyles() {
upWickColor: UP, downWickColor: DOWN,
},
priceMark: {
high: { color: '#94a3b8' }, low: { color: '#94a3b8' },
high: { color: '#9AA0AA' }, low: { color: '#9AA0AA' },
last: { upColor: UP, downColor: DOWN },
},
},
xAxis: { axisLine: { color: '#e2e8f0' }, tickText: { color: '#64748b' }, tickLine: { color: '#e2e8f0' } },
yAxis: { axisLine: { color: '#e2e8f0' }, tickText: { color: '#64748b' }, tickLine: { color: '#e2e8f0' } },
xAxis: { axisLine: { color: '#2A2D34' }, tickText: { color: '#9AA0AA', size: 12 }, tickLine: { color: '#2A2D34' } },
yAxis: { axisLine: { color: '#2A2D34' }, tickText: { color: '#9AA0AA', size: 12 }, tickLine: { color: '#2A2D34' } },
crosshair: {
horizontal: { text: { backgroundColor: '#1e293b' } },
vertical: { text: { backgroundColor: '#1e293b' } },
horizontal: { text: { backgroundColor: '#333A45' } },
vertical: { text: { backgroundColor: '#333A45' } },
},
separator: { color: '#e2e8f0' },
separator: { color: '#23252B' },
};
}
@@ -138,63 +254,173 @@ function lightStyles() {
const SUB_DEFAULT_HEIGHT: Record<string, number> = { vol: 64, macd: 100, kdj: 96, rsi: 84 };
const subH = (k: string) => Math.max(40, props.subHeights[k] ?? SUB_DEFAULT_HEIGHT[k] ?? 90);
// ---------- 鼠标跟随信息框(通达信式) ----------
// ---------- 鼠标跟随信息框(通达信式,浮层贴鼠标,每行一个指标 ----------
interface TipRow { key: string; label: string; text: string; tone: '' | 'up' | 'down' }
interface HoverInfo {
date: string; open: number; high: number; low: number; close: number;
chg: number | null; amp: number | null; vol: string; amount: string | null;
mas: { label: string; value: number | null; color: string }[];
date: string; weekday: string;
rows: TipRow[];
}
const hover = ref<HoverInfo | null>(null);
// tooltip 展示的额/换手不在 KLineData 里,按时间戳从 Candle 源数据另存一份
const EX = new Map<number, { amount: number | null; turnover: number | null }>();
const recordExtra = (candles: Candle[]) => {
for (const c of candles) EX.set(new Date(c.ts).getTime(), { amount: c.amount ?? null, turnover: c.turnover ?? null });
};
const WEEKDAYS = ['日', '一', '二', '三', '四', '五', '六'];
function fmtVol(v: number): string {
if (v >= 1e8) return (v / 1e8).toFixed(2) + '亿';
if (v >= 1e4) return (v / 1e4).toFixed(2) + '万';
return String(Math.round(v));
}
function fmtAmount(v: number): string {
if (v >= 1e8) return (v / 1e8).toFixed(2) + '亿';
if (v >= 1e4) return (v / 1e4).toFixed(2) + '万';
return v.toFixed(0);
}
// 鼠标位置(相对图表容器),浮层跟着走并在右缘/下缘自动翻转
const mx = ref(0);
const my = ref(0);
function onMove(e: MouseEvent) {
const rect = container.value?.getBoundingClientRect();
mx.value = rect ? e.clientX - rect.left : e.clientX;
my.value = rect ? e.clientY - rect.top : e.clientY;
}
const hoverStyle = ref<Record<string, string>>({});
function placeHover(rowCount: number) {
const w = container.value?.clientWidth ?? 800;
const h = container.value?.clientHeight ?? 500;
// 空选时模板仍渲染一行“未选择指标”占位,按至少 1 行估高
const bw = 160, bh = 37 + Math.max(rowCount, 1) * 16, gap = 14;
const x = mx.value + gap + bw > w - 4 ? Math.max(4, mx.value - gap - bw) : mx.value + gap;
const y = my.value + gap + bh > h - 4 ? Math.max(4, my.value - gap - bh) : my.value + gap;
hoverStyle.value = { left: `${x}px`, top: `${y}px` };
}
function bindCrosshair(ch: Chart) {
ch.subscribeAction('onCrosshairChange', (payload) => {
const k = (payload as { data?: { kLineData?: KLineData } }).data?.kLineData;
if (!k || !allData.length) { hover.value = null; return; }
// 二分定位索引(全量数组与指标序列按索引对齐)
let lo = 0, hi = allData.length - 1, idx = -1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (allData[mid].timestamp === k.timestamp) { idx = mid; break; }
if (allData[mid].timestamp < k.timestamp) lo = mid + 1; else hi = mid - 1;
}
// v10 分发的是裸 crosshair {x, y, paneId}(不含 kLineData
// 用公共 API 把 x 像素换算回 timestamp 再定位 bar
const x = (payload as { x?: number }).x;
if (typeof x !== 'number' || allData.length === 0) { hover.value = null; return; }
const pt = ch.convertFromPixel([{ x }]) as Array<Partial<Point>>;
const ts = pt?.[0]?.timestamp;
const idx = ts != null ? idxOfTs(ts) : -1; // 全量数组与指标序列按索引对齐
if (idx < 0) { hover.value = null; return; }
const k = allData[idx];
const prev = idx > 0 ? allData[idx - 1] : null;
const chg = prev ? ((k.close - prev.close) / prev.close) * 100 : null;
const diff = prev ? k.close - prev.close : null;
const chg = prev ? (diff! / prev.close) * 100 : null;
const amp = prev ? ((k.high - k.low) / prev.close) * 100 : null;
hover.value = {
date: new Date(k.timestamp).toLocaleDateString('zh-CN'),
open: k.open, high: k.high, low: k.low, close: k.close,
chg, amp, vol: fmtVol(k.volume ?? 0), amount: null,
mas: props.maPeriods.map((p, i) => ({
label: `MA${p}`,
value: PV[`ma${p}`]?.[idx] ?? null,
color: MA_COLORS[i % MA_COLORS.length],
})),
const d = new Date(k.timestamp);
const ex = EX.get(k.timestamp);
// 每个指标一行配色跟随涨跌色调设置up/down 在 build() 里随 priceTone 刷新)。
// 平盘diff==0为中性色与全站 pctClass 及 klinecharts 的 noChangeColor 三态约定一致
const byDiff: '' | 'up' | 'down' = diff == null || diff === 0 ? '' : diff > 0 ? 'up' : 'down';
const values: Record<TooltipField, { text: string; tone: '' | 'up' | 'down' }> = {
open: { text: k.open.toFixed(2), tone: byDiff },
high: { text: k.high.toFixed(2), tone: 'up' },
low: { text: k.low.toFixed(2), tone: 'down' },
close: { text: k.close.toFixed(2), tone: byDiff },
diff: { text: diff == null ? '—' : (diff > 0 ? '+' : '') + diff.toFixed(2), tone: byDiff },
chg: { text: chg == null ? '—' : (chg > 0 ? '+' : '') + chg.toFixed(2) + '%', tone: byDiff },
amp: { text: amp == null ? '—' : amp.toFixed(2) + '%', tone: '' },
vol: { text: fmtVol(k.volume ?? 0), tone: '' },
amount: { text: ex?.amount != null ? fmtAmount(ex.amount) : '—', tone: '' },
turnover: { text: ex?.turnover == null ? '—' : ex.turnover.toFixed(2) + '%', tone: '' },
};
const selected = new Set(props.tooltipFields ?? DEFAULT_TOOLTIP_FIELDS);
const rows: TipRow[] = TOOLTIP_FIELDS
.filter((f) => selected.has(f.key)) // 目录顺序 = 设置弹层顺序 = 浮层行序
.map((f) => ({ key: f.key, label: f.label, ...values[f.key] }));
hover.value = {
date: `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`,
weekday: `星期${WEEKDAYS[d.getDay()]}`,
rows,
};
placeHover(rows.length);
});
}
// ---------- 画图画线(通达信式工具栏 ----------
const TOOLS: { key: string; label: string; title: string }[] = [
// ---------- 画图画线(Pro 风格工具集v10 内置 + @klinecharts/extension ----------
interface Tool { key: string; label: string; title: string }
// 常用工具工具栏一行直出key 即 overlay 名,'' 表示光标模式)
const COMMON_TOOLS: Tool[] = [
{ key: '', label: '光标', title: '光标模式Esc 取消画线)' },
{ key: 'segment', label: '', title: '线段' },
{ key: 'ray', label: '→', title: '射线' },
{ key: 'horizontalLine', label: '─', title: '水平线' },
{ key: 'rayLine', label: '→', title: '射线' },
{ key: 'horizontalStraightLine', label: '─', title: '水平线' },
{ key: 'rect', label: '▭', title: '矩形' },
{ key: 'priceChannelLine', label: '∥', title: '价格通道' },
{ key: 'fibLine', label: 'fib', title: '斐波那契回撤' },
{ key: 'fibonacciLine', label: 'fib', title: '斐波那契回撤' },
{ key: 'measure', label: '⇹', title: '测量(价差/幅度/K线数' },
];
// 更多工具(分组面板展开;均为已注册 overlay
const MORE_GROUPS: { group: string; items: Tool[] }[] = [
{ group: '线', items: [
{ key: 'straightLine', label: '直线', title: '无限延长直线' },
{ key: 'horizontalSegment', label: '水平线段', title: '两点水平线段' },
{ key: 'verticalStraightLine', label: '竖直线', title: '竖直直线' },
{ key: 'parallelStraightLine', label: '平行线', title: '平行直线' },
{ key: 'priceLine', label: '价格线', title: '单点价格线' },
] },
{ group: '斐波那契', items: [
{ key: 'fibonacciSegment', label: '线段fib', title: '斐波那契线段(周期)' },
{ key: 'fibonacciExtension', label: '扩展', title: '斐波那契扩展' },
{ key: 'fibonacciCircle', label: '圆形', title: '斐波那契圆形' },
{ key: 'fibonacciSpiral', label: '螺线', title: '斐波那契螺线' },
{ key: 'fibonacciSpeedResistanceFan', label: '阻力扇', title: '斐波那契速度阻力扇' },
] },
{ group: '波浪 · 江恩 · 谐波', items: [
{ key: 'threeWaves', label: '三浪', title: '三浪' },
{ key: 'fiveWaves', label: '五浪', title: '五浪' },
{ key: 'eightWaves', label: '八浪', title: '八浪' },
{ key: 'anyWaves', label: '自由浪', title: '自由波浪' },
{ key: 'gannBox', label: '江恩箱', title: '甘氏箱(江恩角度线)' },
{ key: 'abcd', label: 'AB=CD', title: 'AB=CD 谐波' },
{ key: 'xabcd', label: 'XABCD', title: 'XABCD 谐波' },
] },
{ group: '形状', items: [
{ key: 'triangle', label: '△', title: '三角形' },
{ key: 'parallelogram', label: '▱', title: '平行四边形' },
{ key: 'circle', label: '◯', title: '圆' },
{ key: 'arrow', label: '➤', title: '箭头' },
{ key: 'brush', label: '✎', title: '自由画笔' },
] },
];
const activeTool = ref('');
const showMore = ref(false);
/** 测量工具的气泡文案:价差 / 涨跌幅 / 两点间K线数Point.value 即价格) */
function measureTip(points: Partial<Point>[]): string[] {
const a = points[0], b = points[1];
if (!a?.value || !b?.value) return [];
const diff = b.value - a.value;
const pct = (diff / a.value) * 100;
const out = [
`价差 ${diff >= 0 ? '+' : ''}${diff.toFixed(2)}`,
`幅度 ${pct >= 0 ? '+' : ''}${pct.toFixed(2)}%`,
];
const ia = a.timestamp != null ? idxOfTs(a.timestamp) : -1;
const ib = b.timestamp != null ? idxOfTs(b.timestamp) : -1;
if (ia >= 0 && ib >= 0) out.push(`${Math.abs(ib - ia) + 1} 根K线`);
return out;
}
function pickTool(key: string) {
activeTool.value = key;
if (chart && key) chart.createOverlay({ name: key });
showMore.value = false;
if (chart && key) {
// measure 通过 extendData 注入气泡文案,其余直接按名创建
chart.createOverlay(key === 'measure' ? { name: 'measure', extendData: measureTip } : { name: key });
}
}
function clearOverlays() {
@@ -207,35 +433,67 @@ function build() {
UP = settings.upHex;
DOWN = settings.downHex;
PV = {};
EX.clear();
recordExtra(props.candles);
for (const [group, series] of Object.entries(props.indicators)) {
for (const [key, arr] of Object.entries(series)) PV[key] = arr;
}
const ch = init(container.value, { styles: lightStyles() });
const ch = init(container.value, { styles: darkStyles() });
if (!ch) return;
chart = ch;
const myEpoch = ++epoch;
allData = props.candles.map((k) => ({
timestamp: new Date(k.ts).getTime(),
open: k.open, high: k.high, low: k.low, close: k.close, volume: k.volume,
}));
served = 0;
hasMore = props.hasMore;
fetching = null;
failCount = 0;
ch.setDataLoader({
getBars: ({ type, callback }) => {
if (type === 'update') {
const last = allData[allData.length - 1];
callback(last ? [last] : [], { backward: served < allData.length, forward: false });
} else if (type === 'init') {
// 全量已拉到本地:先给最近 INIT_BARS 根,向左滚动时按页吐更早历史
served = Math.min(INIT_BARS, allData.length);
callback(allData.slice(allData.length - served), { backward: served < allData.length, forward: false });
} else if (type === 'backward') {
const remain = allData.length - served;
const take = Math.min(PAGE_BARS, remain);
if (myEpoch !== epoch) return; // 已重建(切股/切口径/改MA旧图表已 dispose无需应答
// klinecharts v10 契约(见 node_modules/klinecharts/dist/index.esm.js _addData
// 'init' → callback 数据整体替换
// 'forward' → 用户拖到左缘callback 数据【前插】为更旧历史more.forward=false 后左缘不再触发
// 'backward'→ 用户拖到右缘callback 数据【追加】为更新端数据;我们已持有最新一根,永远没有
// 每次 getBars 必须恰好应答一次 callback否则图表 _loading 卡死、后续不再加载
const serveOlder = (take: number) => {
const start = allData.length - served - take;
served += take;
callback(allData.slice(start, start + take), { backward: served < allData.length, forward: false });
callback(allData.slice(start, start + take), { forward: canBack(), backward: false });
};
const answerEmpty = () => callback([], { forward: false, backward: false });
if (type === 'init') {
// 首屏:最近 INIT_BARS 根;更早历史由左滑触发 'forward' 翻页
served = Math.min(INIT_BARS, allData.length);
callback(allData.slice(allData.length - served), { forward: canBack(), backward: false });
maybePrefetch(myEpoch);
} else if (type === 'forward') {
// 左缘:优先吐本地未吐出的(首屏余量或已预取页),本地耗尽再向服务端翻一页更早历史
const step = async () => {
if (allData.length - served > 0) {
serveOlder(Math.min(SERVE_BARS, allData.length - served));
maybePrefetch(myEpoch);
return;
}
if (!hasMore) { answerEmpty(); return; }
await ensureOlder(myEpoch); // 若已在请求中则复用同一 promise
if (myEpoch !== epoch) return; // 期间已重建,由新图表应答
if (allData.length - served > 0) {
serveOlder(Math.min(SERVE_BARS, allData.length - served));
maybePrefetch(myEpoch);
} else {
answerEmpty();
}
};
void step();
} else {
callback([], { backward: false, forward: false });
// 'backward'(右缘更新端)与 'update'(单根刷新走 subscribeBar无更新端数据
// 绝不能把更旧历史从这里给出去——v10 会 concat 到最新一根右侧造成时间轴乱序
callback([], { forward: canBack(), backward: false });
}
},
});
@@ -259,6 +517,12 @@ function build() {
}
bindCrosshair(ch);
// 缓冲预取:可视范围接近已加载左缘(<200 根)时提前翻下一页
ch.subscribeAction('onVisibleRangeChange', (payload) => {
if (myEpoch !== epoch) return;
const from = (payload as { data?: { from?: unknown } }).data?.from;
if (typeof from === 'number' && from < 200) maybePrefetch(myEpoch);
});
ch.setOffsetRightDistance(28);
ch.scrollToRealTime();
}
@@ -290,47 +554,73 @@ watch(() => props.subHeights, () => {
</script>
<template>
<div class="relative h-full w-full">
<!-- mousemove captureklinecharts 在内部容器上以冒泡阶段监听并同步触发
onCrosshairChangeplaceHovercapture 先于它更新 mx/my避免用到上一次的坐标 -->
<div class="relative h-full w-full" @mousemove.capture="onMove" @mouseleave="hover = null">
<div ref="container" class="h-full w-full"></div>
<!-- 鼠标跟随信息框通达信式小方块 -->
<!-- 鼠标跟随信息框贴鼠标/下缘自动翻转每行一个指标内容由浮层设置决定 -->
<div
v-if="hover"
class="pointer-events-none absolute left-2 top-2 z-10 rounded border border-slate-700 bg-slate-900/90 px-2.5 py-1.5 font-mono text-[11px] leading-4 text-slate-200 shadow-lg"
class="pointer-events-none absolute z-10 w-40 rounded border border-[#33353D] bg-black/90 px-2.5 py-1.5 font-mono text-xs leading-4 text-[#E8EAED] shadow-lg"
:style="hoverStyle"
>
<div class="text-slate-400">{{ hover.date }}</div>
<div> <span :class="hover.chg != null && hover.chg >= 0 ? 'text-red-400' : 'text-emerald-400'">{{ hover.open.toFixed(2) }}</span>
<span class="text-red-400">{{ hover.high.toFixed(2) }}</span>
<span class="text-emerald-400">{{ hover.low.toFixed(2) }}</span>
<span :class="hover.chg != null && hover.chg >= 0 ? 'text-red-400' : 'text-emerald-400'">{{ hover.close.toFixed(2) }}</span></div>
<div> <span :class="hover.chg != null && hover.chg >= 0 ? 'text-red-400' : 'text-emerald-400'">{{ hover.chg == null ? '—' : (hover.chg > 0 ? '+' : '') + hover.chg.toFixed(2) + '%' }}</span>
<span class="text-slate-100">{{ hover.amp == null ? '—' : hover.amp.toFixed(2) + '%' }}</span>
<span class="text-slate-100">{{ hover.vol }}</span></div>
<div v-if="hover.mas.length" class="mt-0.5">
<span v-for="(m, i) in hover.mas" :key="m.label" class="mr-2" :style="{ color: m.color }">
{{ m.label }} {{ m.value == null ? '' : m.value.toFixed(2) }}<span v-if="i < hover.mas.length - 1" class="invisible">,</span>
</span>
<div class="text-[#9BA3AE]">{{ hover.date }} <span class="text-[#A8AFB8]">{{ hover.weekday }}</span></div>
<div class="mt-1 border-t border-[#33353D]/60 pt-1">
<div v-for="r in hover.rows" :key="r.key" class="flex items-baseline justify-between">
<span class="text-[#A8AFB8]">{{ r.label }}</span>
<span
:style="r.tone ? { color: r.tone === 'up' ? UP : DOWN } : undefined"
:class="r.tone ? '' : 'text-[#E8EAED]'"
>{{ r.text }}</span>
</div>
<div v-if="hover.rows.length === 0" class="text-[#A8AFB8]">未选择指标</div>
</div>
</div>
<!-- 画图画线工具栏 -->
<div class="absolute right-2 top-2 z-10 flex items-center gap-0.5 rounded-md border border-slate-200 bg-white/95 px-1 py-0.5 shadow-sm">
<button
v-for="t in TOOLS"
:key="t.key || 'cursor'"
type="button"
class="min-w-6 rounded px-1 py-0.5 text-[11px] transition-colors"
:class="activeTool === t.key ? 'bg-blue-600 text-white' : 'text-slate-500 hover:bg-slate-100 hover:text-slate-900'"
:title="t.title"
@click="pickTool(t.key)"
>{{ t.label }}</button>
<span class="mx-0.5 h-3 w-px bg-slate-200"></span>
<button
type="button"
class="rounded px-1 py-0.5 text-[11px] text-red-500 transition-colors hover:bg-red-50"
title="清除全部画线"
@click="clearOverlays"
>清除</button>
<!-- 画图画线工具栏常用一行 + 更多分组面板 -->
<div class="absolute right-2 top-2 z-10 rounded-md border border-[#26272E] bg-[#101014] shadow-sm">
<div class="flex items-center gap-0.5 px-1 py-0.5">
<button
v-for="t in COMMON_TOOLS"
:key="t.key || 'cursor'"
type="button"
class="min-w-6 rounded px-1 py-0.5 text-xs transition-colors"
:class="activeTool === t.key ? 'bg-blue-600 text-white' : 'text-[#A8AFB8] hover:bg-[#1E2026] hover:text-[#E8EAED]'"
:title="t.title"
@click="pickTool(t.key)"
>{{ t.label }}</button>
<span class="mx-0.5 h-3 w-px bg-[#26272E]"></span>
<button
type="button"
class="rounded px-1 py-0.5 text-xs transition-colors"
:class="showMore ? 'bg-blue-500/15 text-blue-300' : 'text-[#A8AFB8] hover:bg-[#1E2026] hover:text-[#E8EAED]'"
title="更多画线工具"
@click="showMore = !showMore"
>更多</button>
<button
type="button"
class="rounded px-1 py-0.5 text-xs text-red-500 transition-colors hover:bg-red-500/15"
title="清除全部画线"
@click="clearOverlays"
>清除</button>
</div>
<div v-if="showMore" class="max-w-56 border-t border-[#26272E] px-1.5 py-1">
<div v-for="grp in MORE_GROUPS" :key="grp.group" class="mb-1.5 last:mb-0">
<div class="mb-0.5 text-xs leading-3 text-[#9BA3AE]">{{ grp.group }}</div>
<div class="flex flex-wrap gap-0.5">
<button
v-for="t in grp.items"
:key="t.key"
type="button"
class="rounded px-1.5 py-0.5 text-xs transition-colors"
:class="activeTool === t.key ? 'bg-blue-600 text-white' : 'text-[#A8AFB8] hover:bg-[#1E2026] hover:text-[#E8EAED]'"
:title="t.title"
@click="pickTool(t.key)"
>{{ t.label }}</button>
</div>
</div>
</div>
</div>
</div>
</template>