看股功能更新
This commit is contained in:
@@ -18,6 +18,9 @@ import type {
|
||||
SyncRequest,
|
||||
SyncResponse,
|
||||
Timeframe,
|
||||
TradesClearResponse,
|
||||
TradesImportResponse,
|
||||
UserTrade,
|
||||
} from './types';
|
||||
|
||||
// dev 用 Vite 代理(/api -> :8000);生产构建设 VITE_API_BASE 指向后端地址。
|
||||
@@ -37,8 +40,11 @@ async function readError(res: Response, fallback: string): Promise<string> {
|
||||
const body = await res.text();
|
||||
if (!body) return fallback;
|
||||
try {
|
||||
const data = JSON.parse(body) as { detail?: string };
|
||||
return data.detail || fallback;
|
||||
const data = JSON.parse(body) as { detail?: unknown };
|
||||
// FastAPI 校验类 422 的 detail 是对象数组,直接当字符串用会显示成 [object Object]
|
||||
if (typeof data.detail === 'string') return data.detail;
|
||||
if (data.detail != null) return JSON.stringify(data.detail);
|
||||
return fallback;
|
||||
} catch {
|
||||
return body;
|
||||
}
|
||||
@@ -49,7 +55,9 @@ async function apiFetch(path: string, init: RequestInit = {}): Promise<Response>
|
||||
...init,
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
...(init.body ? { 'Content-Type': 'application/json' } : {}),
|
||||
// 仅 JSON(字符串 body)手工设 Content-Type;FormData 必须留给浏览器生成
|
||||
// multipart 边界,手工设置会导致后端解析失败 422
|
||||
...(typeof init.body === 'string' ? { 'Content-Type': 'application/json' } : {}),
|
||||
...init.headers,
|
||||
},
|
||||
});
|
||||
@@ -158,6 +166,8 @@ export async function getStocks(params: {
|
||||
industry?: string;
|
||||
area?: string;
|
||||
watched_only?: boolean;
|
||||
sort?: string;
|
||||
order?: 'asc' | 'desc';
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}): Promise<StockListResponse> {
|
||||
@@ -167,6 +177,8 @@ export async function getStocks(params: {
|
||||
if (params.industry) q.set('industry', params.industry);
|
||||
if (params.area) q.set('area', params.area);
|
||||
if (params.watched_only) q.set('watched_only', 'true');
|
||||
if (params.sort) q.set('sort', params.sort);
|
||||
if (params.order) q.set('order', params.order);
|
||||
q.set('limit', String(params.limit ?? 100));
|
||||
q.set('offset', String(params.offset ?? 0));
|
||||
const res = await apiFetch(`/api/stocks?${q.toString()}`);
|
||||
@@ -224,3 +236,27 @@ export async function deleteScreenerQuery(id: number): Promise<void> {
|
||||
const res = await apiFetch(`/api/screener/queries/${id}`, { method: 'DELETE' });
|
||||
if (!res.ok && res.status !== 401) throw new ApiError(`删除失败 (HTTP ${res.status})`, res.status);
|
||||
}
|
||||
|
||||
// ---------- 交割单(个人实盘买卖点) ----------
|
||||
export async function getTrades(tsCode?: string): Promise<UserTrade[]> {
|
||||
const q = tsCode ? `?ts_code=${encodeURIComponent(tsCode)}` : '';
|
||||
const res = await apiFetch(`/api/trades${q}`);
|
||||
if (!res.ok) throw new ApiError(await readError(res, `获取成交记录失败 (HTTP ${res.status})`), res.status);
|
||||
return (await res.json()) as UserTrade[];
|
||||
}
|
||||
|
||||
/** 上传交割单文件(CSV/Excel/HTML 均可,后端自动识别列名与编码)。 */
|
||||
export async function importTrades(file: File): Promise<TradesImportResponse> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
// 注意:不能手工设 Content-Type,FormData 需自带 multipart 边界
|
||||
const res = await apiFetch('/api/trades/import', { method: 'POST', body: form });
|
||||
if (!res.ok) throw new ApiError(await readError(res, `导入失败 (HTTP ${res.status})`), res.status);
|
||||
return (await res.json()) as TradesImportResponse;
|
||||
}
|
||||
|
||||
export async function clearTrades(): Promise<TradesClearResponse> {
|
||||
const res = await apiFetch('/api/trades', { method: 'DELETE' });
|
||||
if (!res.ok) throw new ApiError(await readError(res, `清空成交失败 (HTTP ${res.status})`), res.status);
|
||||
return (await res.json()) as TradesClearResponse;
|
||||
}
|
||||
|
||||
@@ -211,7 +211,11 @@ export interface StockListItem {
|
||||
prev_close?: number | null;
|
||||
pct_chg?: number | null;
|
||||
last_ts?: string | null;
|
||||
bar_count?: number | null;
|
||||
turnover_rate?: number | null; // 换手率 %(daily_snapshot)
|
||||
pe_ttm?: number | null;
|
||||
pb?: number | null;
|
||||
total_mv?: number | null; // 总市值(亿元)
|
||||
circ_mv?: number | null; // 流通市值(亿元)
|
||||
watched: boolean;
|
||||
}
|
||||
|
||||
@@ -257,6 +261,32 @@ export interface ScreenerQueryItem {
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
// ---------- 交割单(个人实盘买卖点,镜像 app/schemas.py) ----------
|
||||
export interface UserTrade {
|
||||
id: number;
|
||||
ts_code: string;
|
||||
name?: string | null;
|
||||
trade_date: string; // ISO YYYY-MM-DD
|
||||
direction: 'buy' | 'sell';
|
||||
price?: number | null; // 券商原始成交价(不复权)
|
||||
qty: number;
|
||||
amount?: number | null;
|
||||
fee?: number | null;
|
||||
}
|
||||
|
||||
export interface TradesImportResponse {
|
||||
inserted: number;
|
||||
skipped_dup: number;
|
||||
skipped_other: number;
|
||||
stocks: number;
|
||||
bad: string[];
|
||||
sample: UserTrade[];
|
||||
}
|
||||
|
||||
export interface TradesClearResponse {
|
||||
deleted: number;
|
||||
}
|
||||
|
||||
// ---------- 事件回测(自然语言) ----------
|
||||
export interface EventBacktestSpec {
|
||||
entry: ScreenConditions;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import {
|
||||
dispose, init, registerIndicator, registerOverlay,
|
||||
type Chart, type KLineData, type Point,
|
||||
type Chart, type KLineData, type OverlayCreate, type OverlayTemplate, type Point,
|
||||
} from 'klinecharts';
|
||||
// 官方画线扩展(preview.klinecharts.com 同款工具集);rect/circle 沿用 v10 内置版,不注册扩展的重名模板
|
||||
import {
|
||||
@@ -22,6 +22,50 @@ for (const t of [
|
||||
registerOverlay(t);
|
||||
}
|
||||
|
||||
// ---------- 实盘买卖点标记(交割单导入) ----------
|
||||
// v10 无 v9 的 simpleMarker,须注册自定义模板;字母种类/明细经 extendData 传入。
|
||||
// A股惯例(通达信/同花顺同款):B 买贴 low 下方、S 卖贴 high 上方、T 当日买+卖(做T)贴 high 上方;
|
||||
// 图上只显示单个字母徽章(色底白字,用户指定固定配色,不随涨跌设置),成交明细(数量/均价/费用)
|
||||
// 悬停字母时由组件浮层展示——onMouseEnter/onMouseLeave 是创建项级回调(OverlayCreate 未 Omit
|
||||
// 事件键),闭包进组件状态即可(模板是模块级的,拿不到组件实例)。
|
||||
interface TradeRow { label: string; text: string; tone: 'buy' | 'sell' | '' }
|
||||
interface TradeMarkExt { kind: 'B' | 'S' | 'T'; rows: TradeRow[] }
|
||||
const TRADE_COLORS: Record<'B' | 'S' | 'T', string> = { B: '#FE354B', S: '#3B7BBF', T: '#F9A504' };
|
||||
const tradeMarkerTemplate: OverlayTemplate<TradeMarkExt> = {
|
||||
name: 'tradeMarker',
|
||||
totalStep: 2,
|
||||
needDefaultPointFigure: false,
|
||||
needDefaultXAxisFigure: false,
|
||||
needDefaultYAxisFigure: false,
|
||||
createPointFigures: ({ overlay, coordinates }) => {
|
||||
const c = coordinates[0];
|
||||
const ext = overlay.extendData;
|
||||
if (!c || !ext) return [];
|
||||
const ly = ext.kind === 'B' ? c.y + 22 : c.y - 22; // 字母中心与 bar 高低点的像素间距(离K线远一点更清爽)
|
||||
return [
|
||||
{
|
||||
type: 'text',
|
||||
attrs: { x: c.x, y: ly, text: ext.kind, align: 'center', baseline: 'middle' },
|
||||
styles: {
|
||||
color: '#FFFFFF', backgroundColor: TRADE_COLORS[ext.kind],
|
||||
size: 12, weight: 'bold', borderRadius: 3,
|
||||
paddingLeft: 3, paddingRight: 3, paddingTop: 1, paddingBottom: 1,
|
||||
},
|
||||
ignoreEvent: true,
|
||||
},
|
||||
{ // 透明命中区:把字母徽章的悬停判定兜成 r=9 的圆,指上去更容易。
|
||||
// 必须排在 text 之后:库按数组顺序挂 children、倒序分发 mousemove,
|
||||
// circle 放最后才能最先接管事件——否则首个落点在徽章上时 enter 会被
|
||||
// text 的 ignoreEvent 拦住、tooltip 出不来(circle 全透明,压顶层无视觉影响)
|
||||
type: 'circle',
|
||||
attrs: { x: c.x, y: ly, r: 9 },
|
||||
styles: { style: 'fill', color: 'rgba(0,0,0,0)', borderColor: 'rgba(0,0,0,0)' },
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
registerOverlay(tradeMarkerTemplate);
|
||||
|
||||
const props = defineProps<{
|
||||
ticker: string;
|
||||
candles: Candle[];
|
||||
@@ -45,6 +89,17 @@ const props = defineProps<{
|
||||
timeframe: string;
|
||||
/** 浮层显示的指标(可选;缺省=目录全开,空数组=仅日期头) */
|
||||
tooltipFields?: TooltipField[];
|
||||
/** 日期跳转锚点(本地零点时间戳):build 完成后把该日 K 线滚动到可视区中央;null=停在最新 */
|
||||
centerTs?: number | null;
|
||||
/** 实盘买卖点(交割单导入,按日聚合成标记):B=当日只买 贴 low 下方、S=当日只卖 贴 high 上方、
|
||||
* T=当日买+卖(做T)贴 high 上方;rows 为悬停明细(数量/均价/费用)。
|
||||
* 只画落在已渲染窗口内的(更早的等左滑翻页后自动补画) */
|
||||
tradeMarkers?: { key: string; ts: number; kind: 'B' | 'S' | 'T'; rows: TradeRow[] }[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
/** 日期跳转锚点在本次数据窗口里找不到(早于上市/晚于最后一根):请父组件回退到最新行情并提示 */
|
||||
(e: 'centerMiss', ts: number): void;
|
||||
}>();
|
||||
|
||||
// A股语义色(黑底高对比);UP/DOWN 跟随设置中的涨跌配色
|
||||
@@ -246,7 +301,11 @@ function darkStyles() {
|
||||
horizontal: { text: { backgroundColor: '#333A45' } },
|
||||
vertical: { text: { backgroundColor: '#333A45' } },
|
||||
},
|
||||
separator: { color: '#23252B' },
|
||||
separator: {
|
||||
color: '#23252B',
|
||||
// 悬停/拖拽分隔条时的底色(库默认 8% 蓝在纯黑底上不可见,加重为可感知的拖拽提示)
|
||||
activeBackgroundColor: 'rgba(37, 99, 235, 0.30)',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -254,6 +313,23 @@ function darkStyles() {
|
||||
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);
|
||||
|
||||
// ---------- 分隔条拖拽调高(库原生 SeparatorWidget)→ 持久化 ----------
|
||||
// build 时记录 key→paneId;拖动中库会高频触发 onPaneDrag,防抖后读回各副图实际高度写入偏好
|
||||
let paneIdByKey: Record<string, string> = {};
|
||||
let subHTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function persistSubHeights() {
|
||||
if (!chart) return;
|
||||
const next: Record<string, number> = {};
|
||||
for (const key of props.subPanes) {
|
||||
const pid = paneIdByKey[key];
|
||||
const h = pid ? (chart.getPaneOptions(pid) as { height?: number } | null)?.height : undefined;
|
||||
if (typeof h === 'number') next[key] = Math.max(40, Math.round(h));
|
||||
}
|
||||
if (Object.keys(next).length === 0) return;
|
||||
settings.setChartLayout({ subHeights: { ...props.subHeights, ...next } });
|
||||
}
|
||||
|
||||
// ---------- 鼠标跟随信息框(通达信式,浮层贴鼠标,每行一个指标) ----------
|
||||
interface TipRow { key: string; label: string; text: string; tone: '' | 'up' | 'down' }
|
||||
interface HoverInfo {
|
||||
@@ -426,6 +502,113 @@ function pickTool(key: string) {
|
||||
function clearOverlays() {
|
||||
chart?.removeOverlay();
|
||||
activeTool.value = '';
|
||||
// removeOverlay() 无参清的是全部 overlay(含交易点)——交易点不是用户画线,重画回来
|
||||
renderTradeMarkers();
|
||||
}
|
||||
|
||||
// ---------- 日期跳转居中 ----------
|
||||
/** ts(本地零点)落在哪根K上:取该时刻之前(含同日)最近一根的下标,无则 -1;停牌/非交易日自然落到前一根 */
|
||||
function idxAtOrBefore(list: KLineData[], ts: number): number {
|
||||
let lo = 0, hi = list.length - 1, ans = -1;
|
||||
while (lo <= hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
if (list[mid].timestamp <= ts) { ans = mid; lo = mid + 1; } else hi = mid - 1;
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
|
||||
/** 把已渲染的第 i 根K线滚动到可视区中央(scrollToDataIndex 定位到右缘,补半个可视窗口即居中) */
|
||||
function centerDataIndex(i: number) {
|
||||
if (!chart) return;
|
||||
const v = chart.getVisibleRange();
|
||||
const vis = Math.max(2, Math.round(v.to - v.from) - 1); // from/to 含半个bar余量
|
||||
chart.scrollToDataIndex(i + Math.floor(vis / 2) - 1, 350);
|
||||
}
|
||||
|
||||
/** 对外:把某天滚动到可视区中央;目标不在当前已渲染窗口内时返回 false(调用方走重拉窗口)。
|
||||
* ts 晚于最后一根 10 天以上(未来日期/超出现有数据)同样算失败,避免 floor 搜索落到
|
||||
* 最后一根、锚点却指向一个不存在交易的日期;10 天容忍周末与春节黄金周这类停牌间隙。 */
|
||||
const FUTURE_TOL_MS = 10 * 86400000;
|
||||
function centerOn(ts: number): boolean {
|
||||
if (!chart) return false;
|
||||
const list = chart.getDataList();
|
||||
if (list.length === 0) return false;
|
||||
const i = idxAtOrBefore(list, ts);
|
||||
if (i < 0) return false;
|
||||
if (ts > list[list.length - 1].timestamp + FUTURE_TOL_MS) return false;
|
||||
centerDataIndex(i);
|
||||
return true;
|
||||
}
|
||||
defineExpose({ centerOn });
|
||||
|
||||
// ---------- 实盘买卖点标记渲染 ----------
|
||||
const TRADE_GROUP = 'trades';
|
||||
|
||||
/** 交易点允许吸附到「晚于最后一根K时间戳」的窗口,按周期放大:周/月/年K的 bar 时间戳
|
||||
* 是周期首日(周一/1日/1月1日),当前周期内的成交(如月中)仍应贴到最后一根上。
|
||||
* 日K严格为 0:行情未同步到成交日时宁可先不画(数据同步后重建图表自动补上),
|
||||
* 也不能把周一的成交错标到周五的K线上。 */
|
||||
const TRADE_AHEAD_MS: Record<string, number> = {
|
||||
'1d': 0,
|
||||
'1w': 6 * 86400000,
|
||||
'1M': 31 * 86400000,
|
||||
'1y': 366 * 86400000,
|
||||
};
|
||||
|
||||
/** 按 groupId 整组重建买卖点标记(先删后建,幂等)。交易日期按时间戳吸附到所在 bar:
|
||||
* B 贴 bar.low 下方、S/T 贴 bar.high 上方;坐标随复权切换自动重算(value 取自当前数据)。
|
||||
* 早于已渲染窗口的交易先跳过——左滑翻页 serveOlder 吐出新数据后会重跑本函数补画。
|
||||
* 列表为空(关闭显示/清空成交/切到无成交股票)也必须清组,否则旧标记残留。 */
|
||||
function renderTradeMarkers() {
|
||||
if (!chart) return;
|
||||
tradeTip.value = null; // 组重建期间字母已换位,旧明细浮层不能留在原地
|
||||
chart.removeOverlay({ groupId: TRADE_GROUP });
|
||||
if (!props.tradeMarkers?.length) return;
|
||||
const list = chart.getDataList();
|
||||
if (list.length === 0) return;
|
||||
const lastTs = list[list.length - 1].timestamp;
|
||||
const aheadMs = TRADE_AHEAD_MS[props.timeframe] ?? 0;
|
||||
const creates: OverlayCreate<unknown>[] = [];
|
||||
for (const m of props.tradeMarkers) {
|
||||
const i = idxAtOrBefore(list, m.ts);
|
||||
if (i < 0 || m.ts > lastTs + aheadMs) continue; // 未翻到 / 行情尚未覆盖该周期
|
||||
const bar = list[i];
|
||||
creates.push({
|
||||
id: `trade-${m.key}`,
|
||||
groupId: TRADE_GROUP,
|
||||
name: 'tradeMarker',
|
||||
points: [{ timestamp: bar.timestamp, value: m.kind === 'B' ? bar.low : bar.high }],
|
||||
extendData: { kind: m.kind, rows: m.rows },
|
||||
onMouseEnter: (ev) => {
|
||||
// pageX/pageY 是文档绝对坐标(x/y 是相对各 pane 画布的,副图 pane 会带偏移),而
|
||||
// getBoundingClientRect 是视口坐标——须再减 window.scrollX/Y 对齐基准:浮层是从滚过的
|
||||
// 列表页打开的(body 锁滚仍保留偏移),漏减会把 tip 整体顶出可视区、悬停像失灵
|
||||
const rect = container.value?.getBoundingClientRect();
|
||||
const px = (ev.pageX ?? 0) - (rect?.left ?? 0) - window.scrollX;
|
||||
const py = (ev.pageY ?? 0) - (rect?.top ?? 0) - window.scrollY;
|
||||
tradeTip.value = { ...placeTradeTip(px, py, m.rows.length), kind: m.kind, date: m.key, rows: m.rows };
|
||||
},
|
||||
onMouseLeave: () => { tradeTip.value = null; },
|
||||
// v10 右键命中 figure 会默认 removeOverlay(lock 只拦左键按下),标记被悄悄删掉——显式吞掉
|
||||
onRightClick: (ev) => { ev.preventDefault?.(); },
|
||||
lock: true,
|
||||
});
|
||||
}
|
||||
if (creates.length) chart.createOverlay(creates);
|
||||
}
|
||||
|
||||
// ---------- 交易点悬停明细(悬停 B/S/T 字母才显示,离开/滚动即隐) ----------
|
||||
interface TradeTip { x: number; y: number; kind: 'B' | 'S' | 'T'; date: string; rows: TradeRow[] }
|
||||
const tradeTip = ref<TradeTip | null>(null);
|
||||
|
||||
/** 贴鼠标定位并在右缘/下缘自动翻转(与十字线浮层 placeHover 同款策略,宽度略大) */
|
||||
function placeTradeTip(px: number, py: number, rowCount: number): { x: number; y: number } {
|
||||
const w = container.value?.clientWidth ?? 800;
|
||||
const h = container.value?.clientHeight ?? 500;
|
||||
const bw = 168, bh = 36 + rowCount * 17, gap = 12;
|
||||
const x = px + gap + bw > w - 4 ? Math.max(4, px - gap - bw) : px + gap;
|
||||
const y = py + gap + bh > h - 4 ? Math.max(4, py - gap - bh) : py + gap;
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
function build() {
|
||||
@@ -464,12 +647,20 @@ function build() {
|
||||
const start = allData.length - served - take;
|
||||
served += take;
|
||||
callback(allData.slice(start, start + take), { forward: canBack(), backward: false });
|
||||
renderTradeMarkers(); // 窗口左扩后补画此前跳过的更早交易点
|
||||
};
|
||||
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 });
|
||||
// 首屏:最近 INIT_BARS 根;更早历史由左滑触发 'forward' 翻页。
|
||||
// 有跳转锚点时把 serve 左扩到包含锚点(锚点落在窗口前 1/2 处),仍保持
|
||||
// [n-served, n) 尾连续不变式——这样 serveOlder 的翻页切片不用变;
|
||||
// BOLL/副图等同数据重建时锚点就不会掉出首屏窗口。
|
||||
const n = allData.length;
|
||||
const anchorIdx = props.centerTs != null ? idxAtOrBefore(allData, props.centerTs) : -1;
|
||||
served = anchorIdx >= 0
|
||||
? Math.min(n, Math.max(INIT_BARS, n - anchorIdx + (INIT_BARS >> 1)))
|
||||
: Math.min(INIT_BARS, n);
|
||||
callback(allData.slice(n - served), { forward: canBack(), backward: false });
|
||||
maybePrefetch(myEpoch);
|
||||
} else if (type === 'forward') {
|
||||
// 左缘:优先吐本地未吐出的(首屏余量或已预取页),本地耗尽再向服务端翻一页更早历史
|
||||
@@ -505,38 +696,62 @@ function build() {
|
||||
ch.createIndicator({ name: ensureMaIndicator(props.maPeriods), paneId: 'candle_pane' });
|
||||
if (props.showBoll) ch.createIndicator({ name: 'pv-boll', paneId: 'candle_pane' });
|
||||
|
||||
// 副图按用户顺序创建,并设置用户高度;主图吃剩余高度
|
||||
// 副图按用户顺序创建,并设置用户高度;主图吃剩余高度。
|
||||
// minHeight 交给库在分隔条拖拽时强制执行(与 subH 的 40px 下限一致)
|
||||
const subTotal = props.subPanes.reduce((s, k) => s + subH(k), 0);
|
||||
const total = container.value.clientHeight || 560;
|
||||
ch.setPaneOptions({ id: 'candle_pane', height: Math.max(200, total - subTotal - 24) });
|
||||
ch.setPaneOptions({ id: 'candle_pane', height: Math.max(200, total - subTotal - 24), minHeight: 200 });
|
||||
paneIdByKey = {};
|
||||
for (const key of props.subPanes) {
|
||||
const name = key === 'vol' ? 'VOL' : `pv-${key}`;
|
||||
ch.createIndicator(name);
|
||||
const paneId = ch.getIndicators().find((i) => i.name === name)?.paneId;
|
||||
if (paneId) ch.setPaneOptions({ id: paneId, height: subH(key) });
|
||||
if (paneId) {
|
||||
paneIdByKey[key] = paneId;
|
||||
ch.setPaneOptions({ id: paneId, height: subH(key), minHeight: 40 });
|
||||
}
|
||||
}
|
||||
|
||||
bindCrosshair(ch);
|
||||
// 分隔条拖拽调高:拖动结束(250ms 无新事件)后把各副图实际高度持久化;
|
||||
// 期间图表已重建(epoch 变化)则丢弃,新图表按存档布局
|
||||
ch.subscribeAction('onPaneDrag', () => {
|
||||
if (myEpoch !== epoch) return;
|
||||
if (subHTimer) clearTimeout(subHTimer);
|
||||
subHTimer = setTimeout(() => { subHTimer = null; persistSubHeights(); }, 250);
|
||||
});
|
||||
// 缓冲预取:可视范围接近已加载左缘(<200 根)时提前翻下一页
|
||||
ch.subscribeAction('onVisibleRangeChange', (payload) => {
|
||||
if (myEpoch !== epoch) return;
|
||||
tradeTip.value = null; // 滚动后字母随 bar 移位,悬停明细立即失效
|
||||
const from = (payload as { data?: { from?: unknown } }).data?.from;
|
||||
if (typeof from === 'number' && from < 200) maybePrefetch(myEpoch);
|
||||
});
|
||||
ch.setOffsetRightDistance(28);
|
||||
ch.scrollToRealTime();
|
||||
// 日期跳转:build 尾部的 scrollToRealTime 会把视口重置到最新一根,居中必须放在它之后
|
||||
//(init 数据在 setPeriod 时已同步落入图表,这里可直接定位)。
|
||||
// 居中失败(锚点早于上市首日/晚于最后一根)必须上报:否则锚点 chip 与统计口径
|
||||
// 仍停留在「已定位」状态,视口却悄悄回到最新行情。
|
||||
if (props.centerTs != null && !centerOn(props.centerTs)) emit('centerMiss', props.centerTs);
|
||||
// init 数据在 setPeriod 时已同步落入图表,可直接画首屏窗口内的交易点
|
||||
renderTradeMarkers();
|
||||
}
|
||||
|
||||
function teardown() {
|
||||
if (subHTimer) { clearTimeout(subHTimer); subHTimer = null; }
|
||||
if (container.value) dispose(container.value);
|
||||
chart = null;
|
||||
hover.value = null;
|
||||
tradeTip.value = null;
|
||||
activeTool.value = '';
|
||||
}
|
||||
|
||||
onMounted(build);
|
||||
onBeforeUnmount(teardown);
|
||||
watch(() => [props.candles, props.indicators, props.subPanes, props.showBoll, props.maPeriods, props.timeframe], () => { teardown(); build(); }, { deep: true });
|
||||
// 买卖点数据变化(导入/清空/开关显示):只重画标记,不重建图表(保留滚动位置与用户画线)
|
||||
watch(() => props.tradeMarkers, renderTradeMarkers, { deep: true });
|
||||
// 涨跌配色切换:重建图表以应用新颜色
|
||||
watch(() => settings.priceTone, () => { teardown(); build(); });
|
||||
// 副图高度变化:仅调 pane 高度,不重建(保留滚动/画线状态)
|
||||
@@ -544,11 +759,11 @@ watch(() => props.subHeights, () => {
|
||||
if (!chart) return;
|
||||
const subTotal = props.subPanes.reduce((s, k) => s + subH(k), 0);
|
||||
const total = container.value?.clientHeight || 560;
|
||||
chart.setPaneOptions({ id: 'candle_pane', height: Math.max(200, total - subTotal - 24) });
|
||||
chart.setPaneOptions({ id: 'candle_pane', height: Math.max(200, total - subTotal - 24), minHeight: 200 });
|
||||
for (const key of props.subPanes) {
|
||||
const name = key === 'vol' ? 'VOL' : `pv-${key}`;
|
||||
const paneId = chart.getIndicators().find((i) => i.name === name)?.paneId;
|
||||
if (paneId) chart.setPaneOptions({ id: paneId, height: subH(key) });
|
||||
if (paneId) chart.setPaneOptions({ id: paneId, height: subH(key), minHeight: 40 });
|
||||
}
|
||||
}, { deep: true });
|
||||
</script>
|
||||
@@ -556,12 +771,13 @@ watch(() => props.subHeights, () => {
|
||||
<template>
|
||||
<!-- mousemove 用 capture:klinecharts 在内部容器上以冒泡阶段监听并同步触发
|
||||
onCrosshairChange→placeHover,capture 先于它更新 mx/my,避免用到上一次的坐标 -->
|
||||
<div class="relative h-full w-full" @mousemove.capture="onMove" @mouseleave="hover = null">
|
||||
<div class="relative h-full w-full" @mousemove.capture="onMove" @mouseleave="hover = null; tradeTip = null">
|
||||
<div ref="container" class="h-full w-full"></div>
|
||||
|
||||
<!-- 鼠标跟随信息框(贴鼠标,右/下缘自动翻转;每行一个指标,内容由浮层设置决定) -->
|
||||
<!-- 鼠标跟随信息框(贴鼠标,右/下缘自动翻转;每行一个指标,内容由浮层设置决定)。
|
||||
悬停交易字母时让位给明细浮层,两框几乎同点位叠加会呈现双层边框的重影 -->
|
||||
<div
|
||||
v-if="hover"
|
||||
v-if="hover && !tradeTip"
|
||||
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"
|
||||
>
|
||||
@@ -578,8 +794,33 @@ watch(() => props.subHeights, () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 画图画线工具栏(常用一行 + 「更多」分组面板) -->
|
||||
<div class="absolute right-2 top-2 z-10 rounded-md border border-[#26272E] bg-[#101014] shadow-sm">
|
||||
<!-- 交易点悬停明细:贴鼠标、右/下缘自动翻转;日期 + 字母 + 当日买卖数量/均价/费用 -->
|
||||
<div
|
||||
v-if="tradeTip"
|
||||
class="pointer-events-none absolute z-20 w-44 rounded border border-[#33353D] bg-black/90 px-2.5 py-1.5 font-mono text-xs leading-4 text-[#E8EAED] shadow-lg"
|
||||
:style="{ left: `${tradeTip.x}px`, top: `${tradeTip.y}px` }"
|
||||
>
|
||||
<div class="flex items-baseline justify-between">
|
||||
<span class="text-[#9BA3AE]">{{ tradeTip.date }}</span>
|
||||
<span class="font-bold" :style="{ color: TRADE_COLORS[tradeTip.kind] }">{{ tradeTip.kind }}</span>
|
||||
</div>
|
||||
<div class="mt-1 border-t border-[#33353D]/60 pt-1">
|
||||
<div v-for="(r, i) in tradeTip.rows" :key="i" class="flex items-baseline justify-between">
|
||||
<span class="text-[#A8AFB8]">{{ r.label }}</span>
|
||||
<span
|
||||
:style="r.tone ? { color: r.tone === 'buy' ? TRADE_COLORS.B : TRADE_COLORS.S } : undefined"
|
||||
:class="r.tone ? '' : 'text-[#E8EAED]'"
|
||||
>{{ r.text }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 画图画线工具栏(常用一行 + 「更多」分组面板)。
|
||||
移入工具栏时 canvas 收不到后续 mousemove、onMouseLeave 不会触发,须在此清掉交易明细浮层 -->
|
||||
<div
|
||||
class="absolute right-2 top-2 z-10 rounded-md border border-[#26272E] bg-[#101014] shadow-sm"
|
||||
@mouseenter="tradeTip = null"
|
||||
>
|
||||
<div class="flex items-center gap-0.5 px-1 py-0.5">
|
||||
<button
|
||||
v-for="t in COMMON_TOOLS"
|
||||
|
||||
110
frontend/src/components/SettingsModal.vue
Normal file
110
frontend/src/components/SettingsModal.vue
Normal file
@@ -0,0 +1,110 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted } from 'vue';
|
||||
import { useSettingsStore, type PriceAdjust, type PriceTone } from '@/stores/settings';
|
||||
|
||||
const emit = defineEmits<{ (e: 'close'): void }>();
|
||||
const settings = useSettingsStore();
|
||||
|
||||
// ---------- 分类:行情配色 ----------
|
||||
const TONES: { key: PriceTone; label: string; desc: string; up: string; down: string }[] = [
|
||||
{ key: 'red-up', label: '红涨绿跌', desc: 'A 股风格', up: '#FE354B', down: '#1EBE72' },
|
||||
{ key: 'green-up', label: '绿涨红跌', desc: '美股风格', up: '#1EBE72', down: '#FE354B' },
|
||||
];
|
||||
|
||||
// ---------- 分类:K线复权 ----------
|
||||
const ADJUSTS: { key: PriceAdjust; label: string; desc: string }[] = [
|
||||
{ key: 'bfq', label: '不复权', desc: '原始价格,含除权跳空' },
|
||||
{ key: 'qfq', label: '前复权', desc: '以最新价为基准,看趋势最常用' },
|
||||
{ key: 'hfq', label: '后复权', desc: '以上市价为基准,看累计涨幅' },
|
||||
];
|
||||
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') emit('close');
|
||||
}
|
||||
onMounted(() => window.addEventListener('keydown', onKeydown));
|
||||
onBeforeUnmount(() => window.removeEventListener('keydown', onKeydown));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="fixed inset-0 z-50 grid place-items-center bg-black/60 p-4 backdrop-blur-sm" @click.self="emit('close')">
|
||||
<div class="w-full max-w-md rounded-lg border border-[#26272E] bg-[#101014] shadow-xl shadow-black/60" role="dialog" aria-label="设置">
|
||||
<!-- 头部 -->
|
||||
<div class="flex items-center justify-between border-b border-[#1E2026] px-5 py-3.5">
|
||||
<h2 class="text-sm font-semibold text-[#E8EAED]">设置</h2>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded p-1 text-[#9BA3AE] transition-colors hover:bg-[#1E2026] hover:text-[#E8EAED]"
|
||||
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>
|
||||
</div>
|
||||
|
||||
<!-- 分类一:行情配色 -->
|
||||
<div class="px-5 py-4">
|
||||
<div class="text-[13px] font-medium tracking-wide text-[#A8AFB8]">行情配色</div>
|
||||
<p class="mt-1 text-[13px] text-[#9BA3AE]">设置全站涨跌颜色,立即生效并自动记住。</p>
|
||||
|
||||
<div class="mt-3 grid grid-cols-2 gap-3">
|
||||
<button
|
||||
v-for="t in TONES"
|
||||
:key="t.key"
|
||||
type="button"
|
||||
class="rounded-lg border p-3 text-left transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||
:class="settings.priceTone === t.key
|
||||
? 'border-blue-500 bg-blue-500/15 ring-1 ring-blue-500'
|
||||
: 'border-[#26272E] hover:border-[#3A3D46]'"
|
||||
@click="settings.setPriceTone(t.key)"
|
||||
>
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-sm font-medium text-[#E8EAED]">{{ t.label }}</span>
|
||||
<span
|
||||
v-if="settings.priceTone === t.key"
|
||||
class="grid h-4 w-4 place-items-center rounded-full bg-blue-600 text-white"
|
||||
>
|
||||
<svg class="h-2.5 w-2.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1 text-[13px] text-[#9BA3AE]">{{ t.desc }}</div>
|
||||
<!-- 效果预览 -->
|
||||
<div class="mt-2.5 flex items-baseline gap-3 font-mono text-sm">
|
||||
<span :style="{ color: t.up }">+2.50%</span>
|
||||
<span :style="{ color: t.down }">-1.30%</span>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 分类二:K线复权 -->
|
||||
<div class="border-t border-[#1E2026] px-5 py-4">
|
||||
<div class="text-[13px] font-medium tracking-wide text-[#A8AFB8]">K线复权</div>
|
||||
<p class="mt-1 text-[13px] text-[#9BA3AE]">个股详情 K 线的默认口径;浮层内也可随时切换。</p>
|
||||
|
||||
<div class="mt-3 grid grid-cols-3 gap-3">
|
||||
<button
|
||||
v-for="a in ADJUSTS"
|
||||
:key="a.key"
|
||||
type="button"
|
||||
class="rounded-lg border p-3 text-left transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||
:class="settings.priceAdjust === a.key
|
||||
? 'border-blue-500 bg-blue-500/15 ring-1 ring-blue-500'
|
||||
: 'border-[#26272E] hover:border-[#3A3D46]'"
|
||||
@click="settings.setPriceAdjust(a.key)"
|
||||
>
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-sm font-medium text-[#E8EAED]">{{ a.label }}</span>
|
||||
<span
|
||||
v-if="settings.priceAdjust === a.key"
|
||||
class="grid h-4 w-4 place-items-center rounded-full bg-blue-600 text-white"
|
||||
>
|
||||
<svg class="h-2.5 w-2.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1 text-[13px] text-[#9BA3AE]">{{ a.desc }}</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,7 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { addWatchlist, getStockPreview, getWatchlist as getWatchlistApi, removeWatchlist } from '@/api/client';
|
||||
import type { ChartLayoutPrefs, PreviewResponse, ScreenerItemOut, Timeframe, TooltipField } from '@/api/types';
|
||||
import {
|
||||
addWatchlist, clearTrades, getStockPreview, getTrades, getWatchlist as getWatchlistApi,
|
||||
importTrades, removeWatchlist,
|
||||
} from '@/api/client';
|
||||
import type {
|
||||
ChartLayoutPrefs, PreviewResponse, ScreenerItemOut, Timeframe, TooltipField,
|
||||
TradesImportResponse, UserTrade,
|
||||
} from '@/api/types';
|
||||
import { useSettingsStore, DEFAULT_TOOLTIP_FIELDS, TOOLTIP_FIELDS, type PriceAdjust } from '@/stores/settings';
|
||||
import DetailKLine from './DetailKLine.vue';
|
||||
|
||||
@@ -9,7 +15,12 @@ const props = defineProps<{
|
||||
items: ScreenerItemOut[];
|
||||
initial: string; // ts_code
|
||||
}>();
|
||||
const emit = defineEmits<{ (e: 'close'): void; (e: 'watched-change'): void }>();
|
||||
const emit = defineEmits<{
|
||||
(e: 'close'): void;
|
||||
(e: 'watched-change'): void;
|
||||
/** 浮层内切股(键盘 ↑/↓、侧栏点击)时上报当前 ts_code,父组件据此同步路由 */
|
||||
(e: 'change', code: string): void;
|
||||
}>();
|
||||
const settings = useSettingsStore();
|
||||
|
||||
// ---------- 状态 ----------
|
||||
@@ -43,11 +54,6 @@ function setTimeframe(tf: Timeframe) {
|
||||
settings.setChartLayout({ timeframe: tf });
|
||||
}
|
||||
|
||||
// 数据口径徽标:market=近段未复权兜底;其余为实际复权口径(可能因因子缺失与所选不同)
|
||||
const ADJUST_LABELS: Record<string, string> = { bfq: '不复权', qfq: '前复权', hfq: '后复权' };
|
||||
const sourceLabel = computed(() =>
|
||||
data.value ? (ADJUST_LABELS[data.value.source] ?? data.value.source) : '');
|
||||
|
||||
// ---------- 副图 / MA / 高度(全部随用户偏好持久化) ----------
|
||||
const SUBS = [
|
||||
{ key: 'vol', label: 'VOL' },
|
||||
@@ -68,12 +74,7 @@ function toggleSub(key: string) {
|
||||
subPanes: cur.includes(key) ? cur.filter((k) => k !== key) : [...cur, key],
|
||||
});
|
||||
}
|
||||
function adjustHeight(key: string, delta: number) {
|
||||
const DEFAULTS: Record<string, number> = { vol: 64, macd: 100, kdj: 96, rsi: 84 };
|
||||
const base = subHeights.value;
|
||||
const next = Math.max(40, (base[key] ?? DEFAULTS[key] ?? 90) + delta);
|
||||
settings.setChartLayout({ subHeights: { ...base, [key]: next } });
|
||||
}
|
||||
// 副图高度改为图内分隔条直接拖拽(DetailKLine 订阅 onPaneDrag 持久化),此处不再提供按钮
|
||||
|
||||
// 副图拖拽排序
|
||||
let dragKey: string | null = null;
|
||||
@@ -120,8 +121,57 @@ function toggleTipField(key: TooltipField) {
|
||||
tooltipFields: cur.includes(key) ? cur.filter((k) => k !== key) : [...cur, key],
|
||||
});
|
||||
}
|
||||
function resetTipFields() {
|
||||
settings.setChartLayout({ tooltipFields: [...DEFAULT_TOOLTIP_FIELDS] });
|
||||
|
||||
// ---------- 日期跳转(输入 YYYYMMDD,把该日K线定位到可视区中央) ----------
|
||||
const JUMP_END_DAYS = 170; // 锚点 + 170 自然日 ≈ 120 个交易日:锚点恰落在 240 根首吐窗口正中
|
||||
const jumpInput = ref('');
|
||||
const jumpErr = ref('');
|
||||
const jumpTs = ref<number | null>(null); // 当前锚点(本地零点时间戳);null=最新行情模式
|
||||
const klineRef = ref<InstanceType<typeof DetailKLine> | null>(null);
|
||||
|
||||
/** '20200218' → 本地零点时间戳(与 Candle.ts 的反序列化口径一致,精确命中当日K线);非法返回 null */
|
||||
function parseJumpDate(raw: string): number | null {
|
||||
if (!/^\d{8}$/.test(raw)) return null;
|
||||
const y = +raw.slice(0, 4), m = +raw.slice(4, 6), d = +raw.slice(6, 8);
|
||||
const dt = new Date(y, m - 1, d);
|
||||
if (dt.getFullYear() !== y || dt.getMonth() !== m - 1 || dt.getDate() !== d) return null;
|
||||
if (y < 1990 || y > 2099) return null;
|
||||
return dt.getTime();
|
||||
}
|
||||
/** 时间戳 → 'YYYY-MM-DD'(后端 end 参数格式) */
|
||||
function fmtDashDate(ms: number): string {
|
||||
const dt = new Date(ms);
|
||||
return `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, '0')}-${String(dt.getDate()).padStart(2, '0')}`;
|
||||
}
|
||||
function onJumpInput() {
|
||||
jumpInput.value = jumpInput.value.replace(/\D/g, '').slice(0, 8);
|
||||
jumpErr.value = '';
|
||||
}
|
||||
function jumpToDate() {
|
||||
const ts = parseJumpDate(jumpInput.value.trim());
|
||||
if (ts == null) { jumpErr.value = '日期格式:20200218'; return; }
|
||||
jumpErr.value = '';
|
||||
// 非日K周期:先切回日K再跳(watcher 重拉时 load 会带上刚设好的锚点)
|
||||
if (timeframe.value !== '1d') { jumpTs.value = ts; setTimeframe('1d'); return; }
|
||||
// 快路径:目标日已在当前渲染窗口内 → 纯滚动居中,不打网络
|
||||
if (klineRef.value?.centerOn(ts)) { jumpTs.value = ts; return; }
|
||||
// 慢路径:目标日不在窗口内 → 以锚点为中点重拉一窗(end 不含当日,故右缘=锚点+170 自然日)
|
||||
jumpTs.value = ts;
|
||||
void load(active.value);
|
||||
}
|
||||
/** 清除锚点回到最新行情(锚定窗口的右缘停在锚点日之后,需要这个出口) */
|
||||
function clearJump() {
|
||||
jumpTs.value = null;
|
||||
jumpErr.value = '';
|
||||
void load(active.value);
|
||||
}
|
||||
/** DetailKLine 上报:锚点在拉回的数据里也找不到(早于上市首日,或晚于最后一根的未来日期)。
|
||||
* 统一走与「空数据」相同的回退:清锚点、提示、回最新行情,避免 chip/统计停留在假锚定状态。 */
|
||||
function onCenterMiss() {
|
||||
if (jumpTs.value == null) return;
|
||||
jumpTs.value = null;
|
||||
jumpErr.value = '该日期无K线(早于上市或晚于最新数据),已回到最新行情';
|
||||
void load(active.value);
|
||||
}
|
||||
|
||||
// ---------- 自选股(星标) ----------
|
||||
@@ -149,6 +199,110 @@ async function toggleWatch() {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 实盘交易点(交割单导入) ----------
|
||||
const trades = ref<UserTrade[]>([]);
|
||||
const showTrades = ref(true);
|
||||
const showTradeImport = ref(false);
|
||||
const importing = ref(false);
|
||||
const importResult = ref<TradesImportResponse | null>(null);
|
||||
const importErr = ref<string | null>(null);
|
||||
|
||||
/** 拉当前股的实盘成交(失败静默:未登录/网络异常都不影响看图)。
|
||||
* 与 load() 同款的请求序号:切股瞬间并发拉 K 线与成交,乱序返回的旧股
|
||||
* 成交绝不能回填——否则旧股买卖点会画到新股K线上。 */
|
||||
let tradesToken = 0;
|
||||
async function loadTrades(code: string) {
|
||||
const token = ++tradesToken;
|
||||
try {
|
||||
const list = await getTrades(code);
|
||||
if (token === tradesToken) trades.value = list;
|
||||
} catch {
|
||||
if (token === tradesToken) trades.value = [];
|
||||
}
|
||||
}
|
||||
watch(active, (code) => {
|
||||
trades.value = []; // 同步先清:新图挂载时(成交未返回)不能带着旧股标记
|
||||
loadTrades(code);
|
||||
}, { immediate: true });
|
||||
|
||||
const fmtQty = (q: number) =>
|
||||
q >= 10000 ? `${(q / 10000).toFixed(1).replace(/\.0$/, '')}万` : String(Math.round(q));
|
||||
const fmtPrice = (p: number) => p.toFixed(3).replace(/0+$/, '').replace(/\.$/, '');
|
||||
|
||||
/** 按日聚合成标记:图上只显示 B/S/T 单个字母(B=当日只买 贴 low 下方、S=当日只卖 贴 high 上方、
|
||||
* T=当日买+卖「做T」贴 high 上方);数量/均价/费用收进 rows,悬停字母时才显示。
|
||||
* 均价是券商原始成交价的股数加权均值(不复权口径,仅作参考——标记位置贴 bar 高低点,
|
||||
* 已随复权切换自动对齐)。 */
|
||||
const tradeMarkers = computed(() => {
|
||||
if (!showTrades.value) return [];
|
||||
const byDay = new Map<string, { ts: number; list: UserTrade[] }>();
|
||||
for (const t of trades.value) {
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(t.trade_date);
|
||||
if (!m) continue;
|
||||
let d = byDay.get(m[0]);
|
||||
if (!d) byDay.set(m[0], d = { ts: new Date(+m[1], +m[2] - 1, +m[3]).getTime(), list: [] });
|
||||
d.list.push(t);
|
||||
}
|
||||
const sumBy = (list: UserTrade[], f: (t: UserTrade) => number) => list.reduce((s, t) => s + f(t), 0);
|
||||
const dirRow = (label: string, list: UserTrade[], tone: 'buy' | 'sell') => {
|
||||
const qty = sumBy(list, (t) => t.qty);
|
||||
const wsum = sumBy(list, (t) => (t.price ?? 0) * t.qty);
|
||||
const wqty = sumBy(list, (t) => (t.price != null ? t.qty : 0));
|
||||
const avg = wqty > 0 ? wsum / wqty : null;
|
||||
return { label, text: `${fmtQty(qty)}股${avg != null ? ` @ ${fmtPrice(avg)}` : ''}`, tone };
|
||||
};
|
||||
return [...byDay.entries()].map(([date, d]) => {
|
||||
const buys = d.list.filter((t) => t.direction === 'buy');
|
||||
const sells = d.list.filter((t) => t.direction === 'sell');
|
||||
const kind: 'B' | 'S' | 'T' = buys.length && sells.length ? 'T' : buys.length ? 'B' : 'S';
|
||||
const rows: { label: string; text: string; tone: 'buy' | 'sell' | '' }[] = [
|
||||
...(buys.length ? [dirRow('买入', buys, 'buy')] : []),
|
||||
...(sells.length ? [dirRow('卖出', sells, 'sell')] : []),
|
||||
];
|
||||
const fee = sumBy(d.list, (t) => t.fee ?? 0);
|
||||
if (fee > 0) rows.push({ label: '费用', text: fmtPrice(fee), tone: '' });
|
||||
return { key: date, ts: d.ts, kind, rows };
|
||||
}).sort((a, b) => a.ts - b.ts);
|
||||
});
|
||||
|
||||
async function onTradeFile(e: Event) {
|
||||
const file = (e.target as HTMLInputElement).files?.[0];
|
||||
if (!file) return;
|
||||
importing.value = true;
|
||||
importResult.value = null;
|
||||
importErr.value = null;
|
||||
try {
|
||||
importResult.value = await importTrades(file);
|
||||
await loadTrades(active.value);
|
||||
} catch (err) {
|
||||
importErr.value = err instanceof Error ? err.message : '导入失败';
|
||||
} finally {
|
||||
importing.value = false;
|
||||
(e.target as HTMLInputElement).value = ''; // 允许重选同一文件
|
||||
}
|
||||
}
|
||||
|
||||
async function onClearTrades() {
|
||||
if (!window.confirm('确定清空全部股票的成交记录?此操作不可恢复(需重新导入交割单)。')) return;
|
||||
try {
|
||||
await clearTrades();
|
||||
trades.value = [];
|
||||
importResult.value = null;
|
||||
importErr.value = null;
|
||||
} catch (err) {
|
||||
importErr.value = err instanceof Error ? err.message : '清空失败';
|
||||
}
|
||||
}
|
||||
|
||||
/** 打开导入弹窗:清掉上一次的结果/错误,避免误读为本次操作的结果 */
|
||||
function openTradeImport() {
|
||||
importResult.value = null;
|
||||
importErr.value = null;
|
||||
showMaConfig.value = false;
|
||||
showTipConfig.value = false;
|
||||
showTradeImport.value = true;
|
||||
}
|
||||
|
||||
const filteredItems = computed(() => {
|
||||
const q = filter.value.trim().toLowerCase();
|
||||
if (!q) return props.items;
|
||||
@@ -176,17 +330,28 @@ const header = computed(() => {
|
||||
let fetchToken = 0;
|
||||
async function load(code: string) {
|
||||
const token = ++fetchToken;
|
||||
const anchor = jumpTs.value; // 跳转锚点:之后的所有重拉(复权/周期/MA)都围绕它取窗,视口位置不漂
|
||||
loading.value = true;
|
||||
error.value = null;
|
||||
data.value = null;
|
||||
try {
|
||||
const res = await getStockPreview(code, {
|
||||
limit: 500,
|
||||
// 锚定取数:窗口右缘=锚点+170 自然日(后端 end 不含当日),锚点恰好落在 240 根首吐窗口正中
|
||||
end: anchor != null ? fmtDashDate(anchor + JUMP_END_DAYS * 86400000) : undefined,
|
||||
adjust: adjust.value,
|
||||
timeframe: timeframe.value,
|
||||
mas: maPeriods.value,
|
||||
});
|
||||
if (token === fetchToken) data.value = res;
|
||||
if (token !== fetchToken) return;
|
||||
if (anchor != null && res.candles.length === 0) {
|
||||
// 跳转日期早于上市等:锚定窗口取不到任何K线 → 退回最新行情
|
||||
jumpTs.value = null;
|
||||
jumpErr.value = '该日期无数据(可能早于上市),已回到最新行情';
|
||||
void load(code);
|
||||
return;
|
||||
}
|
||||
data.value = res;
|
||||
} catch (e) {
|
||||
if (token === fetchToken) error.value = e instanceof Error ? e.message : '加载失败';
|
||||
} finally {
|
||||
@@ -211,7 +376,13 @@ async function loadOlder(end: string, count: number) {
|
||||
return null; // 网络失败:图表停止向前翻页(不中断已渲染内容)
|
||||
}
|
||||
}
|
||||
watch(active, (code) => load(code), { immediate: true });
|
||||
watch(active, (code) => {
|
||||
// 切股清空日期锚点:新股票以最新行情打开
|
||||
jumpTs.value = null;
|
||||
jumpErr.value = '';
|
||||
load(code);
|
||||
emit('change', code); // 父组件把当前股写进路由,刷新后可还原
|
||||
}, { immediate: true });
|
||||
watch(adjust, () => load(active.value));
|
||||
watch(timeframe, () => load(active.value));
|
||||
// MA 周期变化也要重拉(后端按 mas 计算指标序列)
|
||||
@@ -236,10 +407,14 @@ function onKeydown(e: KeyboardEvent) {
|
||||
if (e.isComposing) return;
|
||||
const t = e.target as HTMLElement | null;
|
||||
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;
|
||||
// 弹层打开时接管按键:Esc 关弹层,其余(含 ↑/↓)不再切换底层个股
|
||||
const modalOpen = showTradeImport.value || showMaConfig.value || showTipConfig.value;
|
||||
if (e.key === 'Escape') {
|
||||
if (showMaConfig.value || showTipConfig.value) { showMaConfig.value = false; showTipConfig.value = false; }
|
||||
if (showTradeImport.value) showTradeImport.value = false;
|
||||
else if (showMaConfig.value || showTipConfig.value) { showMaConfig.value = false; showTipConfig.value = false; }
|
||||
else emit('close');
|
||||
}
|
||||
else if (modalOpen) return;
|
||||
else if (e.key === 'ArrowUp') { e.preventDefault(); moveActive(-1); }
|
||||
else if (e.key === 'ArrowDown') { e.preventDefault(); moveActive(1); }
|
||||
}
|
||||
@@ -254,7 +429,8 @@ onBeforeUnmount(() => {
|
||||
|
||||
// ---------- 右侧信息栏增强:52周高低 / 年初至今(从日线序列算,无数据留空) ----------
|
||||
const stats = computed(() => {
|
||||
const bars = timeframe.value === '1d' ? data.value?.candles : null;
|
||||
// 日期跳转后窗口是历史段,52周/年初至今口径失真,直接不显示
|
||||
const bars = timeframe.value === '1d' && jumpTs.value == null ? data.value?.candles : null;
|
||||
if (!bars || bars.length === 0) return { high52: null, low52: null, ytd: null };
|
||||
const last = bars[bars.length - 1];
|
||||
const lastTs = new Date(last.ts);
|
||||
@@ -333,18 +509,8 @@ const fmtListDate = (s?: string | null) => (s && s.length === 8 ? `${s.slice(0,
|
||||
@click="setAdjust(a.key)"
|
||||
>{{ a.label }}</button>
|
||||
</div>
|
||||
<span v-if="data?.source === 'market'" class="rounded bg-amber-500/15 px-2 py-0.5 text-xs text-amber-300">
|
||||
近段未复权数据
|
||||
</span>
|
||||
<span
|
||||
v-else-if="data"
|
||||
class="rounded px-2 py-0.5 text-xs"
|
||||
:class="data.source === adjust ? 'bg-blue-500/15 text-blue-300' : 'bg-amber-500/15 text-amber-300'"
|
||||
:title="data.source === adjust ? '' : '该股复权因子缺失,暂按此口径显示(可先同步市场数据)'"
|
||||
>{{ sourceLabel }}</span>
|
||||
|
||||
<span class="ml-auto text-[13px] text-[#9BA3AE]">↑↓ 切换 · Esc 关闭 · 滚轮缩放 · 左滑加载历史</span>
|
||||
<button type="button" class="btn-ghost !px-2.5 !py-1" title="关闭 (Esc)" @click="emit('close')">
|
||||
<button type="button" class="btn-ghost !px-2.5 !py-1 ml-auto cursor-pointer" 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>
|
||||
@@ -399,7 +565,7 @@ const fmtListDate = (s?: string | null) => (s && s.length === 8 ? `${s.slice(0,
|
||||
:class="subPanes.includes(s.key)
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'bg-[#101014] text-[#9BA3AE] line-through'"
|
||||
:title="subPanes.includes(s.key) ? '点击隐藏 · 拖动排序 · 右侧按钮调高度' : '点击显示'"
|
||||
:title="subPanes.includes(s.key) ? '点击隐藏 · 拖动排序 · 图内分隔线拖拽调高度' : '点击显示'"
|
||||
@click="toggleSub(s.key)"
|
||||
@dragstart="onDragStart($event, s.key)"
|
||||
@dragover.prevent
|
||||
@@ -407,10 +573,6 @@ const fmtListDate = (s?: string | null) => (s && s.length === 8 ? `${s.slice(0,
|
||||
>
|
||||
{{ s.label }}
|
||||
</button>
|
||||
<template v-if="subPanes.includes(s.key)">
|
||||
<button type="button" class="border-l px-1 py-1 text-xs text-[#9BA3AE] hover:bg-[#1E2026] hover:text-[#E8EAED]" title="调高" @click="adjustHeight(s.key, 20)">▲</button>
|
||||
<button type="button" class="border-l px-1 py-1 text-xs text-[#9BA3AE] hover:bg-[#1E2026] hover:text-[#E8EAED]" title="调矮" @click="adjustHeight(s.key, -20)">▼</button>
|
||||
</template>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
@@ -419,6 +581,20 @@ const fmtListDate = (s?: string | null) => (s && s.length === 8 ? `${s.slice(0,
|
||||
title="主图叠加布林带"
|
||||
@click="showBoll = !showBoll"
|
||||
>BOLL</button>
|
||||
<!-- 实盘交易点:交割单导入的买卖标记 -->
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md border px-2.5 py-1 text-[13px] transition-colors"
|
||||
:class="showTrades && trades.length ? 'border-amber-500 bg-amber-500 text-white' : 'border-[#26272E] bg-[#101014] text-[#9BA3AE]'"
|
||||
:title="trades.length ? `本股实盘成交 ${trades.length} 笔(交割单导入)` : '本股暂无实盘成交记录,点击导入交割单'"
|
||||
@click="trades.length ? (showTrades = !showTrades) : openTradeImport()"
|
||||
>交易点{{ trades.length ? ` ${trades.length}` : '' }}</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md border border-[#26272E] bg-[#101014] px-2.5 py-1 text-[13px] text-[#A8AFB8] transition-colors hover:border-[#3A3D46] hover:text-[#E8EAED]"
|
||||
title="上传券商交割单,导入实盘买卖点"
|
||||
@click="openTradeImport()"
|
||||
>导入交割单</button>
|
||||
<!-- MA 配置 -->
|
||||
<div class="relative">
|
||||
<button
|
||||
@@ -478,13 +654,40 @@ const fmtListDate = (s?: string | null) => (s && s.length === 8 ? `${s.slice(0,
|
||||
{{ f.label }}
|
||||
</label>
|
||||
</div>
|
||||
<div class="mt-2 flex items-center justify-between">
|
||||
<span class="text-xs text-[#9BA3AE]">已选 {{ tooltipFields.length }}/{{ TOOLTIP_FIELDS.length }}(首行日期固定)</span>
|
||||
<button type="button" class="text-xs text-blue-600 hover:underline" @click="resetTipFields">恢复默认</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<span class="ml-auto text-xs text-[#9BA3AE]">点击开关 · 拖动排序 · ▲▼调高度 · 右上工具栏画线</span>
|
||||
<!-- 日期跳转:输入 YYYYMMDD,该日K线居中显示 -->
|
||||
<div class="ml-auto flex items-center gap-1.5">
|
||||
<span class="text-xs text-[#9BA3AE]">定位</span>
|
||||
<div class="flex items-stretch">
|
||||
<input
|
||||
v-model="jumpInput"
|
||||
type="text"
|
||||
class="w-24 rounded-l-md border border-[#26272E] bg-[#16181D] px-2 py-1 font-mono text-[13px] text-[#E8EAED] outline-none transition-colors placeholder:text-[#7A818C]"
|
||||
:class="jumpErr ? 'border-red-500' : 'focus:border-blue-500'"
|
||||
placeholder="20200218"
|
||||
maxlength="8"
|
||||
inputmode="numeric"
|
||||
title="输入日期(YYYYMMDD),跳转后该日K线居中显示"
|
||||
@input="onJumpInput"
|
||||
@keyup.enter="jumpToDate"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-r-md border border-l-0 border-[#26272E] bg-[#101014] px-2 py-1 text-[13px] text-[#A8AFB8] transition-colors hover:border-[#3A3D46] hover:text-[#E8EAED]"
|
||||
title="跳转到该日期的日K(回车亦可)"
|
||||
@click="jumpToDate"
|
||||
>跳转</button>
|
||||
</div>
|
||||
<button
|
||||
v-if="jumpTs != null"
|
||||
type="button"
|
||||
class="rounded-md border border-blue-500/60 bg-blue-500/10 px-2 py-1 font-mono text-xs text-blue-300 transition-colors hover:bg-blue-500/20"
|
||||
title="清除日期锚点,回到最新行情"
|
||||
@click="clearJump"
|
||||
>{{ fmtDashDate(jumpTs) }} ✕</button>
|
||||
<span v-if="jumpErr" class="text-xs text-red-400">{{ jumpErr }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 图表 -->
|
||||
@@ -496,6 +699,7 @@ const fmtListDate = (s?: string | null) => (s && s.length === 8 ? `${s.slice(0,
|
||||
<div v-else-if="error" class="flex h-full items-center justify-center text-sm text-red-400">{{ error }}</div>
|
||||
<DetailKLine
|
||||
v-else-if="data && data.candles.length"
|
||||
ref="klineRef"
|
||||
:ticker="data.ts_code"
|
||||
:candles="data.candles"
|
||||
:indicators="data.indicators"
|
||||
@@ -507,6 +711,9 @@ const fmtListDate = (s?: string | null) => (s && s.length === 8 ? `${s.slice(0,
|
||||
:show-boll="showBoll"
|
||||
:timeframe="timeframe"
|
||||
:tooltip-fields="tooltipFields"
|
||||
:center-ts="jumpTs"
|
||||
:trade-markers="tradeMarkers"
|
||||
@center-miss="onCenterMiss"
|
||||
/>
|
||||
<div v-else class="flex h-full items-center justify-center text-sm text-[#9BA3AE]">无数据</div>
|
||||
</div>
|
||||
@@ -577,5 +784,64 @@ const fmtListDate = (s?: string | null) => (s && s.length === 8 ? `${s.slice(0,
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<!-- 交割单导入弹窗 -->
|
||||
<div
|
||||
v-if="showTradeImport"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4"
|
||||
@click.self="showTradeImport = false"
|
||||
>
|
||||
<div class="w-full max-w-md rounded-lg border border-[#33353D] bg-[#16181D] p-4 shadow-2xl shadow-black/70">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-sm font-semibold text-[#E8EAED]">导入交割单(实盘买卖点)</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded p-1 text-[#9BA3AE] transition-colors hover:bg-[#26272E] hover:text-white"
|
||||
title="关闭 (Esc)"
|
||||
@click="showTradeImport = false"
|
||||
>
|
||||
<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>
|
||||
</div>
|
||||
<p class="mt-2 text-xs leading-5 text-[#9BA3AE]">
|
||||
上传券商导出的交割单(江海证券通达信版:「查询 → 交割单 → 输出」;App/同花顺版:「交割单 → 导出/发送邮箱」)。
|
||||
CSV / Excel / txt / HTML 均可,编码与列名自动识别;同日成交合并为一个标注(B=买入、S=卖出、T=当日买卖都有),鼠标悬停字母可查看数量与均价。
|
||||
</p>
|
||||
<label
|
||||
class="mt-3 flex cursor-pointer flex-col items-center justify-center rounded-lg border border-dashed px-4 py-6 text-center transition-colors"
|
||||
:class="importing ? 'border-[#26272E] opacity-60' : 'border-[#3A3D46] hover:border-blue-500/60'"
|
||||
>
|
||||
<span class="text-[13px] text-[#C3C9D2]">{{ importing ? '解析导入中…' : '点击选择交割单文件' }}</span>
|
||||
<span class="mt-1 text-xs text-[#7A818C]">支持 .csv / .txt / .xls / .xlsx / .html,20MB 以内</span>
|
||||
<input
|
||||
type="file"
|
||||
class="hidden"
|
||||
accept=".csv,.txt,.xls,.xlsx,.htm,.html"
|
||||
:disabled="importing"
|
||||
@change="onTradeFile"
|
||||
/>
|
||||
</label>
|
||||
<!-- 导入结果反馈 -->
|
||||
<div v-if="importResult" class="mt-3 rounded-md border border-blue-500/30 bg-blue-500/10 p-2.5 text-xs leading-5 text-[#C3C9D2]">
|
||||
<div>
|
||||
新增 <span class="font-semibold text-blue-300">{{ importResult.inserted }}</span> 笔成交,覆盖 {{ importResult.stocks }} 只股票;
|
||||
重复跳过 {{ importResult.skipped_dup }} 笔,其他跳过 {{ importResult.skipped_other }} 笔。
|
||||
</div>
|
||||
<div v-if="importResult.bad.length" class="mt-1 text-red-400">
|
||||
{{ importResult.bad.join(';') }}
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="importErr" class="mt-3 rounded-md border border-red-500/40 bg-red-500/10 p-2.5 text-xs text-red-400">{{ importErr }}</div>
|
||||
<!-- 危险操作:清空(作用于全部股票,不随当前股是否有成交隐藏入口) -->
|
||||
<div class="mt-3 flex items-center justify-between border-t border-[#1E2026] pt-3">
|
||||
<span class="text-xs text-[#7A818C]">清空全部股票的成交记录,K 线买卖点将全部消失</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md border border-red-500/50 px-2.5 py-1 text-[13px] text-red-400 transition-colors hover:bg-red-500/15"
|
||||
@click="onClearTrades"
|
||||
>清空全部成交记录</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
207
frontend/src/stores/settings.ts
Normal file
207
frontend/src/stores/settings.ts
Normal file
@@ -0,0 +1,207 @@
|
||||
import { computed, ref, watchEffect } from 'vue';
|
||||
import { defineStore } from 'pinia';
|
||||
import { getPreferences, putPreferences } from '@/api/client';
|
||||
import type { ChartLayoutPrefs, TooltipField } from '@/api/types';
|
||||
|
||||
export type PriceTone = 'red-up' | 'green-up';
|
||||
export type PriceAdjust = 'bfq' | 'qfq' | 'hfq';
|
||||
|
||||
const STORAGE_KEY = 'stock.settings.priceTone';
|
||||
const ADJUST_KEY = 'stock.settings.priceAdjust';
|
||||
const LAYOUT_KEY = 'stock.settings.chartLayout';
|
||||
const RED = '#FE354B';
|
||||
const GREEN = '#1EBE72';
|
||||
|
||||
export const DEFAULT_MA_PERIODS = [5, 10, 20, 60];
|
||||
export const DEFAULT_SUB_PANES = ['vol', 'macd', 'kdj'];
|
||||
|
||||
/** K线浮层指标目录(展示顺序即目录顺序,设置弹层与浮层渲染共用) */
|
||||
export const TOOLTIP_FIELDS: { key: TooltipField; label: string }[] = [
|
||||
{ key: 'open', label: '开盘价' },
|
||||
{ key: 'high', label: '最高价' },
|
||||
{ key: 'low', label: '最低价' },
|
||||
{ key: 'close', label: '收盘价' },
|
||||
{ key: 'diff', label: '涨跌' },
|
||||
{ key: 'chg', label: '涨幅' },
|
||||
{ key: 'amp', label: '振幅' },
|
||||
{ key: 'vol', label: '总量' },
|
||||
{ key: 'amount', label: '总额' },
|
||||
{ key: 'turnover', label: '换手' },
|
||||
];
|
||||
const TIP_VALID = new Set(TOOLTIP_FIELDS.map((f) => f.key));
|
||||
export const DEFAULT_TOOLTIP_FIELDS: TooltipField[] = TOOLTIP_FIELDS.map((f) => f.key);
|
||||
|
||||
/** 过滤为合法指标 key;非数组返回 undefined(调用方决定回退),空数组合法=仅显示日期头 */
|
||||
function normTipFields(v: unknown): TooltipField[] | undefined {
|
||||
if (!Array.isArray(v)) return undefined;
|
||||
return v.filter((k): k is TooltipField => typeof k === 'string' && TIP_VALID.has(k as TooltipField));
|
||||
}
|
||||
|
||||
function loadTone(): PriceTone {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (raw === 'red-up' || raw === 'green-up') return raw;
|
||||
} catch { /* localStorage 不可用时用默认值 */ }
|
||||
return 'red-up'; // A股默认红涨绿跌
|
||||
}
|
||||
|
||||
function loadAdjust(): PriceAdjust {
|
||||
try {
|
||||
const raw = localStorage.getItem(ADJUST_KEY);
|
||||
if (raw === 'bfq' || raw === 'qfq' || raw === 'hfq') return raw;
|
||||
} catch { /* ignore */ }
|
||||
return 'qfq';
|
||||
}
|
||||
|
||||
function loadLayout(): ChartLayoutPrefs {
|
||||
try {
|
||||
const raw = localStorage.getItem(LAYOUT_KEY);
|
||||
if (raw) {
|
||||
const v = JSON.parse(raw) as ChartLayoutPrefs;
|
||||
if (Array.isArray(v.maPeriods) && Array.isArray(v.subPanes)) {
|
||||
return {
|
||||
...v,
|
||||
subHeights: v.subHeights ?? {},
|
||||
tooltipFields: normTipFields(v.tooltipFields) ?? DEFAULT_TOOLTIP_FIELDS,
|
||||
};
|
||||
}
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
return { maPeriods: DEFAULT_MA_PERIODS, subPanes: DEFAULT_SUB_PANES, subHeights: {}, tooltipFields: DEFAULT_TOOLTIP_FIELDS };
|
||||
}
|
||||
|
||||
function saveLocal(key: string, value: string) {
|
||||
try { localStorage.setItem(key, value); } catch { /* 忽略持久化失败 */ }
|
||||
}
|
||||
|
||||
// 未成功推送到服务端的本地改动(key 集合)。持久化到 localStorage,
|
||||
// 页面刷新后仍能让下次登录时“本地优先”,避免旧服务端存档覆盖离线期间的修改
|
||||
const DIRTY_KEY = 'stock.settings.dirty';
|
||||
|
||||
function loadDirty(): Set<string> {
|
||||
try {
|
||||
const raw = localStorage.getItem(DIRTY_KEY);
|
||||
const v = raw ? JSON.parse(raw) : [];
|
||||
return new Set(Array.isArray(v) ? v.filter((k): k is string => typeof k === 'string') : []);
|
||||
} catch { return new Set(); }
|
||||
}
|
||||
|
||||
/** 用户偏好:localStorage 即时缓存 + 登录后与 user_preferences 表防抖同步 */
|
||||
export const useSettingsStore = defineStore('settings', () => {
|
||||
const priceTone = ref<PriceTone>(loadTone());
|
||||
|
||||
const upHex = computed(() => (priceTone.value === 'red-up' ? RED : GREEN));
|
||||
const downHex = computed(() => (priceTone.value === 'red-up' ? GREEN : RED));
|
||||
|
||||
// 运行时覆盖 Tailwind 主题变量,text-up / text-down 全站即时生效
|
||||
watchEffect(() => {
|
||||
const root = document.documentElement.style;
|
||||
root.setProperty('--color-up', upHex.value);
|
||||
root.setProperty('--color-down', downHex.value);
|
||||
});
|
||||
|
||||
// ---------- 服务端同步(未登录时静默跳过) ----------
|
||||
const synced = ref(false);
|
||||
let pushTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const pending: Record<string, unknown> = {};
|
||||
const dirty = loadDirty();
|
||||
|
||||
function markDirty(keys: string[]) {
|
||||
let changed = false;
|
||||
for (const k of keys) if (!dirty.has(k)) { dirty.add(k); changed = true; }
|
||||
if (changed) saveLocal(DIRTY_KEY, JSON.stringify([...dirty]));
|
||||
}
|
||||
function clearDirty(keys: string[]) {
|
||||
let changed = false;
|
||||
for (const k of keys) if (dirty.delete(k)) changed = true;
|
||||
if (changed) saveLocal(DIRTY_KEY, JSON.stringify([...dirty]));
|
||||
}
|
||||
|
||||
function schedulePush(key: string, value: unknown) {
|
||||
pending[key] = value;
|
||||
markDirty([key]); // 推送确认成功前视为脏,失败/离线期间不被旧档冲掉
|
||||
if (pushTimer) clearTimeout(pushTimer);
|
||||
pushTimer = setTimeout(async () => {
|
||||
const batch = { ...pending };
|
||||
for (const k of Object.keys(batch)) delete pending[k];
|
||||
try {
|
||||
await putPreferences(batch);
|
||||
clearDirty(Object.keys(batch));
|
||||
} catch { /* 未登录/离线:localStorage 已兜底,dirty 保留待下次登录重推 */ }
|
||||
}, 800);
|
||||
}
|
||||
|
||||
/** 登出/会话失效时调用:允许下一次登录重新拉取该账号的偏好 */
|
||||
function invalidateSync() {
|
||||
synced.value = false;
|
||||
}
|
||||
|
||||
/** 登录成功后调用:有未推送本地修改的 key 以本地为准并重推,其余采用服务端存档 */
|
||||
async function syncFromServer() {
|
||||
if (synced.value) return;
|
||||
synced.value = true;
|
||||
try {
|
||||
const prefs = await getPreferences();
|
||||
if (dirty.has('priceTone')) {
|
||||
schedulePush('priceTone', priceTone.value);
|
||||
} else if (typeof prefs.priceTone === 'string' && prefs.priceTone !== priceTone.value) {
|
||||
priceTone.value = prefs.priceTone as PriceTone;
|
||||
saveLocal(STORAGE_KEY, prefs.priceTone);
|
||||
} else if (prefs.priceTone === undefined) {
|
||||
schedulePush('priceTone', priceTone.value);
|
||||
}
|
||||
if (dirty.has('priceAdjust')) {
|
||||
schedulePush('priceAdjust', priceAdjust.value);
|
||||
} else if (typeof prefs.priceAdjust === 'string' && prefs.priceAdjust !== priceAdjust.value) {
|
||||
priceAdjust.value = prefs.priceAdjust as PriceAdjust;
|
||||
saveLocal(ADJUST_KEY, prefs.priceAdjust);
|
||||
} else if (prefs.priceAdjust === undefined) {
|
||||
schedulePush('priceAdjust', priceAdjust.value);
|
||||
}
|
||||
if (dirty.has('chartLayout')) {
|
||||
schedulePush('chartLayout', chartLayout.value);
|
||||
} else if (prefs.chartLayout && typeof prefs.chartLayout === 'object') {
|
||||
const v = prefs.chartLayout as ChartLayoutPrefs;
|
||||
if (Array.isArray(v.maPeriods) && Array.isArray(v.subPanes)) {
|
||||
// 服务端存档早于浮层配置(无 tooltipFields)时保留本地选择,避免旧档案冲掉
|
||||
const tip = normTipFields(v.tooltipFields) ?? chartLayout.value.tooltipFields;
|
||||
chartLayout.value = { ...v, subHeights: v.subHeights ?? {}, tooltipFields: tip };
|
||||
saveLocal(LAYOUT_KEY, JSON.stringify(chartLayout.value));
|
||||
}
|
||||
} else {
|
||||
schedulePush('chartLayout', chartLayout.value);
|
||||
}
|
||||
} catch { /* 未登录:仅本地 */ }
|
||||
}
|
||||
|
||||
function setPriceTone(tone: PriceTone) {
|
||||
priceTone.value = tone;
|
||||
saveLocal(STORAGE_KEY, tone);
|
||||
schedulePush('priceTone', tone);
|
||||
}
|
||||
|
||||
// K线复权模式(个股详情默认口径;浮层内切换会回写此处)
|
||||
const priceAdjust = ref<PriceAdjust>(loadAdjust());
|
||||
|
||||
function setPriceAdjust(adj: PriceAdjust) {
|
||||
priceAdjust.value = adj;
|
||||
saveLocal(ADJUST_KEY, adj);
|
||||
schedulePush('priceAdjust', adj);
|
||||
}
|
||||
|
||||
// ---------- 看股页图表布局(MA 周期 / 副图顺序 / 副图高度) ----------
|
||||
const chartLayout = ref<ChartLayoutPrefs>(loadLayout());
|
||||
|
||||
function setChartLayout(patch: Partial<ChartLayoutPrefs>) {
|
||||
chartLayout.value = { ...chartLayout.value, ...patch };
|
||||
saveLocal(LAYOUT_KEY, JSON.stringify(chartLayout.value));
|
||||
schedulePush('chartLayout', chartLayout.value);
|
||||
}
|
||||
|
||||
return {
|
||||
priceTone, upHex, downHex, setPriceTone,
|
||||
priceAdjust, setPriceAdjust,
|
||||
chartLayout, setChartLayout,
|
||||
syncFromServer, invalidateSync,
|
||||
};
|
||||
});
|
||||
412
frontend/src/views/StocksView.vue
Normal file
412
frontend/src/views/StocksView.vue
Normal file
@@ -0,0 +1,412 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { addWatchlist, getStockFacets, getStocks, removeWatchlist } from '@/api/client';
|
||||
import type { FacetItem, ScreenerItemOut, StockListItem } from '@/api/types';
|
||||
import StockDetailOverlay from '@/components/StockDetailOverlay.vue';
|
||||
|
||||
// ---------- 筛选状态(初始值从路由 query 还原,刷新/分享链接不丢现场) ----------
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
function qStr(key: string): string | undefined {
|
||||
const v = route.query[key];
|
||||
return typeof v === 'string' && v ? v : undefined;
|
||||
}
|
||||
|
||||
const MARKETS = ['全部', '自选', '主板', '创业板', '科创板', '北交所'];
|
||||
// 排序键(后端白名单:symbol/total_mv/circ_mv/pe_ttm/pb/turnover_rate)
|
||||
const SORT_KEYS = ['symbol', 'total_mv', 'circ_mv', 'pe_ttm', 'pb', 'turnover_rate'] as const;
|
||||
type SortKey = (typeof SORT_KEYS)[number];
|
||||
|
||||
const search = ref(qStr('q') ?? '');
|
||||
const market = ref(MARKETS.includes(qStr('market') ?? '') ? (qStr('market') as string) : '全部');
|
||||
const industry = ref(qStr('industry') ?? '');
|
||||
const area = ref(qStr('area') ?? '');
|
||||
const industries = ref<FacetItem[]>([]);
|
||||
const areas = ref<FacetItem[]>([]);
|
||||
const pageSize = 100;
|
||||
const page = ref(Math.max(1, parseInt(qStr('page') ?? '1', 10) || 1));
|
||||
const sortParam = qStr('sort');
|
||||
const sort = ref<SortKey>(SORT_KEYS.includes((sortParam ?? 'symbol') as SortKey) ? ((sortParam ?? 'symbol') as SortKey) : 'symbol');
|
||||
const order = ref<'asc' | 'desc'>(qStr('order') === 'desc' ? 'desc' : 'asc');
|
||||
|
||||
// 列表状态
|
||||
const items = ref<StockListItem[]>([]);
|
||||
const total = ref(0);
|
||||
const loading = ref(false);
|
||||
const error = ref<string | null>(null);
|
||||
|
||||
// 详情浮层(当前股记录在 ?code=,刷新后浮层自动重开)
|
||||
const previewCode = ref<string | null>(qStr('code') ?? null);
|
||||
|
||||
// StockDetailOverlay 需要 ScreenerItemOut 形状;行情字段缺失时它内部有兜底
|
||||
const overlayItems = computed<ScreenerItemOut[]>(() =>
|
||||
items.value.map((it) => ({
|
||||
ts_code: it.ts_code,
|
||||
name: it.name,
|
||||
close: it.close ?? null,
|
||||
pct_chg: it.pct_chg ?? null,
|
||||
total_mv: null,
|
||||
circ_mv: null,
|
||||
pe_ttm: null,
|
||||
pb: null,
|
||||
turnover_rate: null,
|
||||
indicators: {},
|
||||
})),
|
||||
);
|
||||
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize)));
|
||||
|
||||
// ---------- 加载(搜索防抖) ----------
|
||||
let fetchToken = 0;
|
||||
let debounceTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
async function load() {
|
||||
const token = ++fetchToken;
|
||||
loading.value = true;
|
||||
error.value = null;
|
||||
try {
|
||||
const res = await getStocks({
|
||||
search: search.value.trim(),
|
||||
// 「自选」不是 stock_basic.market 的值,走 watched_only
|
||||
market: market.value === '全部' || market.value === '自选' ? '' : market.value,
|
||||
watched_only: market.value === '自选',
|
||||
industry: industry.value,
|
||||
area: area.value,
|
||||
sort: sort.value,
|
||||
order: order.value,
|
||||
limit: pageSize,
|
||||
offset: (page.value - 1) * pageSize,
|
||||
});
|
||||
if (token === fetchToken) {
|
||||
items.value = res.items;
|
||||
total.value = res.total;
|
||||
}
|
||||
} catch (e) {
|
||||
if (token === fetchToken) error.value = e instanceof Error ? e.message : '加载失败';
|
||||
} finally {
|
||||
if (token === fetchToken) loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
watch(search, () => {
|
||||
clearTimeout(debounceTimer);
|
||||
debounceTimer = setTimeout(() => {
|
||||
page.value = 1;
|
||||
load();
|
||||
}, 300);
|
||||
});
|
||||
|
||||
// 筛选/排序变化回到第一页(page 的 watch 会再触发 load);翻页直接加载
|
||||
watch([market, industry, area, sort, order], () => {
|
||||
if (page.value !== 1) page.value = 1;
|
||||
else load();
|
||||
});
|
||||
watch(page, () => load());
|
||||
load();
|
||||
getStockFacets()
|
||||
.then((f) => {
|
||||
industries.value = f.industries;
|
||||
areas.value = f.areas;
|
||||
})
|
||||
.catch(() => { /* 筛选项加载失败不阻塞列表 */ });
|
||||
onBeforeUnmount(() => clearTimeout(debounceTimer));
|
||||
|
||||
function pctClass(v: number | null | undefined): string {
|
||||
if (v == null) return 'text-[#9BA3AE]';
|
||||
return v > 0 ? 'text-up' : v < 0 ? 'text-down' : 'text-[#A8AFB8]';
|
||||
}
|
||||
|
||||
function fmtPct(v: number | null | undefined): string {
|
||||
if (v == null) return '--';
|
||||
return `${v > 0 ? '+' : ''}${v.toFixed(2)}%`;
|
||||
}
|
||||
|
||||
function fmtDate(v: string | null | undefined): string {
|
||||
if (!v) return '--';
|
||||
return v.slice(0, 10);
|
||||
}
|
||||
|
||||
function fmtNum(v: number | null | undefined, digits = 2): string {
|
||||
if (v == null) return '--';
|
||||
return v.toFixed(digits);
|
||||
}
|
||||
|
||||
function fmtYi(v: number | null | undefined): string {
|
||||
if (v == null) return '--';
|
||||
return v >= 100 ? Math.round(v).toLocaleString() : v.toFixed(2);
|
||||
}
|
||||
|
||||
function fmtTurnover(v: number | null | undefined): string {
|
||||
if (v == null) return '--';
|
||||
return `${v.toFixed(2)}%`;
|
||||
}
|
||||
|
||||
// ---------- 列排序(后端白名单键) ----------
|
||||
function toggleSort(key: SortKey) {
|
||||
if (sort.value === key) {
|
||||
order.value = order.value === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
sort.value = key;
|
||||
// 代码列默认升序;其余(市值/估值/换手)默认降序——先看最大/最热
|
||||
order.value = key === 'symbol' ? 'asc' : 'desc';
|
||||
}
|
||||
}
|
||||
|
||||
// PE-TTM 分档着色:≤15 冷绿、15-30 中性、30-60 琥珀、>60 红;亏损/无数据灰
|
||||
function peClass(v: number | null | undefined): string {
|
||||
if (v == null || v <= 0) return 'text-[#9BA3AE]';
|
||||
if (v <= 15) return 'text-emerald-400';
|
||||
if (v <= 30) return 'text-[#A8AFB8]';
|
||||
if (v <= 60) return 'text-amber-400';
|
||||
return 'text-red-400';
|
||||
}
|
||||
|
||||
function go(delta: number) {
|
||||
const next = page.value + delta;
|
||||
if (next >= 1 && next <= totalPages.value) page.value = next;
|
||||
}
|
||||
|
||||
// ---------- 自选股星标(服务端为唯一事实源,本地行内即时翻转) ----------
|
||||
const starBusy = ref('');
|
||||
async function toggleStar(it: StockListItem) {
|
||||
if (starBusy.value === it.ts_code) return;
|
||||
starBusy.value = it.ts_code;
|
||||
const wasWatched = it.watched;
|
||||
it.watched = !wasWatched; // 乐观更新
|
||||
try {
|
||||
const list = wasWatched ? await removeWatchlist(it.ts_code) : await addWatchlist(it.ts_code);
|
||||
const set = new Set(list);
|
||||
for (const row of items.value) row.watched = set.has(row.ts_code);
|
||||
} catch {
|
||||
it.watched = wasWatched; // 回滚
|
||||
} finally {
|
||||
starBusy.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
// 详情浮层里增删自选后,刷新当前页星标
|
||||
function onWatchedChange() {
|
||||
load();
|
||||
}
|
||||
|
||||
// ---------- 路由同步:状态 → ?q/&market/…(replace 不产生历史记录) ----------
|
||||
function buildQuery(): Record<string, string> {
|
||||
const q: Record<string, string> = {};
|
||||
if (search.value.trim()) q.q = search.value.trim();
|
||||
if (market.value !== '全部') q.market = market.value;
|
||||
if (industry.value) q.industry = industry.value;
|
||||
if (area.value) q.area = area.value;
|
||||
if (sort.value !== 'symbol') q.sort = sort.value;
|
||||
if (order.value !== 'asc') q.order = order.value;
|
||||
if (page.value > 1) q.page = String(page.value);
|
||||
if (previewCode.value) q.code = previewCode.value;
|
||||
return q;
|
||||
}
|
||||
|
||||
let selfNav = 0; // 自己发起的导航在途数量:其 route 变化不回灌状态(防输入被旧 URL 覆盖)
|
||||
function syncRoute(push = false) {
|
||||
const query = buildQuery();
|
||||
// 与当前 URL 一致就跳过,避免 state→route→state 回声
|
||||
if (JSON.stringify(query) === JSON.stringify(route.query)) return;
|
||||
selfNav++;
|
||||
const done = () => { selfNav--; };
|
||||
void (push ? router.push({ query }) : router.replace({ query })).then(done, done);
|
||||
}
|
||||
|
||||
// 列表状态变化(含搜索防抖外的输入)随手回写 URL;翻页/筛选也带着当前 ?code
|
||||
watch([search, market, industry, area, sort, order, page], () => syncRoute());
|
||||
|
||||
// 浏览器前进/后退(含返回键关掉 ?code=):把 query 应用回状态
|
||||
watch(() => route.query, (q) => {
|
||||
if (selfNav > 0) return;
|
||||
const qOf = (k: string) => (typeof q[k] === 'string' ? (q[k] as string) : '');
|
||||
search.value = qOf('q');
|
||||
market.value = MARKETS.includes(qOf('market')) ? qOf('market') : '全部';
|
||||
industry.value = qOf('industry');
|
||||
area.value = qOf('area');
|
||||
const p = parseInt(qOf('page'), 10);
|
||||
page.value = Number.isFinite(p) && p >= 1 ? p : 1;
|
||||
const s = qOf('sort');
|
||||
sort.value = SORT_KEYS.includes(s as SortKey) ? (s as SortKey) : 'symbol';
|
||||
order.value = qOf('order') === 'desc' ? 'desc' : 'asc';
|
||||
previewCode.value = qOf('code') || null;
|
||||
});
|
||||
|
||||
// ---------- 详情浮层开关(写入 ?code=) ----------
|
||||
function openStock(code: string) {
|
||||
previewCode.value = code;
|
||||
syncRoute(true); // push:浏览器返回键 = 关闭浮层
|
||||
}
|
||||
function onOverlayChange(code: string) {
|
||||
previewCode.value = code; // 浮层内切股(键盘/侧栏)同步到路由
|
||||
syncRoute();
|
||||
}
|
||||
function closeOverlay() {
|
||||
previewCode.value = null;
|
||||
syncRoute();
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div class="mb-4 flex flex-wrap items-center gap-3">
|
||||
<h1 class="text-xl font-semibold text-[#E8EAED]">全部股票</h1>
|
||||
<span class="text-[13px] text-[#9BA3AE]">共 {{ total.toLocaleString() }} 只 · 点击行查看 K 线详情</span>
|
||||
|
||||
<div class="relative ml-auto">
|
||||
<svg class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[#9BA3AE]" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8" /><path d="M21 21l-4.35-4.35" /></svg>
|
||||
<input
|
||||
v-model="search"
|
||||
type="text"
|
||||
placeholder="搜索代码 / 名称"
|
||||
class="w-56 rounded-md border border-[#33353D] bg-[#16181D] py-2 pl-9 pr-3 text-sm text-[#E8EAED] outline-none transition placeholder:text-[#7A818C] focus:border-blue-500 focus:ring-2 focus:ring-blue-500/30"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<select v-model="market" class="ipt !w-auto !py-1.5 text-[13px]" title="按板块筛选">
|
||||
<option v-for="m in MARKETS" :key="m" :value="m">{{ m }}</option>
|
||||
</select>
|
||||
|
||||
<select v-model="industry" class="ipt !w-auto !py-1.5 text-[13px]" title="按行业筛选">
|
||||
<option value="">全部行业</option>
|
||||
<option v-for="i in industries" :key="i.name" :value="i.name">{{ i.name }}({{ i.count }})</option>
|
||||
</select>
|
||||
|
||||
<select v-model="area" class="ipt !w-auto !py-1.5 text-[13px]" title="按地域筛选">
|
||||
<option value="">全部地域</option>
|
||||
<option v-for="a in areas" :key="a.name" :value="a.name">{{ a.name }}({{ a.count }})</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div v-if="error" class="flex items-start gap-2 rounded-xl border border-red-500/30 bg-red-500/15 px-4 py-3 text-sm text-red-400">
|
||||
<svg class="mt-0.5 h-4 w-4 shrink-0" 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>
|
||||
{{ error }}
|
||||
</div>
|
||||
|
||||
<div class="overflow-hidden rounded-xl border border-[#26272E] bg-[#101014]">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="border-b border-[#1E2026] text-left text-[13px] text-[#A8AFB8]">
|
||||
<th class="w-10 px-2 py-3 font-medium" title="自选">★</th>
|
||||
<th class="px-4 py-3 font-medium">
|
||||
<button type="button" class="inline-flex items-center gap-1 transition hover:text-[#E8EAED]" :class="sort === 'symbol' ? 'text-[#E8EAED]' : ''" @click="toggleSort('symbol')">
|
||||
代码<span class="text-[10px] leading-none" :class="sort === 'symbol' ? 'text-blue-400' : 'text-[#4A4D55]'">{{ sort === 'symbol' ? (order === 'asc' ? '▲' : '▼') : '⇅' }}</span>
|
||||
</button>
|
||||
</th>
|
||||
<th class="px-4 py-3 font-medium">名称</th>
|
||||
<th class="px-4 py-3 font-medium">行业</th>
|
||||
<th class="px-4 py-3 font-medium">市场</th>
|
||||
<th class="px-4 py-3 text-right font-medium">最新价</th>
|
||||
<th class="px-4 py-3 text-right font-medium">涨跌幅</th>
|
||||
<th class="px-4 py-3 text-right font-medium" title="单位:亿元">
|
||||
<button type="button" class="inline-flex items-center gap-1 transition hover:text-[#E8EAED]" :class="sort === 'total_mv' ? 'text-[#E8EAED]' : ''" @click="toggleSort('total_mv')">
|
||||
总市值<span class="text-[10px] leading-none" :class="sort === 'total_mv' ? 'text-blue-400' : 'text-[#4A4D55]'">{{ sort === 'total_mv' ? (order === 'asc' ? '▲' : '▼') : '⇅' }}</span>
|
||||
</button>
|
||||
</th>
|
||||
<th class="px-4 py-3 text-right font-medium" title="单位:亿元">
|
||||
<button type="button" class="inline-flex items-center gap-1 transition hover:text-[#E8EAED]" :class="sort === 'circ_mv' ? 'text-[#E8EAED]' : ''" @click="toggleSort('circ_mv')">
|
||||
流通市值<span class="text-[10px] leading-none" :class="sort === 'circ_mv' ? 'text-blue-400' : 'text-[#4A4D55]'">{{ sort === 'circ_mv' ? (order === 'asc' ? '▲' : '▼') : '⇅' }}</span>
|
||||
</button>
|
||||
</th>
|
||||
<th class="px-4 py-3 text-right font-medium" title="≤15 绿 · 15-30 灰 · 30-60 黄 · >60 红;亏损/无数据为空">
|
||||
<button type="button" class="inline-flex items-center gap-1 transition hover:text-[#E8EAED]" :class="sort === 'pe_ttm' ? 'text-[#E8EAED]' : ''" @click="toggleSort('pe_ttm')">
|
||||
市盈率TTM<span class="text-[10px] leading-none" :class="sort === 'pe_ttm' ? 'text-blue-400' : 'text-[#4A4D55]'">{{ sort === 'pe_ttm' ? (order === 'asc' ? '▲' : '▼') : '⇅' }}</span>
|
||||
</button>
|
||||
</th>
|
||||
<th class="px-4 py-3 text-right font-medium">
|
||||
<button type="button" class="inline-flex items-center gap-1 transition hover:text-[#E8EAED]" :class="sort === 'pb' ? 'text-[#E8EAED]' : ''" @click="toggleSort('pb')">
|
||||
市净率<span class="text-[10px] leading-none" :class="sort === 'pb' ? 'text-blue-400' : 'text-[#4A4D55]'">{{ sort === 'pb' ? (order === 'asc' ? '▲' : '▼') : '⇅' }}</span>
|
||||
</button>
|
||||
</th>
|
||||
<th class="px-4 py-3 text-right font-medium">
|
||||
<button type="button" class="inline-flex items-center gap-1 transition hover:text-[#E8EAED]" :class="sort === 'turnover_rate' ? 'text-[#E8EAED]' : ''" @click="toggleSort('turnover_rate')">
|
||||
换手率<span class="text-[10px] leading-none" :class="sort === 'turnover_rate' ? 'text-blue-400' : 'text-[#4A4D55]'">{{ sort === 'turnover_rate' ? (order === 'asc' ? '▲' : '▼') : '⇅' }}</span>
|
||||
</button>
|
||||
</th>
|
||||
<th class="px-4 py-3 text-right font-medium">数据截至</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="loading && items.length === 0">
|
||||
<td colspan="13" class="px-4 py-16 text-center text-[#9BA3AE]">加载中…</td>
|
||||
</tr>
|
||||
<tr
|
||||
v-for="it in items"
|
||||
:key="it.ts_code"
|
||||
class="cursor-pointer border-b border-[#1E2026] transition hover:bg-blue-500/15"
|
||||
@click="openStock(it.ts_code)"
|
||||
>
|
||||
<td class="px-2 py-2.5 text-center" @click.stop>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded p-0.5 transition-colors disabled:opacity-50"
|
||||
:class="it.watched ? 'text-amber-500 hover:text-amber-600' : 'text-[#C3C9D2] hover:text-amber-400'"
|
||||
:title="it.watched ? '移出自选' : '加入自选'"
|
||||
:disabled="starBusy === it.ts_code"
|
||||
@click="toggleStar(it)"
|
||||
>
|
||||
<svg class="h-4 w-4" viewBox="0 0 24 24" :fill="it.watched ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="2" stroke-linejoin="round">
|
||||
<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
|
||||
</svg>
|
||||
</button>
|
||||
</td>
|
||||
<td class="px-4 py-2.5 font-mono text-sm text-[#E8EAED]">{{ it.symbol }}</td>
|
||||
<td class="px-4 py-2.5 font-medium text-[#E8EAED]">{{ it.name }}</td>
|
||||
<td class="px-4 py-2.5 text-[#A8AFB8]">{{ it.industry || '--' }}</td>
|
||||
<td class="px-4 py-2.5">
|
||||
<span class="rounded bg-[#26272E] px-1.5 py-0.5 text-[13px] text-[#A8AFB8]">{{ it.market || '--' }}</span>
|
||||
</td>
|
||||
<td class="px-4 py-2.5 text-right font-mono text-sm font-medium tabular-nums" :class="pctClass(it.pct_chg)">{{ it.close?.toFixed(2) ?? '--' }}</td>
|
||||
<td class="px-4 py-2.5 text-right font-mono text-sm tabular-nums" :class="pctClass(it.pct_chg)">{{ fmtPct(it.pct_chg) }}</td>
|
||||
<td class="px-4 py-2.5 text-right font-mono text-sm tabular-nums text-[#A8AFB8]">{{ fmtYi(it.total_mv) }}</td>
|
||||
<td class="px-4 py-2.5 text-right font-mono text-sm tabular-nums text-[#A8AFB8]">{{ fmtYi(it.circ_mv) }}</td>
|
||||
<td class="px-4 py-2.5 text-right font-mono text-sm tabular-nums" :class="peClass(it.pe_ttm)">{{ fmtNum(it.pe_ttm) }}</td>
|
||||
<td class="px-4 py-2.5 text-right font-mono text-sm tabular-nums text-[#A8AFB8]">{{ fmtNum(it.pb) }}</td>
|
||||
<td class="px-4 py-2.5 text-right font-mono text-sm tabular-nums text-[#A8AFB8]">{{ fmtTurnover(it.turnover_rate) }}</td>
|
||||
<td class="px-4 py-2.5 text-right font-mono text-sm text-[#9BA3AE]">{{ fmtDate(it.last_ts) }}</td>
|
||||
</tr>
|
||||
<tr v-if="!loading && items.length === 0">
|
||||
<td colspan="13" class="px-4 py-16 text-center text-[#9BA3AE]">没有匹配的股票</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between border-t border-[#1E2026] px-4 py-3 text-[13px] text-[#A8AFB8]">
|
||||
<span v-if="loading">加载中…</span>
|
||||
<span v-else>第 {{ page }} / {{ totalPages }} 页</span>
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-[#26272E] px-3 py-1.5 transition hover:border-[#3A3D46] hover:text-white disabled:opacity-40"
|
||||
:disabled="page <= 1 || loading"
|
||||
@click="go(-1)"
|
||||
>
|
||||
上一页
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-[#26272E] px-3 py-1.5 transition hover:border-[#3A3D46] hover:text-white disabled:opacity-40"
|
||||
:disabled="page >= totalPages || loading"
|
||||
@click="go(1)"
|
||||
>
|
||||
下一页
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 全屏个股详情(与选股页同款;当前股记录在 ?code=) -->
|
||||
<StockDetailOverlay
|
||||
v-if="previewCode && overlayItems.length"
|
||||
:items="overlayItems"
|
||||
:initial="previewCode"
|
||||
@close="closeOverlay"
|
||||
@change="onOverlayChange"
|
||||
@watched-change="onWatchedChange"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
Reference in New Issue
Block a user