feat: 全屏个股详情预览 + Tailwind 改版 + 账号鉴权

This commit is contained in:
2026-08-14 22:37:18 +08:00
parent 0f8b9a7255
commit 4c2ea5521d
47 changed files with 2937 additions and 893 deletions

View File

@@ -1,10 +1,5 @@
<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import InputText from 'primevue/inputtext';
import InputNumber from 'primevue/inputnumber';
import Select from 'primevue/select';
import ToggleSwitch from 'primevue/toggleswitch';
import Button from 'primevue/button';
import type { BacktestRequest } from '@/api/types';
defineProps<{ loading: boolean }>();
@@ -16,7 +11,19 @@ const STRATS: { id: string; label: string; params: ParamDef[] }[] = [
{ id: 'single_ma', label: '单均线(价格穿越)', params: [{ k: 'period', label: '均线周期', def: 20 }] },
{ id: 'macd_cross', label: 'MACD 金叉死叉', params: [{ k: 'fast', label: '快线', def: 12 }, { k: 'slow', label: '慢线', def: 26 }, { k: 'signal', label: '信号线', def: 9 }] },
];
const stratOptions = STRATS.map((s) => ({ label: s.label, value: s.id }));
const TF_OPTIONS = [
{ label: '日线', value: '1d' },
{ label: '周线', value: '1w' },
{ label: '月线', value: '1M' },
{ label: '年线', value: '1y' },
];
const QUICK = [
{ code: '000001', name: '平安银行' },
{ code: '600519', name: '贵州茅台' },
{ code: '000858', name: '五粮液' },
{ code: '601318', name: '中国平安' },
{ code: 'DEMO', name: '合成数据' },
];
const form = reactive({
symbol: '000001',
@@ -49,42 +56,68 @@ function onRun() {
</script>
<template>
<div class="toolbar">
<div class="field">
<label>策略</label>
<Select v-model="form.strategy" :options="stratOptions" optionLabel="label" optionValue="value" size="small" style="width: 170px" />
</div>
<div class="field" v-for="p in currentParams" :key="p.k">
<label>{{ p.label }}</label>
<InputNumber v-model="form.params[p.k]" :min="1" :max="250" size="small" inputStyle="width:64px" />
</div>
<div class="field">
<label>周期</label>
<Select v-model="form.timeframe" :options="[{label:'日线',value:'1d'},{label:'周线',value:'1w'},{label:'月线',value:'1M'},{label:'年线',value:'1y'}]" optionLabel="label" optionValue="value" size="small" style="width: 100px" />
</div>
<div class="field">
<label>标的</label>
<InputText v-model="form.symbol" size="small" style="width: 110px" placeholder="如 000001" />
</div>
<div class="field">
<label>初始资金</label>
<InputNumber v-model="form.initial_cash" :min="1000" :step="100000" size="small" mode="currency" currency="CNY" inputStyle="width:130px" />
</div>
<div class="field">
<label>fast 模式</label>
<ToggleSwitch v-model="form.fast_mode" />
</div>
<div class="spacer"></div>
<Button label="开始回测" icon="pi pi-play" :loading="loading" size="small" @click="onRun" />
</div>
<div class="rounded-xl border border-slate-200 bg-white p-4">
<div class="flex flex-wrap items-end gap-x-4 gap-y-3">
<div>
<label class="lbl">策略</label>
<select v-model="form.strategy" class="ipt w-40">
<option v-for="s in STRATS" :key="s.id" :value="s.id">{{ s.label }}</option>
</select>
</div>
<div class="quick">
<span class="qlabel">快捷</span>
<button v-for="q in [{code:'000001',name:'平安银行'},{code:'600519',name:'贵州茅台'},{code:'000858',name:'五粮液'},{code:'601318',name:'中国平安'},{code:'DEMO',name:'合成数据'}]" :key="q.code" class="qchip" :class="{ active: form.symbol === q.code }" type="button" @click="form.symbol = q.code">
{{ q.code }} <span class="qname">{{ q.name }}</span>
</button>
</div>
<div class="hint">
策略可选 双均线 / 单均线 / MACD参数随策略自适应<code>DEMO</code> 为合成数据其余为真实 A 首次自动经 Tushare 拉取并缓存
<div v-for="p in currentParams" :key="p.k">
<label class="lbl">{{ p.label }}</label>
<input v-model.number="form.params[p.k]" type="number" min="1" max="250" class="ipt w-[76px]" />
</div>
<div>
<label class="lbl">周期</label>
<select v-model="form.timeframe" class="ipt w-24">
<option v-for="t in TF_OPTIONS" :key="t.value" :value="t.value">{{ t.label }}</option>
</select>
</div>
<div>
<label class="lbl">标的</label>
<input v-model="form.symbol" type="text" class="ipt w-[110px]" placeholder="如 000001" />
</div>
<div>
<label class="lbl">初始资金</label>
<input v-model.number="form.initial_cash" type="number" min="1000" step="100000" class="ipt w-[140px]" />
</div>
<label class="flex cursor-pointer select-none items-center gap-2 pb-1.5 text-sm text-slate-600">
<input v-model="form.fast_mode" type="checkbox" class="h-4 w-4 rounded border-slate-300 accent-blue-600" />
fast 模式
</label>
<div class="ml-auto">
<button type="button" class="btn-primary" :disabled="loading" @click="onRun">
<svg v-if="loading" class="h-4 w-4 animate-spin" viewBox="0 0 24 24" fill="none"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" /><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" /></svg>
<svg v-else class="h-4 w-4" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z" /></svg>
{{ loading ? '回测中…' : '开始回测' }}
</button>
</div>
</div>
<div class="mt-3 flex flex-wrap items-center gap-1.5">
<span class="mr-1 text-xs text-slate-400">快捷</span>
<button
v-for="q in QUICK"
:key="q.code"
type="button"
class="rounded-full border px-3 py-1 text-xs transition-colors"
:class="form.symbol === q.code
? 'border-blue-600 bg-blue-600 text-white'
: 'border-slate-200 bg-slate-50 text-slate-600 hover:border-slate-300 hover:bg-slate-100'"
@click="form.symbol = q.code"
>
{{ q.code }} <span :class="form.symbol === q.code ? 'text-blue-200' : 'text-slate-400'">{{ q.name }}</span>
</button>
</div>
<p class="mt-2 text-xs text-slate-400">
策略可选 双均线 / 单均线 / MACD参数随策略自适应<code class="rounded border border-slate-200 bg-slate-50 px-1">DEMO</code> 为合成数据其余为真实 A 首次自动经 Tushare 拉取并缓存
</p>
</div>
</template>

View File

@@ -5,14 +5,13 @@ defineProps<{ conditions: ScreenConditions }>();
const OP_TEXT: Record<string, string> = { gt: '>', ge: '≥', lt: '<', le: '≤', between: '区间' };
const FIELD_TEXT: Record<string, string> = {
total_mv: '总市值', circ_mv: '流通市值', pe_ttm: '市盈率TTM',
pb: '市净率', turnover_rate: '换手率', close: '最新价',
total_mv: '总市值(亿)', circ_mv: '流通市值(亿)', pe_ttm: '市盈率TTM',
pb: '市净率', turnover_rate: '换手率%', close: '最新价',
};
function paramsStr(p?: Record<string, number>) {
if (!p || Object.keys(p).length === 0) return '';
const vals = Object.values(p).map((v) => (Number.isInteger(v) ? String(v) : String(v)));
return `(${vals.join(',')})`;
return `(${Object.values(p).map((v) => (Number.isInteger(v) ? v : v)).join(',')})`;
}
function lookbackText(c: { lookback?: number; match?: string }) {
@@ -23,28 +22,36 @@ function lookbackText(c: { lookback?: number; match?: string }) {
</script>
<template>
<div class="cond-chips">
<span class="clabel">解析条件</span>
<div class="flex flex-wrap items-center gap-1.5">
<span class="mr-1 text-xs text-slate-400">解析条件</span>
<span v-for="(c, i) in conditions.indicator" :key="'i' + i" class="cond-chip ci">
<i class="pi pi-bolt" style="font-size: 10px;"></i>
<span
v-for="(c, i) in conditions.indicator"
:key="'i' + i"
class="inline-flex items-center gap-1.5 rounded-full border border-blue-200 bg-blue-50 px-3 py-1 text-xs text-blue-900"
>
<span class="h-1.5 w-1.5 rounded-full bg-blue-500"></span>
{{ c.indicator }}{{ paramsStr(c.params) }}
<span class="arrow">{{ OP_TEXT[c.op] }}</span>
<span class="text-blue-400">{{ OP_TEXT[c.op] }}</span>
<template v-if="c.value_indicator">{{ c.value_indicator }}{{ paramsStr(c.value_params) }}</template>
<template v-else-if="c.op === 'between' && c.value2">{{ c.value }} ~ {{ c.value2 }}</template>
<template v-else>{{ c.value }}</template>
<span style="color: var(--ink-3);"> · {{ lookbackText(c) }}</span>
<span class="text-blue-300">· {{ lookbackText(c) }}</span>
</span>
<span v-for="(c, i) in conditions.snapshot" :key="'s' + i" class="cond-chip cs">
<i class="pi pi-table" style="font-size: 10px;"></i>
<span
v-for="(c, i) in conditions.snapshot"
:key="'s' + i"
class="inline-flex items-center gap-1.5 rounded-full border border-amber-200 bg-amber-50 px-3 py-1 text-xs text-amber-900"
>
<span class="h-1.5 w-1.5 rounded-full bg-amber-500"></span>
{{ FIELD_TEXT[c.field] ?? c.field }}
<span class="arrow">{{ OP_TEXT[c.op] }}</span>
<span class="text-amber-400">{{ OP_TEXT[c.op] }}</span>
<template v-if="c.op === 'between' && c.value2">{{ c.value }} ~ {{ c.value2 }}</template>
<template v-else>{{ c.value }}</template>
</span>
<span class="cond-chip cx">
<span class="inline-flex items-center rounded-full border border-slate-200 bg-slate-50 px-3 py-1 text-xs text-slate-400">
排除ST · 退市<span v-if="conditions.exclude_bj"> · 北交所</span>
</span>
</div>

View File

@@ -0,0 +1,180 @@
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { dispose, init, registerIndicator, type Chart, type KLineData } from 'klinecharts';
import type { Candle } from '@/api/types';
const props = defineProps<{
ticker: string;
candles: Candle[];
indicators: Record<string, Record<string, (number | null)[]>>;
/** 副图指标及顺序('vol' 用内置;其余为后端序列) */
subPanes: string[];
/** 主图是否叠加布林带 */
showBoll: boolean;
}>();
// A股语义色浅色
const UP = '#dc2626';
const DOWN = '#16a34a';
const C1 = '#2563eb'; // 蓝
const C2 = '#f59e0b'; // 橙
const C3 = '#a855f7'; // 紫
const C4 = '#10b981'; // 绿青
// ---------- 后端序列注入(单一事实源,按索引对齐) ----------
let PV: Record<string, (number | null)[]> = {};
const g = (k: string) => (i: number) => PV[k]?.[i] ?? undefined;
registerIndicator({
name: 'pv-ma',
shortName: 'MA',
figures: [
{ key: 'ma5', title: 'MA5', type: 'line', styles: () => ({ color: C1 }) },
{ key: 'ma10', title: 'MA10', type: 'line', styles: () => ({ color: C2 }) },
{ key: 'ma20', title: 'MA20', type: 'line', styles: () => ({ color: C3 }) },
{ key: 'ma60', title: 'MA60', type: 'line', styles: () => ({ color: C4 }) },
],
calc: (d: KLineData[]) => d.map((_, i) => ({ ma5: g('ma5')(i), ma10: g('ma10')(i), ma20: g('ma20')(i), ma60: g('ma60')(i) })),
});
registerIndicator({
name: 'pv-boll',
shortName: 'BOLL',
figures: [
{ key: 'upper', title: 'UP', type: 'line', styles: () => ({ color: C3 }) },
{ key: 'mid', title: 'MB', type: 'line', styles: () => ({ color: C2 }) },
{ key: 'lower', title: 'DN', type: 'line', styles: () => ({ color: C3 }) },
],
calc: (d: KLineData[]) => d.map((_, i) => ({ upper: g('upper')(i), mid: g('mid')(i), lower: g('lower')(i) })),
});
registerIndicator({
name: 'pv-macd',
shortName: 'MACD',
figures: [
{ key: 'dif', title: 'DIF', type: 'line', styles: () => ({ color: C1 }) },
{ key: 'dea', title: 'DEA', type: 'line', styles: () => ({ color: C2 }) },
{
key: 'hist', title: 'HIST', type: 'bar', baseValue: 0, // 零轴柱,缺省会从面板底部画起
styles: (p) => {
const v = (p.data.current as { hist?: number } | null)?.hist ?? 0;
return { color: v >= 0 ? UP : DOWN };
},
},
],
calc: (d: KLineData[]) => d.map((_, i) => ({ dif: g('dif')(i), dea: g('dea')(i), hist: g('hist')(i) })),
});
registerIndicator({
name: 'pv-kdj',
shortName: 'KDJ',
figures: [
{ key: 'k', title: 'K', type: 'line', styles: () => ({ color: C1 }) },
{ key: 'd', title: 'D', type: 'line', styles: () => ({ color: C2 }) },
{ key: 'j', title: 'J', type: 'line', styles: () => ({ color: UP }) },
],
calc: (d: KLineData[]) => d.map((_, i) => ({ k: g('k')(i), d: g('d')(i), j: g('j')(i) })),
});
registerIndicator({
name: 'pv-rsi',
shortName: 'RSI',
figures: [
{ key: 'rsi6', title: 'RSI6', type: 'line', styles: () => ({ color: C1 }) },
{ key: 'rsi12', title: 'RSI12', type: 'line', styles: () => ({ color: C2 }) },
{ key: 'rsi24', title: 'RSI24', type: 'line', styles: () => ({ color: C3 }) },
],
calc: (d: KLineData[]) => d.map((_, i) => ({ rsi6: g('rsi6')(i), rsi12: g('rsi12')(i), rsi24: g('rsi24')(i) })),
});
const container = ref<HTMLDivElement | null>(null);
let chart: Chart | null = null;
const LIGHT_STYLES = {
grid: { horizontal: { color: '#eef2f7' }, vertical: { color: '#eef2f7' } },
candle: {
bar: {
upColor: UP, downColor: DOWN,
upBorderColor: UP, downBorderColor: DOWN,
upWickColor: UP, downWickColor: DOWN,
},
priceMark: {
high: { color: '#94a3b8' }, low: { color: '#94a3b8' },
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' } },
crosshair: {
horizontal: { text: { backgroundColor: '#1e293b' } },
vertical: { text: { backgroundColor: '#1e293b' } },
},
separator: { color: '#e2e8f0' },
};
// 副图默认高度
const SUB_HEIGHT: Record<string, number> = { vol: 64, macd: 100, kdj: 96, rsi: 84 };
function build() {
if (!container.value || props.candles.length === 0) return;
PV = {};
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: LIGHT_STYLES });
if (!ch) return;
chart = ch;
const data: KLineData[] = 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,
}));
ch.setDataLoader({
getBars: ({ type, callback }) => {
if (type === 'update') {
const last = data[data.length - 1];
callback(last ? [last] : [], { backward: false, forward: false });
} else if (type === 'init') {
callback(data, { backward: false, forward: false });
} else {
callback([], { backward: false, forward: false });
}
},
});
// v10 要求 symbol+period+dataLoader 三者齐备才触发 'init' 加载,缺一则 getBars 永不调用、图表空白
ch.setSymbol({ ticker: props.ticker });
ch.setPeriod({ type: 'day', span: 1 });
// 主图MA 恒开BOLL 可选
ch.createIndicator({ name: 'pv-ma', paneId: 'candle_pane' });
if (props.showBoll) ch.createIndicator({ name: 'pv-boll', paneId: 'candle_pane' });
// 副图按用户顺序创建,并压矮;主图吃剩余高度
const subHeights = props.subPanes.reduce((s, k) => s + (SUB_HEIGHT[k] ?? 90), 0);
const total = container.value.clientHeight || 560;
ch.setPaneOptions({ id: 'candle_pane', height: Math.max(220, total - subHeights - 24) });
for (const key of props.subPanes) {
if (key === 'vol') ch.createIndicator('VOL');
else ch.createIndicator(`pv-${key}`);
const paneId = ch.getIndicators().find((i) => i.name === (key === 'vol' ? 'VOL' : `pv-${key}`))?.paneId;
if (paneId) ch.setPaneOptions({ id: paneId, height: SUB_HEIGHT[key] ?? 90 });
}
ch.setOffsetRightDistance(28);
ch.scrollToRealTime();
}
function teardown() {
if (container.value) dispose(container.value);
chart = null;
}
onMounted(build);
onBeforeUnmount(teardown);
watch(() => [props.candles, props.indicators, props.subPanes, props.showBoll], () => { teardown(); build(); }, { deep: true });
</script>
<template>
<div ref="container" class="h-full w-full"></div>
</template>

View File

@@ -8,38 +8,41 @@ const props = defineProps<{ equity: EquityPoint[] }>();
const container = ref<HTMLDivElement | null>(null);
let chart: echarts.ECharts | null = null;
const UP = '#dc2626';
const DOWN = '#16a34a';
function buildOption() {
const dates = props.equity.map(p => p.ts.slice(0, 10));
const vals = props.equity.map(p => Number(p.value.toFixed(2)));
const first = vals.length ? vals[0] : 0;
const last = vals.length ? vals[vals.length - 1] : 0;
const lineColor = last >= first ? '#f6465d' : '#0ecb81'; // A股盈利红、亏损绿
const lineColor = last >= first ? UP : DOWN; // A股盈利红、亏损绿
return {
backgroundColor: 'transparent',
grid: { left: 64, right: 18, top: 14, bottom: 26 },
tooltip: {
trigger: 'axis' as const,
backgroundColor: '#1b2230', borderColor: 'rgba(255,255,255,0.1)', borderWidth: 1,
textStyle: { color: '#e6edf3' },
backgroundColor: '#ffffff', borderColor: '#e2e8f0', borderWidth: 1,
textStyle: { color: '#0f172a' },
valueFormatter: (v: number) => (v ?? 0).toLocaleString(undefined, { maximumFractionDigits: 0 }),
},
xAxis: {
type: 'category', data: dates, boundaryGap: false,
axisLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } },
axisLabel: { color: '#5c6675' }, axisTick: { show: false },
axisLine: { lineStyle: { color: '#e2e8f0' } },
axisLabel: { color: '#94a3b8' }, axisTick: { show: false },
},
yAxis: {
type: 'value', scale: true,
splitLine: { lineStyle: { color: 'rgba(255,255,255,0.05)' } },
axisLabel: { color: '#5c6675' },
splitLine: { lineStyle: { color: '#f1f5f9' } },
axisLabel: { color: '#94a3b8' },
},
series: [{
type: 'line', data: vals, symbol: 'none', smooth: false,
lineStyle: { color: lineColor, width: 2 },
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: lineColor + '40' },
{ offset: 0, color: lineColor + '33' },
{ offset: 1, color: lineColor + '00' },
]),
},
@@ -56,5 +59,5 @@ watch(() => props.equity, () => chart?.setOption(buildOption(), true), { deep: t
</script>
<template>
<div ref="container" class="chart-equity"></div>
<div ref="container" class="h-[240px] w-full"></div>
</template>

View File

@@ -1,10 +1,6 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import {
createChart, CandlestickSeries, HistogramSeries, LineSeries,
createSeriesMarkers, CrosshairMode, LineStyle,
type IChartApi, type ISeriesApi, type ISeriesMarkersPluginApi, type SeriesMarker, type Time,
} from 'lightweight-charts';
import { dispose, init, registerIndicator, type Chart, type Crosshair, type KLineData } from 'klinecharts';
import type { Candle, IndicatorOut, SignalOut } from '@/api/types';
const props = defineProps<{
@@ -20,70 +16,114 @@ const TF_LABEL: Record<string, string> = { '1d': '日线', '1w': '周线', '1M':
const STRAT_LABEL: Record<string, string> = { macd_cross: 'MACD', ma_cross: '双均线', single_ma: '单均线' };
const WD = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
const UP = '#f6465d';
const DOWN = '#0ecb81';
const DIF = '#5b8ff9';
const DEA = '#f6bd16';
const MA_COLORS = ['#5b8ff9', '#f6bd16', '#c084fc', '#34d399'];
// A股语义色浅色主题
const UP = '#dc2626';
const DOWN = '#16a34a';
const DIF_C = '#2563eb';
const DEA_C = '#f59e0b';
const MA_COLORS = ['#2563eb', '#f59e0b', '#a855f7', '#10b981'];
const IND_LABEL: Record<string, string> = { macd: 'DIF', signal: 'DEA', hist: 'MACD', fast: '快线', slow: '慢线', ma: '均线' };
const IND_COLOR: Record<string, string> = {
macd: DIF, signal: DEA, hist: '#9aa4b2', fast: DIF, slow: DEA, ma: '#c084fc',
macd: DIF_C, signal: DEA_C, hist: '#94a3b8', fast: DIF_C, slow: DEA_C, ma: '#a855f7',
};
const container = ref<HTMLDivElement | null>(null);
let chart: IChartApi | null = null;
let candleSeries: ISeriesApi<'Candlestick'> | null = null;
let volumeSeries: ISeriesApi<'Histogram'> | null = null;
let difSeries: ISeriesApi<'Line'> | null = null;
let deaSeries: ISeriesApi<'Line'> | null = null;
let histSeries: ISeriesApi<'Histogram'> | null = null;
let maSeriesArr: { key: string; series: ISeriesApi<'Line'> }[] = [];
let markersApi: ISeriesMarkersPluginApi<Time> | null = null;
interface DayRec {
open: number; high: number; low: number; close: number; volume: number;
prevClose: number | null; ind: Record<string, number | null>;
}
let byTime: Record<string, DayRec> = {};
const tip = ref<{ visible: boolean; x: number; y: number }>({ visible: false, x: 0, y: 0 });
const tipData = ref<ReturnType<typeof buildTip> | null>(null);
const isMACD = computed(() => props.strategy === 'macd_cross' || 'hist' in (props.indicators.data ?? {}));
const legendChips = computed(() => {
const keys = Object.keys(props.indicators.data ?? {});
if (isMACD.value) return [{ label: 'DIF', color: DIF }, { label: 'DEA', color: DEA }];
if (isMACD.value) return [{ label: 'DIF', color: DIF_C }, { label: 'DEA', color: DEA_C }];
return keys.map((k, i) => ({ label: IND_LABEL[k] ?? k, color: MA_COLORS[i % MA_COLORS.length] }));
});
const t = (ts: string): Time => ts.slice(0, 10) as Time;
function timeKey(time: Time): string {
if (typeof time === 'string') return time.slice(0, 10);
const bd = time as { year: number; month: number; day: number };
if (bd && typeof bd === 'object' && 'year' in bd) {
return `${bd.year}-${String(bd.month).padStart(2, '0')}-${String(bd.day).padStart(2, '0')}`;
}
return String(time);
// ---------- 后端指标数据注入(单一事实源:不在前端重算指标) ----------
// calc 回调按索引回读这些序列,与 K 线严格对齐
let BE_SERIES: Record<string, (number | null)[]> = {};
registerIndicator({
name: 'be-macd',
shortName: 'MACD',
figures: [
{ key: 'dif', title: 'DIF', type: 'line', styles: () => ({ color: DIF_C }) },
{ key: 'dea', title: 'DEA', type: 'line', styles: () => ({ color: DEA_C }) },
{
key: 'hist', title: 'HIST', type: 'bar', baseValue: 0, // 零轴柱,缺省会从面板底部画起
styles: (p) => {
const v = (p.data.current as { hist?: number } | null)?.hist ?? 0;
return { color: v >= 0 ? UP : DOWN };
},
},
],
calc: (dataList: KLineData[]) =>
dataList.map((_, i) => ({
dif: BE_SERIES.macd?.[i] ?? undefined,
dea: BE_SERIES.signal?.[i] ?? undefined,
hist: BE_SERIES.hist?.[i] ?? undefined,
})),
});
registerIndicator({
name: 'be-lines',
shortName: 'MA',
figures: [
{ key: 'fast', title: '快线', type: 'line', styles: () => ({ color: DIF_C }) },
{ key: 'slow', title: '慢线', type: 'line', styles: () => ({ color: DEA_C }) },
{ key: 'ma', title: '均线', type: 'line', styles: () => ({ color: MA_COLORS[2] }) },
],
calc: (dataList: KLineData[]) =>
dataList.map((_, i) => ({
fast: BE_SERIES.fast?.[i] ?? undefined,
slow: BE_SERIES.slow?.[i] ?? undefined,
ma: BE_SERIES.ma?.[i] ?? undefined,
})),
});
// ---------- 画线工具 ----------
const TOOLS: { name: string | null; label: string; title: string }[] = [
{ name: null, label: '指针', title: '浏览模式(点击已画图形可选中/拖动/编辑)' },
{ name: 'segment', label: '线段', title: '线段' },
{ name: 'horizontalStraightLine', label: '水平线', title: '水平直线' },
{ name: 'verticalStraightLine', label: '垂直线', title: '垂直直线' },
{ name: 'rectangle', label: '矩形', title: '矩形区域' },
{ name: 'fibonacciSegment', label: '斐波那契', title: '斐波那契回调' },
{ name: 'priceChannelLine', label: '通道线', title: '价格通道线' },
];
const activeTool = ref<string | null>(null);
function pickTool(name: string) {
activeTool.value = name;
chart?.createOverlay({ name });
}
function clearDrawings() {
if (!chart) return;
chart.removeOverlay(); // 清除全部(含买卖点标注),随后重建标注
drawSignalAnnotations();
}
// ---------- 图表 ----------
const container = ref<HTMLDivElement | null>(null);
let chart: Chart | null = null;
interface DayRec {
open: number; high: number; low: number; close: number; volume: number;
prevClose: number | null; ind: Record<string, number | null>;
}
let byIndex: DayRec[] = [];
let candleData: KLineData[] = [];
const tip = ref<{ visible: boolean; x: number; y: number }>({ visible: false, x: 0, y: 0 });
const tipData = ref<ReturnType<typeof buildTip> | null>(null);
const fmt2 = (v: number | null) => (v == null ? '—' : v.toFixed(2));
const fmt3 = (v: number | null) => (v == null ? '—' : v.toFixed(3));
function weekdayOf(s: string) { return WD[new Date(s + 'T00:00:00').getDay()] ?? ''; }
function hexA(hex: string, a: number) {
const n = hex.replace('#', '');
return `rgba(${parseInt(n.slice(0, 2), 16)},${parseInt(n.slice(2, 4), 16)},${parseInt(n.slice(4, 6), 16)},${a})`;
}
function toLine(arr: (number | null)[], c: Candle[]) {
return arr.map((v, i) => (v == null ? { time: t(c[i].ts) } : { time: t(c[i].ts), value: v }));
}
function buildTip(rec: DayRec, key: string) {
function buildTip(rec: DayRec, ts: string) {
const prev = rec.prevClose ?? rec.open;
const change = rec.close - prev;
return {
date: key, weekday: weekdayOf(key),
date: ts.slice(0, 10), weekday: weekdayOf(ts.slice(0, 10)),
open: rec.open, high: rec.high, low: rec.low, close: rec.close,
change, chgPct: prev ? (change / prev) * 100 : 0,
amplitude: prev ? ((rec.high - rec.low) / prev) * 100 : 0,
@@ -92,111 +132,127 @@ function buildTip(rec: DayRec, key: string) {
};
}
function build() {
if (!container.value) return;
const ch = createChart(container.value, {
autoSize: true,
layout: { background: { color: 'transparent' }, textColor: '#9aa4b2', fontSize: 11, attributionLogo: false },
grid: { vertLines: { color: 'rgba(255,255,255,0.04)' }, horzLines: { color: 'rgba(255,255,255,0.04)' } },
crosshair: {
mode: CrosshairMode.Normal,
vertLine: { color: 'rgba(255,255,255,0.25)', width: 1, style: LineStyle.Dashed, labelBackgroundColor: '#2a2e39' },
horzLine: { color: 'rgba(255,255,255,0.25)', width: 1, style: LineStyle.Dashed, labelBackgroundColor: '#2a2e39' },
// 浅色主题 + A股红涨绿跌与默认样式深合并
const LIGHT_STYLES = {
grid: { horizontal: { color: '#eef2f7' }, vertical: { color: '#eef2f7' } },
candle: {
bar: {
upColor: UP, downColor: DOWN,
upBorderColor: UP, downBorderColor: DOWN,
upWickColor: UP, downWickColor: DOWN,
},
rightPriceScale: { borderColor: 'rgba(255,255,255,0.08)', scaleMargins: { top: 0.08, bottom: 0.28 } },
timeScale: { borderColor: 'rgba(255,255,255,0.08)', rightOffset: 6, barSpacing: 8 },
});
priceMark: {
high: { color: '#94a3b8' }, low: { color: '#94a3b8' },
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' } },
crosshair: {
horizontal: { text: { backgroundColor: '#1e293b' } },
vertical: { text: { backgroundColor: '#1e293b' } },
},
separator: { color: '#e2e8f0' },
};
function build() {
if (!container.value || props.candles.length === 0) return;
BE_SERIES = props.indicators.data ?? {};
const ch = init(container.value, { styles: LIGHT_STYLES });
if (!ch) return;
chart = ch;
candleSeries = ch.addSeries(CandlestickSeries, {
upColor: UP, downColor: DOWN, borderUpColor: UP, borderDownColor: DOWN, wickUpColor: UP, wickDownColor: DOWN,
priceFormat: { type: 'price', precision: 2, minMove: 0.01 },
}, 0);
volumeSeries = ch.addSeries(HistogramSeries, { priceFormat: { type: 'volume' }, priceScaleId: 'vol' }, 0);
volumeSeries.priceScale().applyOptions({ scaleMargins: { top: 0.82, bottom: 0 } });
const keys = Object.keys(props.indicators.data ?? {});
if (isMACD.value && props.indicators.data?.hist) {
// MACD 进副图(震荡指标,独立刻度)
difSeries = ch.addSeries(LineSeries, { color: DIF, lineWidth: 2, priceScaleId: 'macd', priceLineVisible: false, lastValueVisible: true }, 1);
deaSeries = ch.addSeries(LineSeries, { color: DEA, lineWidth: 2, priceScaleId: 'macd', priceLineVisible: false, lastValueVisible: true }, 1);
histSeries = ch.addSeries(HistogramSeries, { priceScaleId: 'macd', priceLineVisible: false, lastValueVisible: false }, 1);
try { ch.panes()[1]?.setHeight(140); } catch { /* pane 未就绪 */ }
} else {
// 均线叠加在主图(价格刻度,与 K 线同坐标系)
maSeriesArr = keys.map((k, i) => ({
key: k,
series: ch.addSeries(LineSeries, {
color: MA_COLORS[i % MA_COLORS.length], lineWidth: 1, priceLineVisible: false,
lastValueVisible: false, crosshairMarkerVisible: true,
}, 0),
}));
}
markersApi = createSeriesMarkers(candleSeries, []);
ch.subscribeCrosshairMove((param) => {
const pt = param.point;
if (!param.time || !pt || !container.value) { tip.value.visible = false; return; }
const key = timeKey(param.time);
const rec = byTime[key];
if (!rec) { tip.value.visible = false; return; }
tipData.value = buildTip(rec, key);
const W = container.value.clientWidth, H = container.value.clientHeight;
const TW = 220, TH = 188;
let x = pt.x + 16; if (x + TW > W) x = pt.x - TW - 16; if (x < 4) x = 4;
let y = pt.y + 16; if (y + TH > H) y = H - TH - 6; if (y < 4) y = 4;
tip.value = { visible: true, x, y };
});
fillData();
ch.timeScale().fitContent();
}
function fillData() {
if (!chart || !candleSeries) return;
// 逐日记录(悬停详情)
const c = props.candles;
const keys = Object.keys(props.indicators.data ?? {});
byTime = {};
c.forEach((k, i) => {
const keys = Object.keys(BE_SERIES);
byIndex = c.map((k, i) => {
const ind: Record<string, number | null> = {};
keys.forEach((key) => { ind[key] = props.indicators.data[key]?.[i] ?? null; });
byTime[t(k.ts) as unknown as string] = {
keys.forEach((key) => { ind[key] = BE_SERIES[key]?.[i] ?? null; });
return {
open: k.open, high: k.high, low: k.low, close: k.close, volume: k.volume,
prevClose: i > 0 ? c[i - 1].close : null, ind,
};
});
candleData = c.map((k) => ({
timestamp: new Date(k.ts).getTime(),
open: k.open, high: k.high, low: k.low, close: k.close, volume: k.volume,
}));
const tsList = c.map((k) => k.ts);
candleSeries.setData(c.map(k => ({ time: t(k.ts), open: k.open, high: k.high, low: k.low, close: k.close })));
volumeSeries?.setData(c.map(k => ({
time: t(k.ts), value: k.volume, color: k.close >= k.open ? hexA(UP, 0.5) : hexA(DOWN, 0.5),
})));
// v10 数据接入DataLoader 一次性提供全量(回测结果静态数据,无分页)
// 注意v10 要求 symbol+period+dataLoader 三者齐备才触发 'init' 加载,缺一图表空白
ch.setDataLoader({
getBars: ({ type, callback }) => {
if (type === 'update') {
const last = candleData[candleData.length - 1];
callback(last ? [last] : [], { backward: false, forward: false });
} else if (type === 'init') {
callback(candleData, { backward: false, forward: false });
} else {
callback([], { backward: false, forward: false });
}
},
});
ch.setSymbol({ ticker: props.symbol ?? 'BACKTEST' });
ch.setPeriod({ type: 'day', span: 1 });
if (difSeries && deaSeries && histSeries && props.indicators.data?.hist) {
difSeries.setData(toLine(props.indicators.data.macd ?? [], c));
deaSeries.setData(toLine(props.indicators.data.signal ?? [], c));
histSeries.setData((props.indicators.data.hist ?? []).map((v, i) => ({
time: t(c[i].ts), value: v ?? 0, color: (v ?? 0) >= 0 ? hexA(UP, 0.6) : hexA(DOWN, 0.6),
})));
// 副图/叠加MACD 独立 pane均线叠加主图
ch.createIndicator('VOL');
if (isMACD.value) {
ch.createIndicator('be-macd');
} else {
maSeriesArr.forEach((m) => m.series.setData(toLine(props.indicators.data[m.key] ?? [], c)));
ch.createIndicator({ name: 'be-lines', paneId: 'candle_pane' });
}
// 副图压矮,主图占大头
for (const ind of ch.getIndicators()) {
if (ind.name === 'VOL') ch.setPaneOptions({ id: ind.paneId, height: 84 });
if (ind.name === 'be-macd') ch.setPaneOptions({ id: ind.paneId, height: 120 });
}
const markers: SeriesMarker<Time>[] = props.signals.map(s => ({
time: t(s.ts),
position: s.side === 'buy' ? 'belowBar' : 'aboveBar',
color: s.side === 'buy' ? UP : DOWN,
shape: s.side === 'buy' ? 'arrowUp' : 'arrowDown',
text: s.side === 'buy' ? 'B' : 'S',
}));
markersApi?.setMarkers(markers);
drawSignalAnnotations();
// 悬停详情crosshair 事件自带数据索引与像素坐标
ch.subscribeAction('onCrosshairChange', (d) => {
const data = d as Crosshair | undefined;
const i = data?.dataIndex;
if (data == null || i == null || i < 0 || i >= byIndex.length) {
tip.value.visible = false;
return;
}
tipData.value = buildTip(byIndex[i], tsList[i]);
const el = container.value;
if (el && data.x != null && data.y != null) {
const TW = 224, TH = 196;
let x = data.x + 16; if (x + TW > el.clientWidth) x = data.x - TW - 16; if (x < 4) x = 4;
let y = data.y + 16; if (y + TH > el.clientHeight) y = data.y - TH - 24; if (y < 4) y = 4;
tip.value = { visible: true, x, y };
}
});
}
function drawSignalAnnotations() {
if (!chart) return;
const c = props.candles;
const idxOfTs = new Map<number, number>();
c.forEach((k, i) => idxOfTs.set(new Date(k.ts).getTime(), i));
for (const s of props.signals) {
const i = idxOfTs.get(new Date(s.ts).getTime());
if (i == null) continue;
const k = c[i];
const buy = s.side === 'buy';
chart.createOverlay({
name: 'simpleAnnotation',
points: [{ dataIndex: i, value: buy ? k.low : k.high }],
extendData: buy ? 'B' : 'S',
styles: { text: { color: buy ? UP : DOWN, size: 11, weight: 'bold' } },
});
}
}
function teardown() {
chart?.remove();
chart = null; candleSeries = null; volumeSeries = null;
difSeries = deaSeries = histSeries = null; maSeriesArr = []; markersApi = null;
if (container.value) dispose(container.value);
chart = null;
}
onMounted(build);
@@ -205,33 +261,59 @@ watch(() => [props.candles, props.indicators, props.signals, props.strategy], ()
</script>
<template>
<div class="kline-wrap">
<div class="lc-legend">
<span class="sym">{{ symbol ?? '—' }}<small>{{ TF_LABEL[timeframe ?? '1d'] ?? timeframe }} · {{ STRAT_LABEL[strategy ?? 'macd_cross'] ?? strategy }}</small></span>
<span v-for="(chip, i) in legendChips" :key="i" class="chip"><i :style="{ background: chip.color }"></i>{{ chip.label }}</span>
<div class="relative">
<!-- 图例 + 画线工具栏 -->
<div class="mb-1 flex flex-wrap items-center gap-x-3 gap-y-1 px-2">
<span class="text-[13px] font-semibold text-slate-900">
{{ symbol ?? '—' }}
<small class="ml-1.5 font-normal text-slate-400">
{{ TF_LABEL[timeframe ?? '1d'] ?? timeframe }} · {{ STRAT_LABEL[strategy ?? 'macd_cross'] ?? strategy }}
</small>
</span>
<span v-for="(chip, i) in legendChips" :key="i" class="flex items-center gap-1 text-xs text-slate-500">
<i class="inline-block h-0.5 w-3 rounded" :style="{ background: chip.color }"></i>{{ chip.label }}
</span>
<span class="ml-auto flex items-center gap-0.5 rounded-lg border border-slate-200 bg-slate-50 p-0.5">
<span class="px-1.5 text-[10px] text-slate-400">画线</span>
<button
v-for="tool in TOOLS"
:key="tool.label"
type="button"
:title="tool.title"
class="rounded-md px-2 py-1 text-xs transition-colors"
:class="activeTool === tool.name ? 'bg-blue-600 text-white' : 'text-slate-600 hover:bg-white hover:shadow-sm'"
@click="tool.name === null ? (activeTool = null) : pickTool(tool.name)"
>{{ tool.label }}</button>
<button type="button" class="rounded-md px-2 py-1 text-xs text-slate-400 transition-colors hover:bg-white hover:text-red-600" title="清除所有画线与标注" @click="clearDrawings">清除</button>
</span>
</div>
<div v-if="tip.visible && tipData" class="lc-tooltip" :style="{ left: tip.x + 'px', top: tip.y + 'px' }">
<div class="tt-date">{{ tipData.date }} <span class="tt-wd">{{ tipData.weekday }}</span></div>
<div class="tt-grid">
<div> <b :class="tipData.up ? 'pos' : 'neg'">{{ fmt2(tipData.open) }}</b></div>
<div> <b class="pos">{{ fmt2(tipData.high) }}</b></div>
<div> <b class="neg">{{ fmt2(tipData.low) }}</b></div>
<div> <b :class="tipData.up ? 'pos' : 'neg'">{{ fmt2(tipData.close) }}</b></div>
<!-- 悬停详情同花顺式 -->
<div
v-if="tip.visible && tipData"
class="pointer-events-none absolute z-20 w-[224px] rounded-lg border border-slate-200 bg-white/95 px-3 py-2 text-[11.5px] leading-relaxed text-slate-600 shadow-lg"
:style="{ left: tip.x + 'px', top: tip.y + 'px' }"
>
<div class="mb-0.5 font-semibold text-slate-900">{{ tipData.date }} <span class="ml-1 font-normal text-slate-400">{{ tipData.weekday }}</span></div>
<div class="grid grid-cols-2 gap-x-4">
<div> <b :class="tipData.up ? 'text-up' : 'text-down'">{{ fmt2(tipData.open) }}</b></div>
<div> <b class="text-up">{{ fmt2(tipData.high) }}</b></div>
<div> <b class="text-down">{{ fmt2(tipData.low) }}</b></div>
<div> <b :class="tipData.up ? 'text-up' : 'text-down'">{{ fmt2(tipData.close) }}</b></div>
</div>
<div class="tt-row">
涨跌 <b :class="tipData.up ? 'pos' : 'neg'">{{ tipData.change >= 0 ? '+' : '' }}{{ fmt2(tipData.change) }}</b>
· 涨幅 <b :class="tipData.up ? 'pos' : 'neg'">{{ tipData.chgPct.toFixed(2) }}%</b>
<div>
涨跌 <b :class="tipData.up ? 'text-up' : 'text-down'">{{ tipData.change >= 0 ? '+' : '' }}{{ fmt2(tipData.change) }}</b>
· 涨幅 <b :class="tipData.up ? 'text-up' : 'text-down'">{{ tipData.chgPct.toFixed(2) }}%</b>
</div>
<div class="tt-row">振幅 {{ tipData.amplitude.toFixed(2) }}% · {{ tipData.volLots.toLocaleString() }} </div>
<div class="tt-sep"></div>
<div class="tt-ind">
<span v-for="(v, k) in tipData.ind" :key="k" :style="{ color: IND_COLOR[k] ?? '#9aa4b2' }">
<div>振幅 {{ tipData.amplitude.toFixed(2) }}% · {{ tipData.volLots.toLocaleString() }} </div>
<div class="mt-1 border-t border-slate-100 pt-1">
<span v-for="(v, k) in tipData.ind" :key="k" class="mr-3" :style="{ color: IND_COLOR[k] ?? '#64748b' }">
{{ IND_LABEL[k] ?? k }} {{ fmt3(v) }}
</span>
</div>
</div>
<div ref="container" class="chart-kline"></div>
<div ref="container" class="h-[520px] w-full"></div>
</div>
</template>

View File

@@ -5,16 +5,35 @@ defineProps<{ metrics: MetricsOut }>();
const pct = (x: number) => `${(x * 100).toFixed(2)}%`;
const num = (x: number) => x.toFixed(2);
const sign = (x: number) => (x >= 0 ? 'pos' : 'neg'); // A股正=红、负=绿
// A股语义:正=红、负=绿
const sign = (x: number) => (x >= 0 ? 'text-up' : 'text-down');
</script>
<template>
<div class="stats">
<div class="stat"><span class="label">总收益</span><span class="value" :class="sign(metrics.total_return)">{{ pct(metrics.total_return) }}</span></div>
<div class="stat"><span class="label">最大回撤</span><span class="value neg">{{ pct(metrics.max_drawdown) }}</span></div>
<div class="stat"><span class="label">夏普</span><span class="value" :class="sign(metrics.sharpe)">{{ num(metrics.sharpe) }}</span></div>
<div class="stat"><span class="label">年化波动</span><span class="value">{{ pct(metrics.volatility) }}</span></div>
<div class="stat"><span class="label">胜率</span><span class="value">{{ pct(metrics.win_rate) }}</span></div>
<div class="stat"><span class="label">交易数</span><span class="value">{{ metrics.num_trades }}</span></div>
<div class="mt-4 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
<div class="rounded-xl border border-slate-200 bg-white px-4 py-3">
<div class="text-xs text-slate-400">总收益</div>
<div class="mt-1 text-lg font-semibold" :class="sign(metrics.total_return)">{{ pct(metrics.total_return) }}</div>
</div>
<div class="rounded-xl border border-slate-200 bg-white px-4 py-3">
<div class="text-xs text-slate-400">最大回撤</div>
<div class="mt-1 text-lg font-semibold text-down">{{ pct(metrics.max_drawdown) }}</div>
</div>
<div class="rounded-xl border border-slate-200 bg-white px-4 py-3">
<div class="text-xs text-slate-400">夏普比率</div>
<div class="mt-1 text-lg font-semibold" :class="sign(metrics.sharpe)">{{ num(metrics.sharpe) }}</div>
</div>
<div class="rounded-xl border border-slate-200 bg-white px-4 py-3">
<div class="text-xs text-slate-400">年化波动</div>
<div class="mt-1 text-lg font-semibold text-slate-900">{{ pct(metrics.volatility) }}</div>
</div>
<div class="rounded-xl border border-slate-200 bg-white px-4 py-3">
<div class="text-xs text-slate-400">胜率</div>
<div class="mt-1 text-lg font-semibold text-slate-900">{{ pct(metrics.win_rate) }}</div>
</div>
<div class="rounded-xl border border-slate-200 bg-white px-4 py-3">
<div class="text-xs text-slate-400">交易次数</div>
<div class="mt-1 text-lg font-semibold text-slate-900">{{ metrics.num_trades }}</div>
</div>
</div>
</template>

View File

@@ -1,7 +1,5 @@
<script setup lang="ts">
import { ref } from 'vue';
import Button from 'primevue/button';
import Textarea from 'primevue/textarea';
defineProps<{ loading: boolean }>();
const emit = defineEmits<{ (e: 'run', text: string): void }>();
@@ -22,29 +20,37 @@ function run() {
</script>
<template>
<div class="toolbar" style="flex-direction: column; align-items: stretch; gap: 10px;">
<div class="field" style="gap: 7px;">
<label>用一句话描述你的选股条件</label>
<Textarea
v-model="text"
class="screener-input"
:auto-resize="true"
rows="2"
size="small"
placeholder="例如:这两天 KDJ 的 J 小于 10市值 100~200 亿的公司"
@keyup.ctrl.enter="run"
/>
<div class="rounded-xl border border-slate-200 bg-white p-5">
<label class="lbl">用一句话描述你的选股条件</label>
<textarea
v-model="text"
rows="2"
class="ipt w-full resize-y leading-relaxed"
placeholder="例如:这两天 KDJ 的 J 小于 10市值 100~200 亿的公司"
@keyup.ctrl.enter="run"
/>
<div class="mt-3 flex flex-wrap items-center gap-1.5">
<span class="mr-1 text-xs text-slate-400">示例</span>
<button
v-for="(ex, i) in examples"
:key="i"
type="button"
class="max-w-full truncate rounded-full border border-slate-200 bg-slate-50 px-3 py-1 text-xs text-slate-600 transition-colors hover:border-slate-300 hover:bg-slate-100"
@click="text = ex"
>{{ ex }}</button>
</div>
<div class="quick">
<span class="qlabel">示例</span>
<span v-for="(ex, i) in examples" :key="i" class="qchip" @click="text = ex">{{ ex }}</span>
</div>
<div class="hint">
支持 KDJ / RSI / MACD / 布林 / 均线指标条件市值 / 市盈率 / 换手率等快照条件以及连续 N N 天任一天等时间窗口
<code>Ctrl+Enter</code> 快速筛选
</div>
<div>
<Button label="开始筛选" icon="pi pi-search" size="small" :loading="loading" :disabled="!text.trim()" @click="run" />
<div class="mt-4 flex items-center justify-between gap-3">
<p class="text-xs leading-relaxed text-slate-400">
支持 KDJ / RSI / MACD / 布林 / 均线指标条件市值 / 市盈率 / 换手率等快照条件以及连续 N N 天任一天时间窗口
<kbd class="rounded border border-slate-200 bg-slate-50 px-1">Ctrl</kbd>+<kbd class="rounded border border-slate-200 bg-slate-50 px-1">Enter</kbd> 快速筛选
</p>
<button type="button" class="btn-primary shrink-0 disabled:opacity-50" :disabled="loading || !text.trim()" @click="run">
<svg v-if="loading" class="h-4 w-4 animate-spin" viewBox="0 0 24 24" fill="none"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" /><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" /></svg>
<svg v-else class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7" /><path d="M21 21l-4.3-4.3" /></svg>
{{ loading ? '筛选中…' : '开始筛选' }}
</button>
</div>
</div>
</template>

View File

@@ -1,10 +1,9 @@
<script setup lang="ts">
import { computed } from 'vue';
import DataTable from 'primevue/datatable';
import Column from 'primevue/column';
import { computed, ref } from 'vue';
import type { ScreenerItemOut, ScreenerRunResponse } from '@/api/types';
const props = defineProps<{ result: ScreenerRunResponse }>();
const emit = defineEmits<{ (e: 'preview', item: ScreenerItemOut): void }>();
const items = computed(() => props.result.items);
// 动态指标列:[{ key: 'kdj_j', label: 'KDJ J(9,3,3)' }]
@@ -12,64 +11,132 @@ const indCols = computed(() =>
Object.entries(props.result.indicator_labels).map(([key, label]) => ({ key, label })),
);
function pctClass(v: number | null) {
if (v == null) return '';
return v > 0 ? 'pos' : v < 0 ? 'neg' : '';
// ---------- 排序(点击表头切换 升/降) ----------
type FieldOf = (it: ScreenerItemOut) => number | string | null;
const FIXED_COLS: { key: string; label: string; get: FieldOf; num?: boolean; fmt?: (v: number | null) => string; cls?: (v: number | null) => string }[] = [
{ key: 'ts_code', label: '代码', get: (it) => it.ts_code },
{ key: 'name', label: '名称', get: (it) => it.name },
{ key: 'close', label: '最新价', get: (it) => it.close, num: true, fmt: fmt2 },
{
key: 'pct_chg', label: '涨跌幅%', get: (it) => it.pct_chg, num: true,
fmt: (v) => (v == null ? '—' : (v > 0 ? '+' : '') + v.toFixed(2)),
cls: (v) => (v == null ? '' : v > 0 ? 'text-up' : v < 0 ? 'text-down' : ''),
},
{ key: 'total_mv', label: '总市值(亿)', get: (it) => it.total_mv, num: true, fmt: fmt2 },
{ key: 'circ_mv', label: '流通市值(亿)', get: (it) => it.circ_mv, num: true, fmt: fmt2 },
{ key: 'pe_ttm', label: 'PE-TTM', get: (it) => it.pe_ttm, num: true, fmt: fmt2 },
{ key: 'pb', label: 'PB', get: (it) => it.pb, num: true, fmt: fmt2 },
{ key: 'turnover_rate', label: '换手率%', get: (it) => it.turnover_rate, num: true, fmt: fmt2 },
];
const sortKey = ref<string>('total_mv');
const sortDir = ref<'asc' | 'desc'>('desc');
function getVal(it: ScreenerItemOut, key: string): number | string | null {
const fixed = FIXED_COLS.find((c) => c.key === key);
if (fixed) return fixed.get(it);
const ind = indCols.value.find((c) => c.key === key);
return ind ? (it.indicators?.[ind.key] ?? null) : null;
}
function fmt(v: number | null, digits = 2) {
return v == null ? '—' : v.toFixed(digits);
function toggleSort(key: string) {
if (sortKey.value === key) {
sortDir.value = sortDir.value === 'asc' ? 'desc' : 'asc';
} else {
sortKey.value = key;
sortDir.value = 'desc'; // 默认数值列降序更直觉
}
}
const sortedItems = computed(() => {
const key = sortKey.value;
const dir = sortDir.value === 'asc' ? 1 : -1;
return [...items.value].sort((a, b) => {
const va = getVal(a, key);
const vb = getVal(b, key);
if (va == null) return 1; // 空值排最后
if (vb == null) return -1;
if (typeof va === 'number' && typeof vb === 'number') return (va - vb) * dir;
return String(va).localeCompare(String(vb)) * dir;
});
});
function fmt2(v: number | null) {
return v == null ? '—' : v.toFixed(2);
}
function fmtInd(it: ScreenerItemOut, key: string) {
const v = it.indicators?.[key];
return v == null ? '—' : v.toFixed(2);
}
</script>
<template>
<div class="panel">
<div class="panel-title">
命中 {{ result.total }} {{ result.total > items.length ? `(仅显示前 ${items.length}` : '' }}
<span v-if="result.trade_date" style="color: var(--ink-3); margin-left: 8px;">· 数据基准 {{ result.trade_date.slice(0, 10) }}</span>
<div class="mt-4 overflow-hidden rounded-xl border border-slate-200 bg-white">
<div class="border-b border-slate-100 px-4 py-3 text-[13px] text-slate-600">
命中 <span class="font-semibold text-slate-900">{{ result.total }}</span>
<span v-if="result.total > items.length" class="text-slate-400">仅显示前 {{ items.length }}</span>
<span v-if="result.trade_date" class="ml-2 text-slate-400">· 数据基准 {{ result.trade_date.slice(0, 10) }}</span>
</div>
<div class="max-h-[560px] overflow-auto">
<table class="w-full border-collapse text-[13px]">
<thead class="sticky top-0 z-10 bg-slate-50 text-slate-500">
<tr class="border-b border-slate-200">
<th
v-for="c in FIXED_COLS"
:key="c.key"
class="cursor-pointer select-none whitespace-nowrap px-3 py-2 text-left font-medium hover:text-slate-900"
@click="toggleSort(c.key)"
>
{{ c.label }}
<span v-if="sortKey === c.key" class="text-blue-600">{{ sortDir === 'asc' ? '' : '' }}</span>
</th>
<th
v-for="col in indCols"
:key="col.key"
class="cursor-pointer select-none whitespace-nowrap px-3 py-2 text-left font-medium hover:text-slate-900"
@click="toggleSort(col.key)"
>
{{ col.label }}
<span v-if="sortKey === col.key" class="text-blue-600">{{ sortDir === 'asc' ? '' : '' }}</span>
</th>
<th class="whitespace-nowrap px-3 py-2 text-right font-medium">操作</th>
</tr>
</thead>
<tbody>
<tr
v-for="it in sortedItems"
:key="it.ts_code"
class="cursor-pointer border-b border-slate-50 transition-colors last:border-0 hover:bg-blue-50/40"
@click="emit('preview', it)"
>
<td class="whitespace-nowrap px-3 py-1.5 font-medium text-slate-900">{{ it.ts_code }}</td>
<td class="whitespace-nowrap px-3 py-1.5 text-slate-700">{{ it.name }}</td>
<td class="whitespace-nowrap px-3 py-1.5">{{ fmt2(it.close) }}</td>
<td class="whitespace-nowrap px-3 py-1.5" :class="it.pct_chg != null && FIXED_COLS[3].cls ? FIXED_COLS[3].cls!(it.pct_chg) : ''">
{{ it.pct_chg == null ? '—' : (it.pct_chg > 0 ? '+' : '') + it.pct_chg.toFixed(2) }}
</td>
<td class="whitespace-nowrap px-3 py-1.5 text-slate-700">{{ fmt2(it.total_mv) }}</td>
<td class="whitespace-nowrap px-3 py-1.5 text-slate-700">{{ fmt2(it.circ_mv) }}</td>
<td class="whitespace-nowrap px-3 py-1.5 text-slate-700">{{ fmt2(it.pe_ttm) }}</td>
<td class="whitespace-nowrap px-3 py-1.5 text-slate-700">{{ fmt2(it.pb) }}</td>
<td class="whitespace-nowrap px-3 py-1.5 text-slate-700">{{ fmt2(it.turnover_rate) }}</td>
<td v-for="col in indCols" :key="col.key" class="whitespace-nowrap px-3 py-1.5 text-slate-700">
{{ fmtInd(it, col.key) }}
</td>
<td class="whitespace-nowrap px-3 py-1.5 text-right">
<button
type="button"
class="rounded-md border border-slate-200 px-2 py-0.5 text-xs text-blue-600 transition-colors hover:border-blue-300 hover:bg-blue-50"
@click.stop="emit('preview', it)"
>详情</button>
</td>
</tr>
<tr v-if="sortedItems.length === 0">
<td :colspan="FIXED_COLS.length + indCols.length + 1" class="px-3 py-12 text-center text-slate-400">没有符合条件的股票</td>
</tr>
</tbody>
</table>
</div>
<DataTable :value="items" size="small" striped-rows :scrollable="true" scroll-height="560px" sort-mode="single">
<Column field="ts_code" header="代码" sortable style="min-width: 92px;">
<template #body="{ data }">
<span style="font-variant-numeric: tabular-nums; color: var(--ink);">{{ data.ts_code }}</span>
</template>
</Column>
<Column field="name" header="名称" sortable style="min-width: 96px;" />
<Column field="close" header="最新价" sortable style="min-width: 84px;">
<template #body="{ data }">{{ fmt(data.close) }}</template>
</Column>
<Column field="pct_chg" header="涨跌幅%" sortable style="min-width: 88px;">
<template #body="{ data }">
<span :class="pctClass(data.pct_chg)">{{ data.pct_chg == null ? '—' : (data.pct_chg > 0 ? '+' : '') + data.pct_chg.toFixed(2) }}</span>
</template>
</Column>
<Column field="total_mv" header="总市值(亿)" sortable style="min-width: 100px;">
<template #body="{ data }">{{ fmt(data.total_mv) }}</template>
</Column>
<Column field="circ_mv" header="流通市值(亿)" sortable style="min-width: 106px;">
<template #body="{ data }">{{ fmt(data.circ_mv) }}</template>
</Column>
<Column field="pe_ttm" header="PE-TTM" sortable style="min-width: 84px;">
<template #body="{ data }">{{ fmt(data.pe_ttm) }}</template>
</Column>
<Column field="pb" header="PB" sortable style="min-width: 70px;">
<template #body="{ data }">{{ fmt(data.pb) }}</template>
</Column>
<Column field="turnover_rate" header="换手率%" sortable style="min-width: 88px;">
<template #body="{ data }">{{ fmt(data.turnover_rate) }}</template>
</Column>
<Column
v-for="col in indCols"
:key="col.key"
:field="`indicators.${col.key}`"
:header="col.label"
sortable
style="min-width: 110px;"
>
<template #body="{ data }">
<span style="font-variant-numeric: tabular-nums;">{{ data.indicators?.[col.key] == null ? '—' : data.indicators[col.key].toFixed(2) }}</span>
</template>
</Column>
</DataTable>
</div>
</template>

View File

@@ -0,0 +1,286 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { getStockPreview } from '@/api/client';
import type { PreviewResponse, ScreenerItemOut } from '@/api/types';
import DetailKLine from './DetailKLine.vue';
const props = defineProps<{
items: ScreenerItemOut[];
initial: string; // ts_code
}>();
const emit = defineEmits<{ (e: 'close'): void }>();
// ---------- 状态 ----------
const active = ref(props.initial);
const data = ref<PreviewResponse | null>(null);
const loading = ref(false);
const error = ref<string | null>(null);
const filter = ref('');
// 副图指标:点击开关 / 拖拽排序
const SUBS = [
{ key: 'vol', label: 'VOL' },
{ key: 'macd', label: 'MACD' },
{ key: 'kdj', label: 'KDJ' },
{ key: 'rsi', label: 'RSI' },
];
const subPanes = ref<string[]>(['vol', 'macd', 'kdj', 'rsi']);
const showBoll = ref(false);
const filteredItems = computed(() => {
const q = filter.value.trim().toLowerCase();
if (!q) return props.items;
return props.items.filter(
(it) => it.ts_code.toLowerCase().includes(q) || it.name.toLowerCase().includes(q),
);
});
const activeItem = computed(
() => props.items.find((it) => it.ts_code === active.value) ?? null,
);
// 头部/右侧展示值:优先预览信息(最新),否则用选股行数据兜底
const header = computed(() => {
const info = data.value?.info;
const item = activeItem.value;
return {
name: info?.name ?? item?.name ?? active.value,
close: info?.close ?? item?.close ?? null,
pct: info?.pct_chg ?? item?.pct_chg ?? null,
};
});
// ---------- 数据加载 ----------
let fetchToken = 0;
async function load(code: string) {
const token = ++fetchToken;
loading.value = true;
error.value = null;
data.value = null;
try {
const res = await getStockPreview(code);
if (token === fetchToken) data.value = res;
} catch (e) {
if (token === fetchToken) error.value = e instanceof Error ? e.message : '加载失败';
} finally {
if (token === fetchToken) loading.value = false;
}
}
watch(active, (code) => load(code), { immediate: true });
function moveActive(delta: number) {
const list = filteredItems.value;
const idx = list.findIndex((it) => it.ts_code === active.value);
if (list.length === 0) return;
const next = idx < 0 ? 0 : Math.min(list.length - 1, Math.max(0, idx + delta));
active.value = list[next].ts_code;
}
// ---------- 键盘 / 滚动锁 ----------
function onKeydown(e: KeyboardEvent) {
// 输入法组合态 / 焦点在输入框时不拦截否则搜索框打字会切股、Esc 关浮层)
if (e.isComposing) return;
const t = e.target as HTMLElement | null;
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;
if (e.key === 'Escape') emit('close');
else if (e.key === 'ArrowUp') { e.preventDefault(); moveActive(-1); }
else if (e.key === 'ArrowDown') { e.preventDefault(); moveActive(1); }
}
onMounted(() => {
window.addEventListener('keydown', onKeydown);
document.body.style.overflow = 'hidden';
});
onBeforeUnmount(() => {
window.removeEventListener('keydown', onKeydown);
document.body.style.overflow = '';
});
// ---------- 副图 chips开关 + 拖拽排序 ----------
let dragKey: string | null = null;
function toggleSub(key: string) {
subPanes.value = subPanes.value.includes(key)
? subPanes.value.filter((k) => k !== key)
: [...subPanes.value, key];
}
function onDragStart(e: DragEvent, key: string) {
dragKey = key;
// Firefox/Safari 要求 dragstart 写入数据才会真正发起拖拽
e.dataTransfer?.setData('text/plain', key);
if (e.dataTransfer) e.dataTransfer.effectAllowed = 'move';
}
function onDrop(target: string) {
if (!dragKey || dragKey === target) return;
const arr = [...subPanes.value];
const from = arr.indexOf(dragKey);
if (from >= 0) arr.splice(from, 1);
const to = arr.indexOf(target);
arr.splice(to >= 0 ? to : arr.length, 0, dragKey);
subPanes.value = arr;
dragKey = null;
}
// ---------- 格式化 ----------
const fmt = (v: number | null | undefined, d = 2) => (v == null ? '—' : v.toFixed(d));
const fmtInt = (v: number | null | undefined) =>
v == null ? '—' : Math.round(v).toLocaleString();
const pctClass = (v: number | null | undefined) =>
v == null ? '' : v > 0 ? 'text-up' : v < 0 ? 'text-down' : '';
const fmtListDate = (s?: string | null) => (s && s.length === 8 ? `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}` : s ?? '—');
</script>
<template>
<div class="fixed inset-0 z-40 flex flex-col bg-slate-100">
<!-- 顶栏 -->
<header class="flex h-12 shrink-0 items-center gap-4 border-b border-slate-200 bg-white px-4">
<div class="flex items-baseline gap-2">
<span class="text-base font-semibold text-slate-900">{{ header.name }}</span>
<span class="text-xs text-slate-400">{{ active }}</span>
</div>
<div class="flex items-baseline gap-2">
<span class="text-lg font-semibold" :class="pctClass(header.pct)">{{ fmt(header.close) }}</span>
<span v-if="header.pct != null" class="text-sm" :class="pctClass(header.pct)">
{{ header.pct > 0 ? '+' : '' }}{{ fmt(header.pct) }}%
</span>
</div>
<span v-if="data?.source === 'market'" class="rounded bg-amber-50 px-2 py-0.5 text-[11px] text-amber-600">
近段未复权数据
</span>
<span v-else-if="data" class="rounded bg-blue-50 px-2 py-0.5 text-[11px] text-blue-600">前复权</span>
<span class="ml-auto text-xs text-slate-400"> 切换 · Esc 关闭</span>
<button type="button" class="btn-ghost !px-2.5 !py-1" title="关闭 (Esc)" @click="emit('close')">
<svg class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6L6 18M6 6l12 12" /></svg>
</button>
</header>
<!-- 三栏主体 -->
<div class="flex min-h-0 flex-1">
<!-- 命中列表 -->
<aside class="flex w-56 shrink-0 flex-col border-r border-slate-200 bg-white">
<div class="border-b border-slate-100 p-2">
<input v-model="filter" type="text" class="ipt w-full !py-1 text-xs" placeholder="搜索代码 / 名称" />
</div>
<div class="min-h-0 flex-1 overflow-y-auto">
<button
v-for="it in filteredItems"
:key="it.ts_code"
type="button"
class="flex w-full items-center gap-2 border-b border-slate-50 px-3 py-2 text-left transition-colors"
:class="it.ts_code === active ? 'bg-blue-50' : 'hover:bg-slate-50'"
@click="active = it.ts_code"
>
<span class="min-w-0 flex-1">
<span class="block truncate text-[13px] font-medium text-slate-800">{{ it.name }}</span>
<span class="block text-[11px] text-slate-400">{{ it.ts_code }}</span>
</span>
<span class="text-right">
<span class="block text-[13px]">{{ fmt(it.close) }}</span>
<span class="block text-[11px]" :class="pctClass(it.pct_chg)">
{{ it.pct_chg == null ? '—' : (it.pct_chg > 0 ? '+' : '') + it.pct_chg.toFixed(2) + '%' }}
</span>
</span>
</button>
<div v-if="filteredItems.length === 0" class="px-3 py-8 text-center text-xs text-slate-400">无匹配</div>
</div>
<div class="border-t border-slate-100 px-3 py-2 text-[11px] text-slate-400"> {{ filteredItems.length }} </div>
</aside>
<!-- K线 + 指标面板 -->
<section class="flex min-w-0 flex-1 flex-col">
<!-- 指标开关 / 排序 -->
<div class="flex shrink-0 flex-wrap items-center gap-1.5 bg-white px-3 py-2">
<span class="text-[11px] text-slate-400">副图</span>
<button
v-for="s in SUBS"
:key="s.key"
type="button"
draggable="true"
class="cursor-grab rounded-md border px-2.5 py-1 text-xs transition-colors active:cursor-grabbing"
:class="subPanes.includes(s.key)
? 'border-blue-600 bg-blue-600 text-white'
: 'border-slate-200 bg-white text-slate-400 line-through'"
:title="subPanes.includes(s.key) ? '点击隐藏 · 拖动排序' : '点击显示'"
@click="toggleSub(s.key)"
@dragstart="onDragStart($event, s.key)"
@dragover.prevent
@drop="onDrop(s.key)"
>
{{ s.label }}
</button>
<button
type="button"
class="rounded-md border px-2.5 py-1 text-xs transition-colors"
:class="showBoll ? 'border-purple-500 bg-purple-500 text-white' : 'border-slate-200 bg-white text-slate-400'"
title="主图叠加布林带"
@click="showBoll = !showBoll"
>BOLL</button>
<span class="ml-2 text-[11px] text-slate-400">点击开关副图 · 拖动排序 · 滚轮缩放 · 拖拽平移</span>
</div>
<!-- 图表 -->
<div class="relative min-h-0 flex-1 bg-white p-1">
<div v-if="loading" class="absolute inset-0 z-10 flex flex-col items-center justify-center bg-white/80 text-sm text-slate-400">
<svg class="mb-2 h-6 w-6 animate-spin text-blue-500" viewBox="0 0 24 24" fill="none"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" /><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" /></svg>
{{ active }} 首次查看需拉取全量日线
</div>
<div v-else-if="error" class="flex h-full items-center justify-center text-sm text-red-600">{{ error }}</div>
<DetailKLine
v-else-if="data && data.candles.length"
:ticker="data.ts_code"
:candles="data.candles"
:indicators="data.indicators"
:sub-panes="subPanes"
:show-boll="showBoll"
/>
<div v-else class="flex h-full items-center justify-center text-sm text-slate-400">无数据</div>
</div>
</section>
<!-- 个股信息通达信式 -->
<aside v-if="data" class="w-72 shrink-0 overflow-y-auto border-l border-slate-200 bg-white p-4">
<div class="border-b border-slate-100 pb-3">
<div class="text-[15px] font-semibold text-slate-900">{{ data.info.name }}</div>
<div class="mt-0.5 text-xs text-slate-400">
{{ data.info.ts_code }}
<span v-if="data.info.market" class="ml-1 rounded bg-slate-100 px-1.5 py-0.5">{{ data.info.market }}</span>
</div>
<div class="mt-2 flex items-baseline gap-2">
<span class="text-2xl font-semibold" :class="pctClass(data.info.pct_chg)">{{ fmt(data.info.close) }}</span>
<span v-if="data.info.pct_chg != null" class="text-sm" :class="pctClass(data.info.pct_chg)">
{{ data.info.pct_chg > 0 ? '+' : '' }}{{ fmt(data.info.pct_chg) }}%
</span>
</div>
</div>
<div class="mt-3 grid grid-cols-2 gap-y-2 text-[13px]">
<template v-for="(row, i) in [
['今开', fmt(data.info.open)],
['昨收', fmt(data.info.pre_close)],
['最高', fmt(data.info.high)],
['最低', fmt(data.info.low)],
['成交量', fmtInt(data.info.volume_hand) + ' 手'],
['成交额', fmt(data.info.amount_yi) + ' 亿'],
['换手率', fmt(data.info.turnover_rate) + '%'],
['市盈率TTM', fmt(data.info.pe_ttm)],
['市净率', fmt(data.info.pb)],
['总市值', fmt(data.info.total_mv) + ' 亿'],
['流通市值', fmt(data.info.circ_mv) + ' 亿'],
['上市日期', fmtListDate(data.info.list_date)],
['数据日期', (data.info.trade_date ?? '').slice(0, 10) || '—'],
]" :key="i">
<span class="text-slate-400">{{ row[0] }}</span>
<span class="text-right text-slate-800">{{ row[1] }}</span>
</template>
</div>
<div class="mt-4 border-t border-slate-100 pt-3 text-[13px]">
<div class="mb-2 text-xs text-slate-400">归属</div>
<div class="flex flex-wrap gap-1.5">
<span v-if="data.info.industry" class="rounded-full bg-slate-100 px-2.5 py-0.5 text-xs text-slate-600">{{ data.info.industry }}</span>
<span v-if="data.info.area" class="rounded-full bg-slate-100 px-2.5 py-0.5 text-xs text-slate-600">{{ data.info.area }}</span>
</div>
</div>
</aside>
</div>
</div>
</template>

View File

@@ -1,6 +1,5 @@
<script setup lang="ts">
import { computed } from 'vue';
import Button from 'primevue/button';
import type { ScreenerSyncStatus } from '@/api/types';
const props = defineProps<{ status: ScreenerSyncStatus | null }>();
@@ -15,7 +14,7 @@ function fmtDate(s?: string | null) {
const freshness = computed(() => {
const s = props.status;
if (!s) return { tone: 'none', text: '正在检查数据状态…' };
if (!s.ready) return { tone: 'warn', text: '全市场数据尚未同步,请先点击右侧「同步数据」' };
if (!s.ready) return { tone: 'warn', text: '全市场数据尚未同步,请先点击右侧「同步市场数据」' };
const snapMissing = s.stats.snapshot_rows === 0;
const d = s.stats.dates;
const base = `数据截至 ${fmtDate(s.last_trade_date)} · 共 ${d} 个交易日 · ${s.stats.stocks} 只股票`;
@@ -25,32 +24,41 @@ const freshness = computed(() => {
</script>
<template>
<div class="sync-bar">
<span :class="freshness.tone === 'ok' ? 'ok' : freshness.tone === 'warn' ? 'warn' : ''">
<i class="pi" :class="freshness.tone === 'ok' ? 'pi-check-circle' : 'pi-info-circle'" style="margin-right: 5px;"></i>
<div class="mt-4 flex flex-wrap items-center gap-x-4 gap-y-2 rounded-xl border border-slate-200 bg-white px-4 py-3 text-[13px] text-slate-600">
<span :class="freshness.tone === 'ok' ? 'text-emerald-600' : freshness.tone === 'warn' ? 'text-amber-600' : 'text-slate-400'">
<svg class="mr-1 inline h-4 w-4 align-[-3px]" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<template v-if="freshness.tone === 'ok'">
<path d="M22 11.1V12a10 10 0 11-5.9-9.1" />
<path d="M22 4L12 14l-3-3-7 7" />
</template>
<template v-else>
<circle cx="12" cy="12" r="10" />
<path d="M12 16v-4M12 8h.01" />
</template>
</svg>
{{ freshness.text }}
</span>
<template v-if="status && status.running">
<span class="sync-progress">
<i class="pi pi-spin pi-spinner"></i>
<span class="txt">{{ status.step || '同步中…' }}{{ status.done_days }}/{{ status.total_days }}</span>
<span class="flex min-w-[200px] flex-1 items-center gap-2">
<svg class="h-4 w-4 shrink-0 animate-spin text-blue-500" viewBox="0 0 24 24" fill="none"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" /><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" /></svg>
<span class="whitespace-nowrap text-xs text-slate-500">{{ status.step || '同步中…' }}{{ status.done_days }}/{{ status.total_days }}</span>
<span class="h-1.5 flex-1 overflow-hidden rounded-full bg-slate-100">
<span class="block h-full rounded-full bg-blue-500 transition-all" :style="{ width: (status.total_days ? Math.min(100, (status.done_days / status.total_days) * 100) : 0) + '%' }" />
</span>
</span>
</template>
<template v-else>
<span class="spacer"></span>
<Button
label="同步市场数据"
icon="pi pi-refresh"
size="small"
severity="secondary"
:disabled="status?.running"
@click="emit('sync')"
/>
<span class="flex-1"></span>
<button type="button" class="btn-ghost shrink-0 disabled:opacity-50" :disabled="status?.running" @click="emit('sync')">
<svg class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 11-2.6-6.4M21 3v6h-6" /></svg>
同步市场数据
</button>
</template>
<div v-if="status && status.error" class="warn" style="flex-basis: 100%; margin-top: 4px;">
<i class="pi pi-exclamation-triangle" style="margin-right: 5px;"></i>{{ status.error }}
<div v-if="status && status.error" class="w-full text-amber-600">
<svg class="mr-1 inline h-4 w-4 align-[-3px]" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.3 3.9L1.8 18a2 2 0 001.7 3h17a2 2 0 001.7-3L13.7 3.9a2 2 0 00-3.4 0z" /><path d="M12 9v4M12 17h.01" /></svg>
{{ status.error }}
</div>
</div>
</template>