This commit is contained in:
2026-09-05 00:12:19 +08:00
parent 991d1bf343
commit ad9245abdd
12 changed files with 287 additions and 595 deletions

View File

@@ -2,7 +2,7 @@ import type {
AdjustMode,
BacktestRequest,
BacktestResponse,
ChipsResponse,
Candle,
CurrentUser,
EventBacktestRequest,
EventBacktestResponse,
@@ -191,22 +191,6 @@ export async function getStockPreview(
return (await res.json()) as PreviewResponse;
}
// ---------- 筹码分布(个股筹码峰) ----------
/** 获取某参考日的筹码截面date 缺省取最新;周/月 K 线由调用方换算成周期末日传入,
* 后端吸附到 <=date 的最近有数据交易日。价格与成本均已按 adjust 口径换算。 */
export async function getStockChips(
tsCode: string,
opts: { date?: string; adjust?: AdjustMode } = {},
): Promise<ChipsResponse> {
const q = new URLSearchParams();
if (opts.date) q.set('date', opts.date);
if (opts.adjust) q.set('adjust', opts.adjust);
const qs = q.toString();
const res = await apiFetch(`/api/stock/${encodeURIComponent(tsCode)}/chips${qs ? `?${qs}` : ''}`);
if (!res.ok) throw new ApiError(await readError(res, `获取筹码分布失败 (HTTP ${res.status})`), res.status);
return (await res.json()) as ChipsResponse;
}
// ---------- 大盘总览(主页) ----------
export async function getMarketOverview(): Promise<MarketOverview> {
const res = await apiFetch('/api/market/overview');
@@ -214,6 +198,13 @@ export async function getMarketOverview(): Promise<MarketOverview> {
return (await res.json()) as MarketOverview;
}
/** 上证指数全量 K 线(日线基底聚合到目标周期;收盘口径) */
export async function getIndexCandles(timeframe: Timeframe): Promise<Candle[]> {
const res = await apiFetch(`/api/market/index-candles?timeframe=${encodeURIComponent(timeframe)}`);
if (!res.ok) throw new ApiError(await readError(res, `获取指数K线失败 (HTTP ${res.status})`), res.status);
return (await res.json()) as Candle[];
}
export async function getStocks(params: {
search?: string;
market?: string;

View File

@@ -260,6 +260,9 @@ export interface ChartLayoutPrefs {
subHeights: Record<string, number>; // 面板高度 px
timeframe?: Timeframe;
tooltipFields?: TooltipField[]; // 浮层显示的指标(顺序即行序;空数组=仅日期头)
indexTimeframe?: Timeframe; // 首页上证指数 K 线周期
showBoll?: boolean; // 主图叠加 BOLL
showZhixing?: boolean; // 主图叠加知行指标(趋势线+多空线)
}
export interface ScreenerQueryItem {
@@ -357,29 +360,6 @@ export interface EventBacktestResponse {
total: number;
}
// ---------- 筹码分布cyq_chips/cyq_perf数据自 2018 年起) ----------
export interface ChipRow {
price: number; // 已按 adjust 口径换算的价位
percent: number; // 该价位筹码占比0~1全价位合计约 1
}
export interface ChipsResponse {
ts_code: string;
trade_date: string | null; // YYYYMMDD 截面日
adjust: string;
rows: ChipRow[];
his_low: number | null;
his_high: number | null;
cost_5pct: number | null;
cost_15pct: number | null;
cost_50pct: number | null;
cost_85pct: number | null;
cost_95pct: number | null;
weight_avg: number | null; // 平均成本
winner_rate: number | null; // 获利比例 %
error: string | null;
}
// ---------- 大盘总览(主页) ----------
export interface IndexQuote {
code: string; // 000001.SH / HKTECH / DJI

View File

@@ -11,7 +11,8 @@ import {
threeWaves, triangle, xabcd,
} from '@klinecharts/extension';
import { useSettingsStore, TOOLTIP_FIELDS, DEFAULT_TOOLTIP_FIELDS } from '@/stores/settings';
import { registerCustomIndicators, computeZhixingSeries, DKX_PERIODS, ZHIXING_NAME, CHIPS_NAME, CHIPS_COL_PX, type ChipsExt } from '@/indicators';
import { darkStyles as sharedDarkStyles } from '@/chartStyles';
import { registerCustomIndicators, computeZhixingSeries, DKX_PERIODS, ZHIXING_NAME } from '@/indicators';
import type { Candle, TooltipField } from '@/api/types';
// 通达信导入的自定义主图指标注册表;知行序列走 PV 管道按时间戳取预计算值。
@@ -95,10 +96,6 @@ const props = defineProps<{
showZhixing: boolean;
/** 知行指标图例行的板块文本(通达信 HYBLOCK+DYBLOCK 的近似,行业+地域) */
zhixingBlocks?: string;
/** 主图是否叠加筹码峰cyq 截面横向直方图,纯 draw 绘制) */
showChips: boolean;
/** 筹码峰截面数据(父组件按 当前窗口末根/十字线 所在周期取数null=暂无) */
chips?: ChipsExt | null;
/** K线周期标签仅用于 MA 指标名缓存 key */
timeframe: string;
/** 浮层显示的指标(可选;缺省=目录全开,空数组=仅日期头) */
@@ -114,8 +111,6 @@ const props = defineProps<{
const emit = defineEmits<{
/** 日期跳转锚点在本次数据窗口里找不到(早于上市/晚于最后一根):请父组件回退到最新行情并提示 */
(e: 'centerMiss', ts: number): void;
/** 十字线落在某根K线上开启筹码峰时逐根上报父组件防抖后取该周期筹码截面 */
(e: 'crosshairDate', ts: number): void;
}>();
// A股语义色黑底高对比UP/DOWN 跟随设置中的涨跌配色
@@ -327,35 +322,9 @@ function maybePrefetch(myEpoch: number) {
}
function darkStyles() {
return {
grid: { horizontal: { color: '#1C1E24' }, vertical: { color: '#1C1E24' } },
// 内建 VOL 等指标柱的涨跌色缺省是库默认绿涨红跌,与全站语义相反;
// bars[0] 与库默认项深合并init 时 merge 到 getDefaultStyles只覆盖三个颜色键
// UP/DOWN 在 build() 里随 settings 刷新,故切「绿涨红跌」重建后同样生效
indicator: { bars: [{ upColor: UP, downColor: DOWN, noChangeColor: '#7A818C' }] },
candle: {
bar: {
upColor: UP, downColor: DOWN,
upBorderColor: UP, downBorderColor: DOWN,
upWickColor: UP, downWickColor: DOWN,
},
priceMark: {
high: { color: '#9AA0AA' }, low: { color: '#9AA0AA' },
last: { upColor: UP, downColor: DOWN },
},
},
xAxis: { axisLine: { color: '#2A2D34' }, tickText: { color: '#9AA0AA', size: 12 }, tickLine: { color: '#2A2D34' } },
yAxis: { axisLine: { color: '#2A2D34' }, tickText: { color: '#9AA0AA', size: 12 }, tickLine: { color: '#2A2D34' } },
crosshair: {
horizontal: { text: { backgroundColor: '#333A45' } },
vertical: { text: { backgroundColor: '#333A45' } },
},
separator: {
color: '#23252B',
// 悬停/拖拽分隔条时的底色(库默认 8% 蓝在纯黑底上不可见,加重为可感知的拖拽提示)
activeBackgroundColor: 'rgba(37, 99, 235, 0.30)',
},
};
// 共享暗色主题chartStyles.tsUP/DOWN 在 build() 里随 settings 刷新,
// 故切「绿涨红跌」重建后同样生效
return sharedDarkStyles(UP, DOWN);
}
// 副图默认高度
@@ -437,8 +406,6 @@ function bindCrosshair(ch: Chart) {
const idx = ts != null ? idxOfTs(ts) : -1; // 全量数组与指标序列按索引对齐
if (idx < 0) { hover.value = null; return; }
const k = allData[idx];
// 筹码峰跟随:十字线逐根上报(父组件防抖取截面);不开启时不上报,避免无谓事件
if (props.showChips) emit('crosshairDate', k.timestamp);
const prev = idx > 0 ? allData[idx - 1] : null;
const diff = prev ? k.close - prev.close : null;
const chg = prev ? (diff! / prev.close) * 100 : null;
@@ -662,70 +629,8 @@ function placeTradeTip(px: number, py: number, rowCount: number): { x: number; y
return { x, y };
}
// ---------- 筹码峰指标同步不重建图表createIndicator 不支持原地改 extendData
// 先删后建即可;数据/开关变化走这里,保留滚动位置与用户画线) ----------
function syncChipsIndicator() {
if (!chart) return;
const exists = chart.getIndicators().some((i) => i.name === CHIPS_NAME);
const want = props.showChips && !!props.chips;
if (want) {
if (exists) chart.removeIndicator({ name: CHIPS_NAME });
chart.createIndicator({ name: CHIPS_NAME, paneId: 'candle_pane', extendData: props.chips ?? undefined });
syncRightOffset(); // 开关即扩留白(不等数据),数据到达时列直接落在已预留的空白里
} else if (exists) {
chart.removeIndicator({ name: CHIPS_NAME });
restoreRightOffset();
} else {
restoreRightOffset(); // 数据未到即关:同样要还原已扩出去的留白
}
}
// ---------- 筹码峰竖列的右侧留白管理 ----------
// klinecharts 滚动状态唯一变量是 diff最后一根K距绘图区右缘的 bar 数),
// setOffsetRightDistance(px) 会把 diff 直接重置为 px/barSpace 并 relayout——等价于
// “视口拽回实时位并留 px 空白”。因此只在「右区」末根K在视野内getVisibleRange().to
// 达到 data 长度)时调用;用户在看历史时绝不调,滚回右区后由 onScroll 防抖补一次吸附
// (同花顺松手吸附同款)。绝不调 setMaxOffsetRightDistance会把滚动限制切到
// 'distance' 模式,默认钳到 50px 且改变滚动边缘行为。
// 右侧固定留白价格轴与末根K之间的呼吸空间scrollToRealTime 以它为锚点)
const BASE_RIGHT_PX = 28;
let syncingRightOffset = false; // 重入守卫set 会同步派发 onVisibleRangeChange
let scrollReanchorTimer: ReturnType<typeof setTimeout> | null = null;
let managedRightPx = 0; // 筹码开启期间我们 set 过的目标值(关筹码时判断“是否还归我们管”)
/** 目标右侧留白:开筹码 = 列宽 + 一根K线 + 余量bar 最宽 50px → 峰值 ~182px */
function targetRightPx(): number {
if (!props.showChips) return BASE_RIGHT_PX;
const bar = chart?.getBarSpace().bar || 10;
return Math.round(CHIPS_COL_PX + bar + 12);
}
/** 开筹码期间保证留白盖住竖列:只扩不缩(用户自己拖出的更大留白不动) */
function syncRightOffset(): void {
if (!chart || syncingRightOffset || !props.showChips) return;
const list = chart.getDataList();
if (!list.length || chart.getVisibleRange().to < list.length) return; // 右区守卫
const target = targetRightPx();
if (chart.getOffsetRightDistance() >= target - 2) return; // 阈值防循环 + 只扩不缩
syncingRightOffset = true;
try {
chart.setOffsetRightDistance(target);
managedRightPx = target;
} finally {
syncingRightOffset = false;
}
}
/** 关筹码时一次性还原 28px仅当留白仍在我们管理范围内用户没手动拖大过 */
function restoreRightOffset(): void {
if (!chart || managedRightPx === 0) return;
const list = chart.getDataList();
const cur = chart.getOffsetRightDistance();
if (list.length && chart.getVisibleRange().to >= list.length
&& cur > BASE_RIGHT_PX + 2 && cur <= managedRightPx + 2) {
chart.setOffsetRightDistance(BASE_RIGHT_PX);
}
managedRightPx = 0;
}
function build() {
if (!container.value || props.candles.length === 0) return;
@@ -819,7 +724,6 @@ function build() {
calcParams: DKX_PERIODS, extendData: { blocks: props.zhixingBlocks },
});
}
if (props.showChips) syncChipsIndicator(); // 筹码峰(数据未到时 draw 直接空转,到货后由 watch 补建)
// 副图按用户顺序创建,并设置用户高度;主图吃剩余高度。
// minHeight 交给库在分隔条拖拽时强制执行(与 subH 的 40px 下限一致)
@@ -852,23 +756,8 @@ function build() {
const from = (payload as { data?: { from?: unknown } }).data?.from;
if (typeof from === 'number' && from < 200) maybePrefetch(myEpoch);
});
// 右侧留白:开筹码时按竖列宽度预留scrollToRealTime 以它为锚点,先后顺序不能换)
ch.setOffsetRightDistance(props.showChips ? targetRightPx() : BASE_RIGHT_PX);
// 筹码竖列的留白跟随:缩放后 barSpace 变化onZoom 触发时新值已生效)立即补扩;
// 拖拽期间 onScroll 逐帧触发、且拖拽每帧从手势起点快照重算 diff逐帧同步会与拖拽
// “互搏”(从实时位拖向历史会被逐帧拽回),故防抖 150ms 只在手势结束后补一次
ch.subscribeAction('onZoom', () => {
if (myEpoch !== epoch) return;
syncRightOffset();
});
ch.subscribeAction('onScroll', () => {
if (myEpoch !== epoch) return;
if (scrollReanchorTimer) clearTimeout(scrollReanchorTimer);
scrollReanchorTimer = setTimeout(() => {
scrollReanchorTimer = null;
if (myEpoch === epoch) syncRightOffset();
}, 150);
});
// 右侧留白scrollToRealTime 以它为锚点,先后顺序不能换)
ch.setOffsetRightDistance(BASE_RIGHT_PX);
ch.scrollToRealTime();
// 日期跳转build 尾部的 scrollToRealTime 会把视口重置到最新一根,居中必须放在它之后
//init 数据在 setPeriod 时已同步落入图表,这里可直接定位)。
@@ -881,8 +770,6 @@ function build() {
function teardown() {
if (subHTimer) { clearTimeout(subHTimer); subHTimer = null; }
if (scrollReanchorTimer) { clearTimeout(scrollReanchorTimer); scrollReanchorTimer = null; }
managedRightPx = 0;
if (container.value) dispose(container.value);
chart = null;
hover.value = null;
@@ -893,9 +780,6 @@ function teardown() {
onMounted(build);
onBeforeUnmount(teardown);
watch(() => [props.candles, props.indicators, props.subPanes, props.showBoll, props.showZhixing, props.zhixingBlocks, props.maPeriods, props.timeframe], () => { teardown(); build(); }, { deep: true });
// 筹码峰开关/截面变化:只同步该指标,不重建图表(保留滚动位置与用户画线;
// 十字线跟随会高频更新截面,重建会闪 + 丢状态)
watch(() => [props.showChips, props.chips], syncChipsIndicator, { deep: true });
// 买卖点数据变化(导入/清空/开关显示):只重画标记,不重建图表(保留滚动位置与用户画线)
watch(() => props.tradeMarkers, renderTradeMarkers, { deep: true });
// 涨跌配色切换:重建图表以应用新颜色

View File

@@ -5,6 +5,7 @@ import { getMarketOverview } from '@/api/client';
import type { IndexQuote, MarketOverview as Overview } from '@/api/types';
import AmountHistoryChart from '@/components/AmountHistoryChart.vue';
import IndexKLine from '@/components/IndexKLine.vue';
// 主页大盘总览A 股 + 港美指数最近收盘(收盘口径,标注交易日),沪深两市市值/成交统计。
// 数据为 EOD 口径,进页面拉一次 + 手动刷新即可,不做轮询。
@@ -226,6 +227,9 @@ function hoverText(it: IndexQuote): string {
</div>
</div>
<!-- 上证指数 K 线///周期随用户偏好持久化 -->
<IndexKLine class="mt-4" />
<!-- 两市统计daily_info SH_MARKET(主板A+科创+B) + SZ_MARKET 汇总 -->
<div
v-if="overview.stats"

View File

@@ -1,15 +1,14 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import {
addWatchlist, clearTrades, getStockChips, getStockPreview, getTrades, getWatchlist as getWatchlistApi,
addWatchlist, clearTrades, getStockPreview, getTrades, getWatchlist as getWatchlistApi,
importTrades, removeWatchlist,
} from '@/api/client';
import type {
ChartLayoutPrefs, ChipsResponse, PreviewResponse, ScreenerItemOut, Timeframe, TooltipField,
ChartLayoutPrefs, PreviewResponse, ScreenerItemOut, Timeframe, TooltipField,
TradesImportResponse, UserTrade,
} from '@/api/types';
import { useSettingsStore, DEFAULT_TOOLTIP_FIELDS, TOOLTIP_FIELDS, type PriceAdjust } from '@/stores/settings';
import type { ChipsExt } from '@/indicators';
import DetailKLine from './DetailKLine.vue';
const props = defineProps<{
@@ -67,8 +66,11 @@ const subPanes = computed<string[]>(() => layout.value.subPanes);
const maPeriods = computed<number[]>(() => layout.value.maPeriods);
const subHeights = computed(() => layout.value.subHeights);
const tooltipFields = computed<TooltipField[]>(() => layout.value.tooltipFields ?? DEFAULT_TOOLTIP_FIELDS);
const showBoll = ref(false);
const showZhixing = ref(false);
// 主图可选叠加BOLL / 知行):随用户偏好持久化,跨会话/跨设备记忆开关
const showBoll = computed<boolean>(() => layout.value.showBoll === true);
const showZhixing = computed<boolean>(() => layout.value.showZhixing === true);
function toggleBoll() { settings.setChartLayout({ showBoll: !showBoll.value }); }
function toggleZhixing() { settings.setChartLayout({ showZhixing: !showZhixing.value }); }
// 知行指标图例行的板块文本(通达信 HYBLOCK+' '+DYBLOCK 的近似GNBLOCK 概念板块无数据源)
const zhixingBlocks = computed(() => {
const info = data.value?.info;
@@ -76,84 +78,6 @@ const zhixingBlocks = computed(() => {
return [info.industry, info.area].filter(Boolean).join(' ') || undefined;
});
// ---------- 筹码峰cyq 截面,跟随 日/周/月K 的当前周期 + 十字线) ----------
const showChips = ref(false);
const chipsExt = ref<ChipsExt | null>(null);
let chipsToken = 0; // 请求序号:切股/切口径瞬间乱序返回的旧截面不能回填
let chipsKey = ''; // 已请求去重键code|adjust|参考日)
function toChipsExt(res: ChipsResponse, refClose: number): ChipsExt {
return {
rows: res.rows.map((r) => ({ price: r.price, percent: r.percent })),
date: res.trade_date ?? undefined,
refClose,
winner: res.winner_rate,
avg: res.weight_avg,
costLow: res.cost_5pct,
costHigh: res.cost_95pct,
error: res.error ?? undefined,
};
}
/** 筹码锚点(同花顺式):返回 参考日 + 锚定 bar 收盘价(获利/套牢的分界价)。
* 日K=bar 当日;周/月/年K 的 bar ts 是周期首日,参考日=下一根 bar 首日的前一天
* (最后一根=今天,后端再吸附到 <=参考日 的最近有数据交易日)。
* idx 缺省=窗口最后一根(跟随当前可视周期);十字线跟随时传落点下标。
* 注:翻页前插的更早 bar 不在 data.candles 里,十字线落到那些 bar 上时沿用上一截面。 */
function chipsAnchor(idx?: number): { ref: string; close: number } | undefined {
const bars = data.value?.candles;
if (!bars?.length) return undefined;
const i = idx != null && idx >= 0 && idx < bars.length ? idx : bars.length - 1;
if (timeframe.value === '1d') return { ref: bars[i].ts.slice(0, 10), close: bars[i].close };
const nextTs = i + 1 < bars.length ? new Date(bars[i + 1].ts).getTime() - 86400000 : Date.now();
return { ref: fmtDashDate(Math.min(nextTs, Date.now())), close: bars[i].close };
}
async function loadChips(anchorIdx?: number) {
if (!showChips.value) return;
const anchor = chipsAnchor(anchorIdx);
if (!anchor) return;
const key = `${active.value}|${adjust.value}|${anchor.ref}`;
if (key === chipsKey) return; // 同股同口径同参考日不重复请求(后端有 Redis 缓存,前端也省一次往返)
chipsKey = key;
const token = ++chipsToken;
try {
const res = await getStockChips(active.value, { date: anchor.ref, adjust: adjust.value });
if (token === chipsToken) chipsExt.value = toChipsExt(res, anchor.close);
} catch {
if (token === chipsToken) chipsExt.value = { rows: [], refClose: anchor.close, error: '筹码数据获取失败' };
}
}
/** K线数据就绪/切换(切股、复权、周期、日期跳转都经 load() 换 data筹码重置到新窗口末根 */
watch(data, () => {
chipsKey = '';
chipHoverTs = null;
chipsExt.value = null;
void loadChips();
});
/** 十字线跟随(防抖 350ms落在哪根K线就取那个周期的截面离开图表保留最后截面通达信同款 */
let chipHoverTimer: ReturnType<typeof setTimeout> | null = null;
let chipHoverTs: number | null = null;
function onCrosshairDate(ts: number) {
if (!showChips.value || chipHoverTs === ts) return;
chipHoverTs = ts;
if (chipHoverTimer) clearTimeout(chipHoverTimer);
chipHoverTimer = setTimeout(() => {
chipHoverTimer = null;
const bars = data.value?.candles;
if (!bars) return;
const idx = bars.findIndex((b) => new Date(b.ts).getTime() === ts);
if (idx >= 0) void loadChips(idx);
}, 350);
}
function toggleChips() {
showChips.value = !showChips.value;
if (showChips.value) { chipsKey = ''; chipHoverTs = null; void loadChips(); }
}
function toggleSub(key: string) {
const cur = subPanes.value;
settings.setChartLayout({
@@ -664,7 +588,7 @@ const fmtListDate = (s?: string | null) => (s && s.length === 8 ? `${s.slice(0,
class="rounded-md border px-2.5 py-1 text-[13px] transition-colors"
:class="showBoll ? 'border-purple-500 bg-purple-500 text-white' : 'border-[#26272E] bg-[#101014] text-[#9BA3AE]'"
title="主图叠加布林带"
@click="showBoll = !showBoll"
@click="toggleBoll"
>BOLL</button>
<!-- 知行通达信导入的自定义主图指标趋势线+多空线 -->
<button
@@ -672,16 +596,8 @@ const fmtListDate = (s?: string | null) => (s && s.length === 8 ? `${s.slice(0,
class="rounded-md border px-2.5 py-1 text-[13px] transition-colors"
:class="showZhixing ? 'border-[#E61851] bg-[#E61851] text-white' : 'border-[#26272E] bg-[#101014] text-[#9BA3AE]'"
title="知行指标:短期趋势线 EMA(EMA(C,10),10) + 多空线 (MA14+MA28+MA57+MA114)/4"
@click="showZhixing = !showZhixing"
@click="toggleZhixing"
>知行</button>
<!-- 筹码峰右侧横向线状直方图选中K线下方获利盘红/上方套牢盘蓝+平均成本虚线 -->
<button
type="button"
class="rounded-md border px-2.5 py-1 text-[13px] transition-colors"
:class="showChips ? 'border-cyan-400 bg-cyan-400 text-black' : 'border-[#26272E] bg-[#101014] text-[#9BA3AE]'"
title="筹码峰各价位持仓占比选中K线分界下方获利盘红/上方套牢盘蓝),随日/周/月K与十字线切换截面"
@click="toggleChips"
>筹码峰</button>
<!-- 实盘交易点交割单导入的买卖标记 -->
<button
type="button"
@@ -812,9 +728,6 @@ const fmtListDate = (s?: string | null) => (s && s.length === 8 ? `${s.slice(0,
:show-boll="showBoll"
:show-zhixing="showZhixing"
:zhixing-blocks="zhixingBlocks"
:show-chips="showChips"
:chips="chipsExt"
@crosshair-date="onCrosshairDate"
:timeframe="timeframe"
:tooltip-fields="tooltipFields"
:center-ts="jumpTs"

View File

@@ -1,188 +0,0 @@
// 个股筹码峰Tushare cyq_chips / cyq_perf同花顺火焰山式右侧专用竖列
//
// 数据不在图表窗口上计算,而是一次性截面(某交易日各价位筹码占比 + 获利比例/平均成本),
// 经 extendData 注入、纯 draw 绘制:
// - 主图绘图区右缘、价格轴左侧一条【不透明底色专用竖列】K线不透出同花顺同款
// - 每个价位一根横条,在列内从右缘向左伸展,宽度 ∝ 占比/最大占比(火焰山形态)
// - 分界价 = 选中K线的收盘价refClose下方为获利盘、上方为套牢盘
// - 平均成本画黄色虚线、末根收盘画现价细实线;列内顶部小字:截面日/获利比例/平均成本/90%成本
// DetailKLine 依据 CHIPS_COL_PX 在开启筹码时加大右侧留白保证最新K线不被竖列盖住。
// figures 为空、calc 返回空行:指标不产生序列值,也不影响主图价格刻度(筹码是覆盖层)。
import type { IndicatorTemplate } from 'klinecharts';
export const CHIPS_NAME = 'pv-chips';
/** 火焰山竖列基准宽度pxDetailKLine 据此预留右侧留白draw 据此画列 */
export const CHIPS_COL_PX = 120;
/** 经 extendData 注入的筹码截面(父组件按 当前窗口末根/十字线 所在周期取数) */
export interface ChipsExt {
rows: { price: number; percent: number }[]; // percent 为 0~1 占比
date?: string; // YYYYMMDD 截面日
refClose?: number | null; // 获利/套牢分界价选中K线收盘缺省时 draw 退回图表末根收盘)
winner?: number | null; // 获利比例 %
avg?: number | null; // 平均成本
costLow?: number | null; // 90% 成本下沿cost_5pct
costHigh?: number | null; // 90% 成本上沿cost_95pct
error?: string | null; // 无数据/出错的提示文案(仍要画出来,用户才知道为何空)
}
// 同花顺筹码峰配色:获利盘红、套牢盘蓝
const UP = '#FE354B';
const DOWN = '#2F7BFF';
const AVG_COLOR = '#F5C518';
const LABEL_COLOR = '#9AA0AA';
const VALUE_COLOR = '#E8EAED';
// 竖列几何:窄图下限 56px最多占绘图区宽度 35%(实际宽度取两者与基准的钳制值)
const COL_MIN_PX = 56;
const COL_MAX_RATIO = 0.35;
/** 列内左右内边距(横条右缘、统计文字与列缘的呼吸) */
const COL_PAD = 5;
/** 不透明底色(图表容器纯黑 bg-black取应用面板色左缘 1px 分隔线与 y 轴线同色 */
const COL_BG = '#101014';
const COL_BORDER = '#2A2D34';
/** 实心条透明度:不透明列内 0.85 足够“实心”,与底色留一丝层次 */
const BAR_ALPHA = 0.85;
/** 横条高度上限px极度放大时单价位占比条不至于铺满大半个竖列 */
const BAR_HEIGHT_CAP = 24;
/** 统计文字起始 y画线工具栏是 HTML 层,占顶部 ~36px文字块从 44px 起)/ 行高 */
const HEADER_TOP = 44;
const LINE_H = 13;
function fmtDate(d?: string): string {
return d && d.length === 8 ? `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}` : '—';
}
/** 右对齐数值超宽时截断加省略号90%成本 “10.50~14.20” 这类长串的兜底) */
function fitText(ctx: CanvasRenderingContext2D, text: string, maxW: number): string {
if (ctx.measureText(text).width <= maxW) return text;
let s = text;
while (s.length > 1 && ctx.measureText(`${s}`).width > maxW) s = s.slice(0, -1);
return `${s}`;
}
export const chipsIndicator: IndicatorTemplate<Record<string, never>, unknown, ChipsExt> = {
name: CHIPS_NAME,
shortName: '筹码',
figures: [], // 纯 draw 绘制,无序列图形
calc: (d) => d.map(() => ({})),
// 返回 trueisCover跳过框架 figure 渲染(本来也没有 figures全部自己画
draw: ({ ctx, chart, indicator, bounding, yAxis }) => {
const ext = indicator.extendData;
if (!ext) return true;
// 竖列几何bounding.right 即 y 轴左缘,列贴着价格轴(预留逻辑见 DetailKLine 的 syncRightOffset
const colW = Math.max(COL_MIN_PX, Math.min(CHIPS_COL_PX, Math.floor(bounding.width * COL_MAX_RATIO)));
const colRight = bounding.right;
const colLeft = colRight - colW;
// 无数据/出错:不画底色列(空面板不遮图),错误文案画在原右上角位置
if (!ext.rows.length) {
if (ext.error) {
ctx.font = '11px sans-serif';
ctx.textBaseline = 'top';
ctx.textAlign = 'right';
ctx.fillStyle = LABEL_COLOR;
ctx.fillText(`筹码 ${ext.error}`, bounding.right - 4, bounding.top + HEADER_TOP);
}
return true;
}
// 1. 不透明底色列 + 左缘 1px 分隔线(先画,盖住网格/K线/MA/最新价虚线的右端)
ctx.fillStyle = COL_BG;
ctx.fillRect(colLeft, bounding.top, colW, bounding.height);
ctx.fillStyle = COL_BORDER;
ctx.fillRect(colLeft, bounding.top, 1, bounding.height);
const list = chart.getDataList();
// 分界价选中K线的收盘价父组件随截面注入缺省退回图表末根收盘
// <=分界价为获利盘(红)、>分界价为套牢盘(蓝)——同花顺同款
const split = ext.refClose ?? (list.length ? list[list.length - 1].close : undefined);
// 2. 筹码横条:列右缘向左伸展,宽度 ∝ 占比/最大占比
// 价位升序,便于求相邻像素间距(直方图的“条高”)
const rows = [...ext.rows].sort((a, b) => a.price - b.price);
const maxP = rows.reduce((m, r) => Math.max(m, r.percent), 0);
if (maxP > 0) {
// 相邻价位的中位像素间距 → 条高(连续火焰形态;缩到极小时并成实心轮廓)
const pitches: number[] = [];
for (let i = 1; i < rows.length; i++) {
const p = Math.abs(yAxis.convertToPixel(rows[i].price) - yAxis.convertToPixel(rows[i - 1].price));
if (p > 0) pitches.push(p);
}
pitches.sort((a, b) => a - b);
const pitch = pitches.length ? pitches[pitches.length >> 1] : 4;
const barH = Math.min(BAR_HEIGHT_CAP, Math.max(1, pitch * 0.92));
const maxBarW = colW - COL_PAD * 2;
for (const r of rows) {
const y = yAxis.convertToPixel(r.price);
if (y < bounding.top - barH || y > bounding.bottom + barH) continue; // 视口外跳过
const w = Math.max(1, (r.percent / maxP) * maxBarW);
ctx.fillStyle = split == null ? 'rgba(154,160,170,0.85)'
: r.price <= split ? `rgba(254,53,75,${BAR_ALPHA})` : `rgba(47,123,255,${BAR_ALPHA})`;
ctx.fillRect(colRight - COL_PAD - w, y - barH / 2, w, barH);
}
}
// 3. 平均成本虚线(横贯竖列)
if (ext.avg != null) {
const y = yAxis.convertToPixel(ext.avg);
if (y >= bounding.top && y <= bounding.bottom) {
ctx.save();
ctx.strokeStyle = AVG_COLOR;
ctx.lineWidth = 1;
ctx.setLineDash([4, 3]);
ctx.beginPath();
ctx.moveTo(colLeft + 1, Math.round(y) + 0.5);
ctx.lineTo(colRight, Math.round(y) + 0.5);
ctx.stroke();
ctx.restore();
}
}
// 4. 现价细实线(末根收盘,红/蓝随涨跌,与 y 轴最新价标签同源同色;
// 分界价本身已是横条红蓝交界,不再重复画线)
if (list.length >= 2) {
const last = list[list.length - 1];
const y = yAxis.convertToPixel(last.close);
if (y >= bounding.top && y <= bounding.bottom) {
ctx.save();
ctx.strokeStyle = last.close >= list[list.length - 2].close ? UP : DOWN;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(colLeft + 1, Math.round(y) + 0.5);
ctx.lineTo(colRight, Math.round(y) + 0.5);
ctx.stroke();
ctx.restore();
}
}
// 5. 统计小字块列内顶部label 左对齐 + value 右对齐,超宽截断
//列宽有限两列布局比原先的单行右对齐更能放下「90%成本 10.50~14.20」这类长串)
const w = ext.winner;
const lines: [string, string, string][] = [
['筹码', fmtDate(ext.date), VALUE_COLOR],
['获利比例', w == null ? '—' : `${w.toFixed(2)}%`, w == null ? VALUE_COLOR : w >= 50 ? UP : DOWN],
['平均成本', ext.avg == null ? '—' : ext.avg.toFixed(2), AVG_COLOR],
['90%成本', ext.costLow == null || ext.costHigh == null ? '—'
: `${ext.costLow.toFixed(2)}~${ext.costHigh.toFixed(2)}`, VALUE_COLOR],
];
ctx.font = '10px sans-serif';
ctx.textBaseline = 'top';
const labelX = colLeft + COL_PAD;
const valueX = colRight - COL_PAD;
const valueMaxW = colW - COL_PAD * 2 - 36; // 36 ≈ 左侧标签区预留宽
let ty = bounding.top + HEADER_TOP;
for (const [label, value, color] of lines) {
ctx.textAlign = 'left';
ctx.fillStyle = LABEL_COLOR;
ctx.fillText(label, labelX, ty);
ctx.textAlign = 'right';
ctx.fillStyle = color;
ctx.fillText(fitText(ctx, value, valueMaxW), valueX, ty);
ty += LINE_H;
}
return true;
},
};

View File

@@ -2,22 +2,14 @@
// 依赖预计算序列的指标(知行)不在此处闭包数据,而是导出模板工厂、由 DetailKLine 注入
// 按时间戳取值的访问器g(),与 pv-boll 等后端序列同款管道)。注意 g 及其闭包的
// PV/allData 是组件实例级的script setup 每次挂载重建),知行模板必须随挂载重注册
// 换绑到当前实例——否则永远读首挂实例的数据,切股后画的是第一只股票的线
// 筹码峰等“截面数据 + 纯 draw”指标不闭包实例数据经 extendData 注入),注册一次即可。
// 换绑到当前实例——否则永远读首挂实例的数据,切股后画的是第一只股票的线
import { registerIndicator } from 'klinecharts';
import { chipsIndicator } from './chips';
import { makeZhixingIndicator, ZHIXING_NAME, type ZhixingGetter } from './zhixing';
let staticRegistered = false;
export function registerCustomIndicators(get: ZhixingGetter) {
// 知行:同名重注册即替换,把 calc 换绑到本次挂载实例的 g与 DetailKLine 内
// pv-boll/pv-macd 每挂必注册同款;幂等闸曾导致知行只认第一只股票)
registerIndicator(makeZhixingIndicator(get));
if (staticRegistered) return;
staticRegistered = true;
registerIndicator(chipsIndicator);
}
export { CHIPS_NAME, CHIPS_COL_PX, type ChipsExt } from './chips';
export { ZHIXING_NAME, ZHIXING_TREND_COLOR, DKX_PERIODS, computeZhixingSeries } from './zhixing';

View File

@@ -1,7 +1,7 @@
import { computed, ref, watchEffect } from 'vue';
import { defineStore } from 'pinia';
import { getPreferences, putPreferences } from '@/api/client';
import type { ChartLayoutPrefs, TooltipField } from '@/api/types';
import type { ChartLayoutPrefs, Timeframe, TooltipField } from '@/api/types';
export type PriceTone = 'red-up' | 'green-up';
export type PriceAdjust = 'bfq' | 'qfq' | 'hfq';
@@ -37,6 +37,12 @@ function normTipFields(v: unknown): TooltipField[] | undefined {
return v.filter((k): k is TooltipField => typeof k === 'string' && TIP_VALID.has(k as TooltipField));
}
const TF_VALID = new Set(['1d', '1w', '1M', '1y']);
/** K线周期合法化非法/缺失返回 undefined调用方回退默认值 */
function normTimeframe(v: unknown): Timeframe | undefined {
return typeof v === 'string' && TF_VALID.has(v) ? (v as Timeframe) : undefined;
}
function loadTone(): PriceTone {
try {
const raw = localStorage.getItem(STORAGE_KEY);
@@ -63,6 +69,9 @@ function loadLayout(): ChartLayoutPrefs {
...v,
subHeights: v.subHeights ?? {},
tooltipFields: normTipFields(v.tooltipFields) ?? DEFAULT_TOOLTIP_FIELDS,
showBoll: v.showBoll === true,
showZhixing: v.showZhixing === true,
indexTimeframe: normTimeframe(v.indexTimeframe),
};
}
}
@@ -165,7 +174,14 @@ export const useSettingsStore = defineStore('settings', () => {
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 };
chartLayout.value = {
...v,
subHeights: v.subHeights ?? {},
tooltipFields: tip,
showBoll: v.showBoll === true,
showZhixing: v.showZhixing === true,
indexTimeframe: normTimeframe(v.indexTimeframe),
};
saveLocal(LAYOUT_KEY, JSON.stringify(chartLayout.value));
}
} else {