@@ -69,6 +95,66 @@ const dsOptions = computed(() =>
/>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
{{ settings.movingAveragePeriods.length }} / {{ MAX_MOVING_AVERAGE_COUNT }}
+
+
+
diff --git a/src/composables/README.md b/src/composables/README.md
index 21a6deb..8e6fa14 100644
--- a/src/composables/README.md
+++ b/src/composables/README.md
@@ -26,13 +26,18 @@ useMinuteChart.ts ←─ 分时图 (MinuteChart.vue)
useChart.ts ←─ K线图 (KLineChart.vue)
├─ invoke get_kline → K线数据 + 懒加载历史
├─ syncSubIndicator(VOL|MACD) → 副图切换
- └─ MA 叠加 + VOL 自定义外观
+ ├─ syncMainOverlay(MA|BOLL) → 主图叠加切换
+ └─ VOL 自定义外观
+
+utils/movingAverage.ts ←─ 主图均线
+ ├─ 配置解析、默认值与数量/周期边界
+ └─ syncMovingAverage() → 创建或更新 klinecharts MA 指标
```
### 关键数据流
-1. **挂载**: initChart → initChartCore → applyStyles → overrideIndicator(VOL) → syncSubIndicator → createIndicator(MA)
+1. **挂载**: initChart → initChartCore → applyStyles → syncSubIndicator → syncMainOverlay → syncMovingAverage
2. **加载**: loadData → invoke → map + setDataLoader → getBars('init') 触发渲染 → syncPrecision → startAutoRefresh
3. **周期切换**: watch([code,market,period]) → initChart + loadData → allData 重置
4. **副图切换**: SubIndicatorSwitcher emit → watch(subIndicator) → syncSubIndicator → createIndicator({name}, {pane: SUB_PANE_ID}) → isStack=false 自动替换
-5. **主题切换**: watch(settings.theme) → reapplyStyles → themeColors() 重新计算全色板
+5. **主题/均线设置**: watch(settings.theme / movingAveragePeriods) → 重放样式或 MA calcParams → themeColors() 重新计算色板
diff --git a/src/composables/useChart.ts b/src/composables/useChart.ts
index 548d72e..5cfba5a 100644
--- a/src/composables/useChart.ts
+++ b/src/composables/useChart.ts
@@ -3,6 +3,8 @@ import { invoke } from '@tauri-apps/api/core';
import type { KLineData as KCLineData, DataLoader } from 'klinecharts';
import type { KLineData, PeriodType, SubIndicatorType, MainOverlayType } from '@/types';
import { useSettingsStore } from '@/stores/settings';
+import { subPaneHeight } from '@/utils/paneSize';
+import { syncMovingAverage } from '@/utils/movingAverage';
import { minuteKSpan } from './minutePeriod';
import { useChartCore } from './useChartCore';
@@ -22,7 +24,7 @@ export function useChart(options: {
mainOverlay?: MaybeRef;
}) {
const settings = useSettingsStore();
- const { chart, loading, error, currentPeriod, themeColors, periodToKlinecharts, syncPrecision: syncPrecisionCore, initChartCore, disposeChart: disposeChartCore, reapplyStyles } = useChartCore(options);
+ const { chart, loading, error, currentPeriod, themeColors, volIndicatorConfig, periodToKlinecharts, syncPrecision: syncPrecisionCore, initChartCore, disposeChart: disposeChartCore, reapplyStyles } = useChartCore(options);
let abortController: AbortController | null = null;
let refreshTimer: ReturnType | null = null;
@@ -224,22 +226,16 @@ export function useChart(options: {
/**
* 副图高度。klinecharts 的 pane 高度是**固定像素**,主图吃掉剩余空间;
- * 默认 100px 在小视口下会占到图区三分之一以上,喧宾夺主。这里按图区高度的
- * 28% 计算并夹在 48–80px:大窗口不会无限长高,小窗口也保得住主图的面积。
+ * 默认 100px 在小视口下会占到图区三分之一以上,喧宾夺主。口径见 utils/paneSize
+ * (分时图的成交量副图共用同一份,切周期时高度不跳)。
*/
- const SUB_PANE_RATIO = 0.28;
- const SUB_PANE_MIN = 48;
- const SUB_PANE_MAX = 80;
-
- function subPaneHeight(): number {
- const total = options.chartRef.value?.clientHeight ?? 0;
- if (!(total > 0)) return 72;
- return Math.round(Math.min(SUB_PANE_MAX, Math.max(SUB_PANE_MIN, total * SUB_PANE_RATIO)));
+ function currentSubPaneHeight(): number {
+ return subPaneHeight(options.chartRef.value?.clientHeight ?? 0);
}
function applySubPaneHeight() {
if (!chart.value) return;
- chart.value.setPaneOptions({ id: SUB_PANE_ID, height: subPaneHeight() });
+ chart.value.setPaneOptions({ id: SUB_PANE_ID, height: currentSubPaneHeight() });
}
/** 图区高度随详情面板/窗口变化时同步副图比例(不监听会一直停留在初始像素值) */
@@ -255,32 +251,11 @@ export function useChart(options: {
paneResizeObserver.observe(el);
}
- /**
- * VOL 副图自定义外观(成交量 + MA5/10/20 均量线,柱子配色随主题)。
- * 注意:不覆盖内置 `figures` —— v10 内置 VOL 的 volume 柱用了一个 styles 回调函数
- * 从 `indicator.styles.bars[0]` 取色,若用静态 figure 覆盖会丢失取色逻辑导致柱子不显示。
- * 因此仅通过 `styles.bars[0]` 传入柱子配色,保留内置 figures/calc。
- */
- function volIndicatorConfig() {
- const colors = themeColors();
- return {
- name: 'VOL',
- paneId: SUB_PANE_ID,
- shortName: '成交量',
- calcParams: [5, 10, 20],
- styles: {
- bars: [
- { upColor: colors.volumeBarUp, downColor: colors.volumeBarDown, noChangeColor: colors.volumeBarNoChange },
- ],
- },
- };
- }
-
function syncSubIndicator(name: SubIndicatorType) {
if (!chart.value) return;
// v10:createIndicator(value, isStack?),paneId 须写入 value 内;同一 paneId 且 isStack=false 会替换旧指标。
// VOL 需带自定义外观(v10 overrideIndicator 仅对已存在指标生效,故在创建时一次性传入)。
- const create = name === 'VOL' ? volIndicatorConfig() : { name, paneId: SUB_PANE_ID };
+ const create = name === 'VOL' ? volIndicatorConfig(SUB_PANE_ID) : { name, paneId: SUB_PANE_ID };
chart.value.createIndicator(create as any);
// 切换指标可能重建 pane(回到默认 100px),每次创建后都按当前图高再定一次
applySubPaneHeight();
@@ -303,12 +278,21 @@ export function useChart(options: {
chart.value.removeIndicator({ paneId: 'candle_pane', name: other });
}
}
- const existing = chart.value.getIndicators({ paneId: 'candle_pane', name });
- if (existing.length === 0) {
- const config = name === 'MA'
- ? { name, calcParams: [5, 10, 20, 60], paneId: 'candle_pane' }
- : { name, paneId: 'candle_pane' };
- chart.value.createIndicator(config, true);
+ if (name === 'MA') {
+ syncMovingAverage(
+ chart.value,
+ settings.movingAveragePeriods,
+ 'candle_pane',
+ themeColors().lineColors,
+ );
+ } else if (chart.value.getIndicators({ paneId: 'candle_pane', name }).length === 0) {
+ chart.value.createIndicator({ name, paneId: 'candle_pane' }, true);
+ }
+ }
+
+ function syncActiveMainOverlay() {
+ if (currentPeriod.value !== 'minute') {
+ syncMainOverlay(unref(options.mainOverlay) ?? 'MA');
}
}
@@ -419,11 +403,16 @@ export function useChart(options: {
// 须用 overrideIndicator 重新传入,否则量柱停留在旧配色
watch(() => [settings.theme, settings.colorScheme], () => {
reapplyStyles();
+ syncActiveMainOverlay();
if (chart.value && unref(options.subIndicator) === 'VOL') {
- chart.value.overrideIndicator(volIndicatorConfig() as any);
+ chart.value.overrideIndicator(volIndicatorConfig(SUB_PANE_ID) as any);
}
});
+ watch(() => settings.movingAveragePeriods, () => {
+ if ((unref(options.mainOverlay) ?? 'MA') === 'MA') syncActiveMainOverlay();
+ }, { deep: true });
+
if (options.subIndicator) {
watch(() => unref(options.subIndicator)!, (newVal) => {
syncSubIndicator(newVal);
@@ -436,6 +425,18 @@ export function useChart(options: {
});
}
+ /**
+ * 完整重放主题样式。reapplyStyles 只更新全局样式,VOL 的柱子配色是创建指标时的
+ * 实例级 styles,压不到已存在的指标,需要再 override 一次。
+ */
+ function applyTheme() {
+ reapplyStyles();
+ syncActiveMainOverlay();
+ if (chart.value && unref(options.subIndicator) === 'VOL') {
+ chart.value.overrideIndicator(volIndicatorConfig(SUB_PANE_ID) as any);
+ }
+ }
+
return {
chart,
loading,
@@ -444,6 +445,6 @@ export function useChart(options: {
initChart,
loadData,
disposeChart,
- applyTheme: reapplyStyles,
+ applyTheme,
};
}
diff --git a/src/composables/useChartCore.ts b/src/composables/useChartCore.ts
index b222914..c4947b2 100644
--- a/src/composables/useChartCore.ts
+++ b/src/composables/useChartCore.ts
@@ -1,12 +1,22 @@
import { ref, watch, onUnmounted, type Ref, type MaybeRef, unref } from 'vue';
import { init, dispose } from 'klinecharts';
-import type { Chart, KLineData as KCLineData, Period } from 'klinecharts';
+import type { CandleTooltipLegendsCustomCallback, Chart, KLineData as KCLineData, Period } from 'klinecharts';
import type { PeriodType } from '@/types';
import { useSettingsStore } from '@/stores/settings';
import { getPricePrecision } from '@/utils/format';
import { hexToRgba } from '@/utils/color';
import { isMinuteK, minuteKSpan } from './minutePeriod';
+/**
+ * tooltip 里的价格文本:固定精度 + 千分位。
+ * klinecharts 自带的 `{open}` 等占位符会按 chart 的 thousandSeparator(`,`)格式化,
+ * 均价是我们自己算好塞进图例的,得用同样的口径才不会在同一行里出现 `1438.03` 与
+ * `1,438.03` 两种写法。
+ */
+function tooltipPriceText(value: number, precision: number): string {
+ return value.toFixed(precision).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
+}
+
/**
* 图表核心 — 创建/销毁、样式主题、精度自适应等公共逻辑。
* K 线图和分时图共用,各自在上层 composable 中补充数据加载和自动刷新。
@@ -36,11 +46,16 @@ export function useChartCore(options: {
const up = rootStyle.getPropertyValue('--color-up').trim() || '#f85149';
const down = rootStyle.getPropertyValue('--color-down').trim() || '#3fb950';
const noChange = '#8b949e';
+ // 多条均线配色按配置顺序使用;分时均价线固定取第 2 个,保持黄色口径。
+ const lineColors = isDark
+ ? ['#F1F1F1', '#FFD302', '#E454CE', '#32CD32', '#01C5C4', '#FF7F50', '#6495ED', '#DAA520', '#7FFFD4', '#FF69B4']
+ : ['#333333', '#CC8800', '#B8308F', '#1E8C4A', '#0A8A8A', '#C84B28', '#4169B1', '#996515', '#188A75', '#C33A79'];
return {
up,
down,
noChange,
lineColor: isDark ? '#58a6ff' : '#0969da',
+ avgLineColor: lineColors[1],
gridHColor: isDark ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.06)',
gridVColor: isDark ? 'rgba(255,255,255,0.03)' : 'rgba(0,0,0,0.04)',
axisColor: isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.1)',
@@ -58,15 +73,34 @@ export function useChartCore(options: {
volumeBarUp: hexToRgba(up, isDark ? 0.5 : 0.55),
volumeBarDown: hexToRgba(down, isDark ? 0.5 : 0.55),
volumeBarNoChange: hexToRgba(noChange, isDark ? 0.45 : 0.5),
- // 多条均线配色
- lineColors: isDark
- ? ['#F1F1F1', '#FFD302', '#E454CE', '#32CD32', '#01C5C4']
- : ['#333333', '#CC8800', '#B8308F', '#1E8C4A', '#0A8A8A'],
+ lineColors,
};
}
// ---- 样式应用 ----
+ /**
+ * 成交量指标(VOL)的实例配置。K 线与分时图的成交量副图共用同一套外观。
+ * 注意:不覆盖内置 `figures` —— v10 内置 VOL 的 volume 柱用 styles 回调从
+ * `indicator.styles.bars[0]` 取色,静态 figure 会丢掉取色逻辑导致柱子不显示;
+ * 只通过 `styles.bars[0]` 传柱子配色,保留内置 figures/calc。
+ * 分时图传 `calcParams: []`(只要量柱,不要均量线),K 线用默认的 [5, 10, 20]。
+ */
+ function volIndicatorConfig(paneId: string, calcParams: number[] = [5, 10, 20]) {
+ const colors = themeColors();
+ return {
+ name: 'VOL',
+ paneId,
+ shortName: '成交量',
+ calcParams,
+ styles: {
+ bars: [
+ { upColor: colors.volumeBarUp, downColor: colors.volumeBarDown, noChangeColor: colors.volumeBarNoChange },
+ ],
+ },
+ };
+ }
+
function applyChartStyles() {
if (!chart.value) return;
const c = themeColors();
@@ -79,14 +113,35 @@ export function useChartCore(options: {
},
candle: {
type: 'area',
- bar: { upColor: c.up, downColor: c.down, upBorderColor: c.up, downBorderColor: c.down, upWickColor: c.up, downWickColor: c.down, noChangeColor: c.noChange, noChangeBorderColor: c.noChange, noChangeWickColor: c.noChange, compareRule: 'previous_close' },
+ bar: { upColor: c.up, downColor: c.down, upBorderColor: c.up, downBorderColor: c.down, upWickColor: c.up, downWickColor: c.down, noChangeColor: c.noChange, noChangeBorderColor: c.noChange, noChangeWickColor: c.noChange, compareRule: 'current_open' },
area: { lineSize: 1.5, lineColor: '#58a6ff' },
tooltip: {
- labels: ['时间', '开', '高', '低', '收', '量', '额'],
+ // 均价并入蜡烛 tooltip 的同一行(放在「量」后面),不再让均价指标单独占一行。
+ // 指标自身的那行图例在 useMinuteChart 里通过「空短名 + 无 title 的 figure」关掉。
+ legend: {
+ template: ((data) => {
+ const current = data.current;
+ const precision = chart.value?.getSymbol()?.pricePrecision ?? 2;
+ const avgValue = current?.avgPrice;
+ const avg = typeof avgValue === 'number' ? tooltipPriceText(avgValue, precision) : '--';
+ return [
+ { title: '时间', value: '{time}' },
+ { title: '开', value: '{open}' },
+ { title: '高', value: '{high}' },
+ { title: '低', value: '{low}' },
+ { title: '收', value: '{close}' },
+ { title: '量', value: '{volume}' },
+ {
+ title: { text: '均价', color: c.avgLineColor },
+ value: { text: avg, color: c.avgLineColor },
+ },
+ ];
+ }) as CandleTooltipLegendsCustomCallback,
+ },
title: { show: false },
rect: { position: 'pointer', paddingLeft: 8, paddingTop: 4, paddingRight: 8, paddingBottom: 4, offsetLeft: 12, offsetTop: 8, offsetRight: 0, offsetBottom: 0, borderRadius: 4, borderSize: 0, backgroundColor: c.tooltipBg },
text: { size: 11, color: c.tooltipText, family: 'var(--font-sans)' },
- } as any, // labels/text 为遗留字段,不在 v10 CandleTooltipStyle 类型中
+ } as any, // text 为遗留字段,不在 v10 CandleTooltipStyle 类型中
priceMark: {
high: { show: false },
low: { show: false },
@@ -94,7 +149,7 @@ export function useChartCore(options: {
},
},
indicator: {
- ohlc: { upColor: c.up, downColor: c.down, noChangeColor: c.noChange, compareRule: 'previous_close' },
+ ohlc: { upColor: c.up, downColor: c.down, noChangeColor: c.noChange, compareRule: 'current_open' },
bars: [
{ upColor: c.indicatorBarUp, downColor: c.indicatorBarDown, noChangeColor: c.indicatorBarNoChange },
],
@@ -133,7 +188,7 @@ export function useChartCore(options: {
chart.value.setStyles({
candle: {
type: 'candle_solid',
- bar: { upColor: c.up, downColor: c.down, upBorderColor: c.up, downBorderColor: c.down, upWickColor: c.up, downWickColor: c.down, noChangeColor: c.noChange, noChangeBorderColor: c.noChange, noChangeWickColor: c.noChange, compareRule: 'previous_close' },
+ bar: { upColor: c.up, downColor: c.down, upBorderColor: c.up, downBorderColor: c.down, upWickColor: c.up, downWickColor: c.down, noChangeColor: c.noChange, noChangeBorderColor: c.noChange, noChangeWickColor: c.noChange, compareRule: 'current_open' },
area: { lineSize: 1.5, lineColor: '#58a6ff' },
tooltip: {
legend: {
@@ -260,6 +315,7 @@ export function useChartCore(options: {
error,
currentPeriod,
themeColors,
+ volIndicatorConfig,
applyChartStyles,
applyCandlestickStyles,
reapplyStyles,
diff --git a/src/composables/useMinuteChart.ts b/src/composables/useMinuteChart.ts
index 2f4ab88..d0763eb 100644
--- a/src/composables/useMinuteChart.ts
+++ b/src/composables/useMinuteChart.ts
@@ -1,16 +1,46 @@
import { ref, watch, onUnmounted, type Ref, type MaybeRef, unref } from 'vue';
import { invoke } from '@tauri-apps/api/core';
+import { registerIndicator } from 'klinecharts';
import type { AxisCreateRangeParams, AxisCreateTicksParams, AxisRange, AxisTick, KLineData as KCLineData, DataLoader, YAxisOverride } from 'klinecharts';
import type { MinuteData } from '@/types';
+import { useSettingsStore } from '@/stores/settings';
+import { hexToRgba } from '@/utils/color';
import { beijingNow, mapMinuteBars, sessionKeyOf, sessionPrevClose, sessionUpdate } from '@/utils/minuteBars';
-import { inferBarMinutes, minuteAxisLayout, percentText, sessionFits, sessionTicks, symmetricRange } from '@/utils/minuteAxis';
+import { adaptiveRange, inferBarMinutes, minuteAxisLayout, percentText, sessionFits, sessionTicks } from '@/utils/minuteAxis';
+import { subPaneHeight } from '@/utils/paneSize';
import { useChartCore } from './useChartCore';
+const CANDLE_PANE = 'candle_pane';
+/** 均价线指标名 — 注册一次,所有分时图共用 */
+const AVG_PRICE_INDICATOR = 'MINUTE_AVG_PRICE';
+/** 成交量副图 pane — 与 K 线的 sub_indicator_pane 分开,互不干扰 */
+const VOLUME_PANE_ID = 'minute_volume_pane';
+
+/**
+ * 均价线指标:价格类指标(series: 'price'),画在 candle pane 上,与价格线共用纵轴。
+ *
+ * VWAP 不在这里算:`MinuteData.avg_price` 在两个适配器里都只是 bar 的开盘价(见
+ * minuteBars.cumulativeAvgPrices 的注释),真正的当日累计均价在前端一次算好放在
+ * bar 的 `avgPrice` 上 —— 这里只负责把算好的值喂给 klinecharts。
+ */
+registerIndicator({
+ name: AVG_PRICE_INDICATOR,
+ // 图例并入蜡烛 tooltip(见 useChartCore 的 legend.template),指标自己那行要彻底空掉:
+ // shortName 为空 → 不画名字;figure 不带 title → 不画数值行。
+ shortName: '',
+ series: 'price',
+ figures: [{ key: 'avgPrice', type: 'line' }],
+ calc: (dataList) =>
+ dataList.map((bar) => ({
+ avgPrice: typeof bar.avgPrice === 'number' ? bar.avgPrice : bar.close,
+ })),
+});
+
/**
* 分时图 composable — 仅用于 MinuteChart 组件。
* 不含副图指标、K 线懒加载等逻辑,与 K 线图表完全隔离。
* 数据映射(bar 构造 + 只取当前交易日)见 @/utils/minuteBars;
- * 坐标轴(横轴固定一个交易日、纵轴以昨收对称)见 @/utils/minuteAxis。
+ * 坐标轴(横轴固定一个交易日、纵轴自适应但保留 0% 基准)见 @/utils/minuteAxis。
*/
export function useMinuteChart(options: {
chartRef: Ref;
@@ -23,7 +53,8 @@ export function useMinuteChart(options: {
*/
prevClose?: MaybeRef;
}) {
- const { chart, loading, error, periodToKlinecharts, syncPrecision, initChartCore, disposeChart: coreDispose, reapplyStyles } = useChartCore(options);
+ const settings = useSettingsStore();
+ const { chart, loading, error, periodToKlinecharts, syncPrecision, themeColors, volIndicatorConfig, initChartCore, disposeChart: coreDispose, reapplyStyles } = useChartCore(options);
let abortController: AbortController | null = null;
let refreshTimer: ReturnType | null = null;
@@ -112,18 +143,21 @@ export function useMinuteChart(options: {
resizeObserver?.disconnect();
resizeObserver = new ResizeObserver(() => {
// 先让 klinecharts 自己的 ResizeObserver 更新内部尺寸,下一帧再按新宽度重排,
- // 否则这里读到的还是旧宽度
- requestAnimationFrame(() => applySessionAxis());
+ // 否则这里读到的还是旧宽度;副图高度也跟着图区高度重算
+ requestAnimationFrame(() => {
+ applyVolumePaneHeight();
+ applySessionAxis();
+ });
});
resizeObserver.observe(el);
}
// ---- 纵轴:价格 + 涨跌幅双刻度 ----
- // 分时图的纵轴以昨收为中心对称(0.00% 在正中):右侧价格刻度、左侧涨跌幅刻度,
- // 两条轴共用同一个区间,所以刻度逐行对应。昨收拿不到时两条轴都不装 ——
+ // 右侧价格刻度、左侧涨跌幅刻度,两条轴共用同一个区间,所以刻度逐行对应。
+ // 区间不强制以昨收为中心(见 adaptiveRange):单边行情下曲线仍能占满画布,
+ // 同时 0% 线两侧各留一条最小可见带。昨收拿不到时两条轴都不装 ——
// 已经装着的也要摘掉,见 applyPriceScale。
- const CANDLE_PANE = 'candle_pane';
const PERCENT_AXIS_ID = 'minute_percent';
const BASELINE_OVERLAY_ID = 'minute_prev_close';
@@ -184,7 +218,7 @@ export function useMinuteChart(options: {
c.createYAxis(percentAxis);
// 两条轴共用的区间。gap 也得一起设:默认是「上 20% / 下 10%」的非对称留白,
- // 会把对称区间推歪。昨收无效时把 klinecharts 算好的区间原样交回去,
+ // 会叠加到自适应区间上再放大一次。昨收无效时把 klinecharts 算好的区间原样交回去,
// 免得停牌股那种拿不到昨收的标的被画成压在顶上的一条线。
c.overrideYAxis({
paneId: CANDLE_PANE,
@@ -192,7 +226,7 @@ export function useMinuteChart(options: {
createRange: (params: AxisCreateRangeParams): AxisRange => {
const base = prevCloseValue();
if (base <= 0) return params.defaultRange;
- const { from, to } = symmetricRange(klineData.value, base);
+ const { from, to } = adaptiveRange(klineData.value, base);
return {
from, to, range: to - from,
realFrom: from, realTo: to, realRange: to - from,
@@ -201,7 +235,8 @@ export function useMinuteChart(options: {
},
});
- // 昨收基准线(区间正中)。锁住不给拖,默认的点/坐标轴小标签也不画。
+ // 昨收基准线(0% 基准)。纵轴区间是自适应的,这条线不保证落在正中。
+ // 锁住不给拖,默认的点/坐标轴小标签也不画。
// 颜色跟蜡烛的 noChange 一样写死一个中性灰:深浅主题都读得出来,
// 也就不必在切主题时重建这条线。
c.removeOverlay({ id: BASELINE_OVERLAY_ID });
@@ -218,10 +253,112 @@ export function useMinuteChart(options: {
});
}
+ // ---- 主图:价格线配色 + 均价线 + 成交量副图 ----
+ // A 股分时图的两项标配:价格线随涨跌变色(相对昨收),以及黄色的当日累计均价线。
+ // 成交量另起一个副图窗格,横轴与主图共用(klinecharts 的 x 轴跨 pane 对齐)。
+
+ /** 已装到图上的价格线颜色,避免 5s 刷新里价格方向没变也重设一次样式 */
+ let installedLineColor = '';
+
+ /** 价格线颜色:高于昨收缴红、低于缴绿、持平中性灰;昨收/数据没到位时退回主题强调色 */
+ function minuteLineColor(colors: ReturnType): string {
+ const prev = prevCloseValue();
+ const last = klineData.value[klineData.value.length - 1];
+ if (prev <= 0 || !last || !Number.isFinite(last.close)) return colors.lineColor;
+ if (last.close > prev) return colors.up;
+ if (last.close < prev) return colors.down;
+ return colors.noChange;
+ }
+
+ /**
+ * 价格线与其下方的渐变填充。
+ * @param force 主题切换/重建图表后强制重设:applyChartStyles 会把 lineColor 写回
+ * 默认蓝,颜色数值没变也得覆盖回来
+ */
+ function applyMinuteLineStyle(force = false) {
+ const c = chart.value;
+ if (!c) return;
+ const color = minuteLineColor(themeColors());
+ if (!force && color === installedLineColor) return;
+ installedLineColor = color;
+ c.setStyles({
+ candle: {
+ area: {
+ lineSize: 1.5,
+ lineColor: color,
+ // 渐变方向与内置默认一致:offset 0 在底部、1 靠近曲线
+ backgroundColor: [
+ { offset: 0, color: hexToRgba(color, 0.02) },
+ { offset: 1, color: hexToRgba(color, 0.18) },
+ ],
+ },
+ },
+ });
+ }
+
+ /** 已应用过的副图高度;-1 表示还没设过 */
+ let appliedVolumePaneHeight = -1;
+
+ /** 成交量副图高度与 K 线的指标副图共用同一份口径(28%,夹在 48–80px) */
+ function applyVolumePaneHeight(force = false) {
+ if (!chart.value) return;
+ const height = subPaneHeight(options.chartRef.value?.clientHeight ?? 0);
+ // 水平 resize(高度不变)时不重复 setPaneOptions:它每次都会 setBounding + 置 shouldLayout
+ if (!force && height === appliedVolumePaneHeight) return;
+ appliedVolumePaneHeight = height;
+ chart.value.setPaneOptions({ id: VOLUME_PANE_ID, height });
+ }
+
+ /** 补上均价线与成交量副图。换标的时图表实例是复用的,已存在就不要再创建 */
+ function syncMinuteIndicators() {
+ const c = chart.value;
+ if (!c) return;
+ if (c.getIndicators({ paneId: CANDLE_PANE, name: AVG_PRICE_INDICATOR }).length === 0) {
+ c.createIndicator({
+ name: AVG_PRICE_INDICATOR,
+ paneId: CANDLE_PANE,
+ // 空短名:tooltip 图例已经并进蜡烛那行,指标自己不再占一行
+ shortName: '',
+ styles: { lines: [{ color: themeColors().avgLineColor, size: 1 }] },
+ } as any, true);
+ }
+ if (c.getIndicators({ paneId: VOLUME_PANE_ID }).length === 0) {
+ // calcParams 传空数组:分时图只画量柱,不要内置的 MA5/10/20 均量线
+ c.createIndicator(volIndicatorConfig(VOLUME_PANE_ID, []) as any);
+ }
+ // 新建/复用副图时强制应用一次高度(-1 初始值之外,重建时也要设回去)
+ applyVolumePaneHeight(true);
+ }
+
+ /**
+ * 分钟图特有的主题样式:价格线颜色按涨跌重算,均价线/量柱的实例级配色也要跟着令牌走。
+ * useChartCore 的 theme watcher 只负责通用样式(且会把 area.lineColor 写回默认蓝),
+ * 所以这里必须强制重设,不能依赖 installedLineColor 的缓存。
+ */
+ function applyMinuteThemeStyles() {
+ const c = chart.value;
+ if (!c) return;
+ applyMinuteLineStyle(true);
+ c.overrideIndicator({
+ name: AVG_PRICE_INDICATOR,
+ paneId: CANDLE_PANE,
+ styles: { lines: [{ color: themeColors().avgLineColor, size: 1 }] },
+ } as any);
+ if (c.getIndicators({ paneId: VOLUME_PANE_ID }).length > 0) {
+ c.overrideIndicator(volIndicatorConfig(VOLUME_PANE_ID, []) as any);
+ }
+ }
+
+ // 主题/涨跌配色翻转:通用样式由 useChartCore 的 watcher 重放,这里补分钟图特有的部分
+ watch(() => [settings.theme, settings.colorScheme], applyMinuteThemeStyles);
+
// 兜底昨收是异步到的(行情比分钟内数据晚一拍),到了再算一次;
// 数据里能算出昨收时,上面的守卫会把它挡掉
if (options.prevClose) {
- watch(() => unref(options.prevClose), () => applyPriceScale());
+ watch(() => unref(options.prevClose), () => {
+ applyPriceScale();
+ applyMinuteLineStyle();
+ });
}
// ---- 自动刷新 ----
@@ -258,6 +395,7 @@ export function useMinuteChart(options: {
}
applySessionAxis();
applyPriceScale(reset);
+ applyMinuteLineStyle();
} catch (e) {
console.error('[useMinuteChart] incremental update failed:', e);
}
@@ -293,6 +431,11 @@ export function useMinuteChart(options: {
if (data.length) {
klineData.value = mapMinuteBars(data);
dataPrevClose = sessionPrevClose(data);
+ } else {
+ // 空响应必须跟着标的清空:图表实例是复用的,留着上一只股票的 bar/昨收,
+ // 下面的 setSymbol + setDataLoader 会把旧数据当成新标的重新喂进去。
+ klineData.value = [];
+ dataPrevClose = null;
}
if (signal.aborted) return;
@@ -305,6 +448,7 @@ export function useMinuteChart(options: {
applySessionAxis();
// 数据整份换过:昨收可能恰好相等,但基准线的时间戳得跟着新数据走
applyPriceScale(true);
+ applyMinuteLineStyle(true);
}
startAutoRefresh();
} catch (e) {
@@ -328,6 +472,8 @@ export function useMinuteChart(options: {
// 缩完柱宽就不再等于「图宽 / 格子数」。分时图本来也不给拖,索性关掉这两个手势。
chart.value.setScrollEnabled(false);
chart.value.setZoomEnabled(false);
+ syncMinuteIndicators();
+ applyMinuteLineStyle(true);
applyPriceScale();
observeResize();
}
@@ -348,12 +494,21 @@ export function useMinuteChart(options: {
// 不会停这里起的 5s 轮询,也不会断开新加的 ResizeObserver —— 切一次周期就漏一份
onUnmounted(() => disposeChart());
+ /**
+ * 完整重放主题样式(通用 + 分钟图特有)。只调 core 的 reapplyStyles 会把价格线打回
+ * 默认蓝,而 installedLineColor 缓存会让下一次非强制刷新无法恢复。
+ */
+ function applyTheme() {
+ reapplyStyles();
+ applyMinuteThemeStyles();
+ }
+
return {
loading,
error,
initChart,
loadData,
disposeChart,
- applyTheme: reapplyStyles,
+ applyTheme,
};
}
diff --git a/src/stores/settings.spec.ts b/src/stores/settings.spec.ts
index 3538ce1..a8dabb9 100644
--- a/src/stores/settings.spec.ts
+++ b/src/stores/settings.spec.ts
@@ -134,6 +134,13 @@ describe('派生配置的解析与兜底', () => {
expect((await load({})).tickerItemsPerPage).toBe(2);
});
+ it('moving_average_periods 缺失或损坏时使用默认值,并保留自定义条数', async () => {
+ expect((await load({})).movingAveragePeriods).toEqual([5, 10, 20, 60]);
+ expect((await load({ moving_average_periods: '{' })).movingAveragePeriods).toEqual([5, 10, 20, 60]);
+ expect((await load({ moving_average_periods: '{"periods":[7,14]}' })).movingAveragePeriods)
+ .toEqual([7, 14]);
+ });
+
it('布尔型设置只认 "1"/"0",缺键时取各自默认值', async () => {
const store = await load({
market_overview_visible: '0',
@@ -201,6 +208,24 @@ describe('写入与跨窗口同步', () => {
});
});
+ it('setMovingAveragePeriods 归一化、持久化并广播配置', async () => {
+ const store = await load({});
+ invokeMock.mockResolvedValueOnce(undefined);
+
+ await store.setMovingAveragePeriods([7, 14, 28.5, 0, 99999]);
+
+ const value = JSON.stringify({ periods: [7, 14, 9999] });
+ expect(invokeMock).toHaveBeenCalledWith('set_setting', {
+ key: 'moving_average_periods',
+ value,
+ });
+ expect(store.movingAveragePeriods).toEqual([7, 14, 9999]);
+ expect(emitMock).toHaveBeenCalledWith('settings-changed', {
+ key: 'moving_average_periods',
+ value,
+ });
+ });
+
it('applyRemoteSetting 只改本地 —— 不回写、不回广播', async () => {
const store = await load({});
invokeMock.mockClear();
@@ -214,6 +239,18 @@ describe('写入与跨窗口同步', () => {
expect(emitMock).not.toHaveBeenCalled();
});
+ it('applyRemoteSetting 更新均线配置而不回写、不回广播', async () => {
+ const store = await load({});
+ invokeMock.mockClear();
+ emitMock.mockClear();
+
+ store.applyRemoteSetting('moving_average_periods', '{"periods":[9,21]}');
+
+ expect(store.movingAveragePeriods).toEqual([9, 21]);
+ expect(invokeMock).not.toHaveBeenCalled();
+ expect(emitMock).not.toHaveBeenCalled();
+ });
+
it('setTickerVisible 走 set_ticker_visible 命令(托盘菜单的同一份实现)', async () => {
const store = await load({ ticker_visible: '1' });
invokeMock.mockResolvedValueOnce(undefined);
diff --git a/src/stores/settings.ts b/src/stores/settings.ts
index 946f810..4319b19 100644
--- a/src/stores/settings.ts
+++ b/src/stores/settings.ts
@@ -18,6 +18,10 @@ import {
type ThemeMode,
} from '@/utils/prefs';
import { resolveTheme, systemPrefersDark, watchSystemTheme, type ResolvedTheme } from '@/utils/theme';
+import {
+ normalizeMovingAveragePeriods,
+ parseMovingAveragePeriods,
+} from '@/utils/movingAverage';
/** 设置项默认值(前端侧兜底)。后端 `init_defaults()` 会在首启时写入同名的键,
* 这里的值只在键缺失(旧库、手工删键)时生效。 */
@@ -114,6 +118,9 @@ export const useSettingsStore = defineStore('settings', () => {
/** 老板键;空串表示未设置(见 utils/prefs 的 parseAccelerator)。 */
const bossKey = computed(() => parseAccelerator(settings.value['boss_key']));
+ const movingAveragePeriods = computed(() =>
+ parseMovingAveragePeriods(settings.value['moving_average_periods']));
+
async function fetchSettings() {
try {
settings.value = await invoke>('get_settings');
@@ -176,6 +183,11 @@ export const useSettingsStore = defineStore('settings', () => {
await setSetting('sector_top_n', String(clampTopN(n)));
}
+ async function setMovingAveragePeriods(periods: unknown[]) {
+ const normalized = normalizeMovingAveragePeriods(periods);
+ await setSetting('moving_average_periods', JSON.stringify({ periods: normalized }));
+ }
+
/**
* 显示/隐藏行情条。走 IPC 命令而不是前端窗口 API —— 窗口的显示需要补
* always_on_top / skip_taskbar / WS_EX_TOOLWINDOW / 位置还原,这些只在
@@ -352,11 +364,13 @@ export const useSettingsStore = defineStore('settings', () => {
indexCodes, marketOverviewVisible, sectorTopN, tickerVisible, tickerTransparent,
tickerClickWakes,
tickerItemsPerPage, watchlistColumns, watchlistDefaultSort, colorScheme, bossKey,
+ movingAveragePeriods,
// 动作
fetchSettings, setSetting, switchDatasource, setThemeMode, toggleAutoLaunch,
applyColorScheme, applyRemoteSetting,
setIndexCodes, setMarketOverviewVisible, setSectorTopN, setTickerVisible,
setTickerTransparent, setTickerClickWakes, setTickerItemsPerPage, setWatchlistColumns,
setWatchlistDefaultSort, setColorScheme, setBossKey,
+ setMovingAveragePeriods,
};
});
diff --git a/src/utils/minuteAxis.spec.ts b/src/utils/minuteAxis.spec.ts
index d70fe7a..ece82a3 100644
--- a/src/utils/minuteAxis.spec.ts
+++ b/src/utils/minuteAxis.spec.ts
@@ -2,12 +2,12 @@ import { describe, expect, it } from 'vitest';
import {
SESSION_MINUTES,
SESSION_TICKS,
+ adaptiveRange,
inferBarMinutes,
minuteAxisLayout,
percentText,
sessionFits,
sessionTicks,
- symmetricRange,
tradingMinutesOfDay,
} from './minuteAxis';
@@ -158,20 +158,30 @@ describe('sessionTicks', () => {
});
});
-describe('symmetricRange', () => {
- it('半幅取收盘价相对昨收的最大偏离,两侧对称', () => {
- const range = symmetricRange([{ close: 103 }, { close: 97 }, { close: 100 }], 100);
- expect(range).toEqual({ from: 97, to: 103 });
+describe('adaptiveRange', () => {
+ it('上涨日:下沿只留 1% 保底,上沿跟到最高价 —— 曲线不再被挤在上半区', () => {
+ expect(adaptiveRange([{ close: 100 }, { close: 103 }, { close: 106 }], 100))
+ .toEqual({ from: 99, to: 106 });
});
- it('涨跌不到 1% 时兜底到昨收的 1%,免得开盘头一分钟被放大到满屏', () => {
- const range = symmetricRange([{ close: 100.1 }, { close: 100.05 }], 100);
- expect(range.from).toBeCloseTo(99, 6);
- expect(range.to).toBeCloseTo(101, 6);
+ it('下跌日:上沿留 1%,下沿跟到最低价', () => {
+ expect(adaptiveRange([{ close: 100 }, { close: 97 }, { close: 94 }], 100))
+ .toEqual({ from: 94, to: 101 });
});
- it('已超过 1% 时按实际幅度走,不额外留白', () => {
- expect(symmetricRange([{ close: 106 }], 100)).toEqual({ from: 94, to: 106 });
+ it('全天走平时两侧各留 1%,免得被放大到满屏', () => {
+ expect(adaptiveRange([{ close: 100.1 }, { close: 100.05 }], 100))
+ .toEqual({ from: 99, to: 101 });
+ });
+
+ it('均价线也参与取幅 —— 典型价累计的均价可能超出收盘价范围', () => {
+ expect(adaptiveRange([{ close: 100, avgPrice: 106 }], 100))
+ .toEqual({ from: 99, to: 106 });
+ });
+
+ it('均价缺失或非数字时只看收盘价', () => {
+ expect(adaptiveRange([{ close: 103, avgPrice: undefined }, { close: 97, avgPrice: NaN }], 100))
+ .toEqual({ from: 97, to: 103 });
});
});
diff --git a/src/utils/minuteAxis.ts b/src/utils/minuteAxis.ts
index 2fbe4bd..f7abde0 100644
--- a/src/utils/minuteAxis.ts
+++ b/src/utils/minuteAxis.ts
@@ -128,31 +128,46 @@ export function sessionTicks(plotWidth: number, barSpace: number, barMinutes: nu
}));
}
-// ---- 纵轴:以昨收为中心的对称区间 ----
+// ---- 纵轴:自适应区间 ----
/**
- * 涨跌幅很小时的半幅下限(昨收的 1%)。开盘头一分钟涨跌往往不到 0.05%,
- * 不兜底的话纵轴会被放大到看不出任何幅度。
+ * 0% 两侧的保底幅度(昨收的 1%)。开盘头一分钟涨跌往往不到 0.05%,
+ * 不兜底的话纵轴会被放大到看不出任何幅度;单边行情下也靠它把 0% 线留在图内。
*/
const MIN_RANGE_RATE = 0.01;
/**
- * 以昨收为中心的对称价格区间 —— 分时图的标准画法:0.00% 落在正中,涨跌一眼看出对称。
- * 半幅取收盘价相对昨收的最大偏离(分时图画的是一条收盘价连线,所以只看 close),
- * 再兜一个最小半幅。
+ * 分时图纵轴区间:覆盖价格线与均价线,但不强制以昨收为中心对称。
+ *
+ * 早先是上下完全均分(0.00% 在正中),单边行情(尤其接近涨跌停)下曲线会整段压在
+ * 上半区或下半区,浪费一半画布。这里改成自适应:
+ * - 上沿取数据相对昨收的最大正偏离,下沿取最大负偏离;
+ * - 两侧各保底 MIN_RANGE_RATE(昨收的 1%):0% 线仍有可见空间,全天走平时也不会被放大。
+ *
+ * 收盘价与均价一起参与取幅:均价由典型价累计,可能略微超出收盘价范围,不一起算会被
+ * 裁到图外。
*/
-export function symmetricRange(
- bars: readonly { close: number }[],
+export function adaptiveRange(
+ bars: readonly { close: number; avgPrice?: unknown }[],
prevClose: number,
- minRate = MIN_RANGE_RATE,
+ minSideRate = MIN_RANGE_RATE,
): { from: number; to: number } {
- let half = 0;
+ let up = 0;
+ let down = 0;
+ const consider = (value: unknown) => {
+ if (typeof value !== 'number' || !Number.isFinite(value)) return;
+ const diff = value - prevClose;
+ if (diff > up) up = diff;
+ if (-diff > down) down = -diff;
+ };
for (const bar of bars) {
- const deviation = Math.abs(bar.close - prevClose);
- if (deviation > half) half = deviation;
+ consider(bar.close);
+ consider(bar.avgPrice);
}
- half = Math.max(half, Math.abs(prevClose) * minRate);
- return { from: prevClose - half, to: prevClose + half };
+ const floor = Math.abs(prevClose) * minSideRate;
+ up = Math.max(up, floor);
+ down = Math.max(down, floor);
+ return { from: prevClose - down, to: prevClose + up };
}
/** 价格相对昨收的涨跌幅文本,如 `+1.23%` / `-0.45%` */
diff --git a/src/utils/minuteBars.spec.ts b/src/utils/minuteBars.spec.ts
index aa4f2ee..a0e8ed2 100644
--- a/src/utils/minuteBars.spec.ts
+++ b/src/utils/minuteBars.spec.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import type { MinuteData } from '@/types';
import {
beijingNow,
+ cumulativeAvgPrices,
mapMinuteBars,
sessionKeyOf,
sessionPrevClose,
@@ -124,6 +125,57 @@ describe('mapMinuteBars', () => {
});
});
+describe('cumulativeAvgPrices', () => {
+ it('按成交量加权累计,均价从开盘单调地跟着成交走', () => {
+ // 典型价 = (high + low + close) / 3;这里 high = low = close,退化为收盘价
+ const avg = cumulativeAvgPrices([
+ { close: 10, high: 10, low: 10, volume: 100 },
+ { close: 12, high: 12, low: 12, volume: 100 },
+ { close: 11, high: 11, low: 11, volume: 200 },
+ ]);
+ expect(avg).toEqual([10, 11, 11]);
+ });
+
+ it('用典型价而不是收盘价估算成交额', () => {
+ // 一根振幅很大的 bar:(10 + 14 + 12) / 3 = 12
+ expect(cumulativeAvgPrices([{ close: 12, high: 14, low: 10, volume: 100 }])).toEqual([12]);
+ });
+
+ it('开盘第一根就没有成交时退回该根收盘价,不产出 0', () => {
+ const avg = cumulativeAvgPrices([
+ { close: 10, high: 10, low: 10, volume: 0 },
+ { close: 12, high: 12, low: 12, volume: 100 },
+ ]);
+ expect(avg).toEqual([10, 12]);
+ });
+
+ it('盘中停牌(已有累计成交量后出现零量 bar)均价保持上一根的值', () => {
+ // 11:00 停牌:该 bar 不贡献成交额,均价停在 10,而不是跳到该根收盘价 12
+ const avg = cumulativeAvgPrices([
+ { close: 10, high: 10, low: 10, volume: 100 },
+ { close: 12, high: 12, low: 12, volume: 0 },
+ ]);
+ expect(avg).toEqual([10, 10]);
+ });
+
+ it('缺 high/low/volume 时退回收盘价与 0,不产出 NaN', () => {
+ expect(cumulativeAvgPrices([{ close: 8 }])).toEqual([8]);
+ expect(cumulativeAvgPrices([])).toEqual([]);
+ });
+});
+
+describe('mapMinuteBars 的均价字段', () => {
+ it('只按当前交易日的成交累计 —— 上一交易日的量不参与', () => {
+ const bars = mapMinuteBars([
+ { time: '2026-09-23 15:00', price: 99, open: 99, high: 99, low: 99, volume: 1_000_000, avg_price: 99 },
+ { time: '2026-09-24 09:30', price: 10, open: 10, high: 10, low: 10, volume: 100, avg_price: 10 },
+ { time: '2026-09-24 09:31', price: 12, open: 12, high: 12, low: 12, volume: 100, avg_price: 12 },
+ ]);
+
+ expect(bars.map((b) => b.avgPrice)).toEqual([10, 11]);
+ });
+});
+
describe('sessionKeyOf', () => {
it('给出的交易日与 mapMinuteBars 的切分口径一致', () => {
const [first, last] = mapMinuteBars([bar('2026-09-24 09:30'), bar('2026-09-24 09:31')]);
diff --git a/src/utils/minuteBars.ts b/src/utils/minuteBars.ts
index 7955e83..faaac66 100644
--- a/src/utils/minuteBars.ts
+++ b/src/utils/minuteBars.ts
@@ -75,6 +75,35 @@ function lastSessionDay(stamped: Stamped[]): string {
return stamped[stamped.length - 1].day;
}
+/**
+ * 分时均价(当日累计 VWAP)。
+ *
+ * 后端 `MinuteData.avg_price` 目前并不是真的均价:腾讯 mkline 没有这个字段,新浪的
+ * 5 分钟 K 线也没有,两个适配器都拿 bar 的 `open` 顶上(见 tencent.rs / sina.rs)。
+ * 直接画会得到一条和价格线几乎重合的伪均价线,所以在这里自己累计:
+ * `Σ(典型价 × 成交量) / Σ成交量`,典型价取 `(high + low + close) / 3`。
+ *
+ * 传入的必须是**同一个交易日**、按时间升序的 bar(mapMinuteBars 的输出即是),
+ * 累计结果才对得上「从开盘到现在」的均价。成交量为 0 的 bar(停牌、缺数据)
+ * 不贡献成交额,均价保持上一根的累计值;累计成交量仍为 0(首根就没有成交)
+ * 时退回该根收盘价,避免把均价画成 0。
+ */
+export function cumulativeAvgPrices(
+ bars: readonly { high?: number; low?: number; close: number; volume?: number }[],
+): number[] {
+ let amount = 0;
+ let volume = 0;
+ return bars.map((bar) => {
+ const high = Number.isFinite(bar.high) ? (bar.high as number) : bar.close;
+ const low = Number.isFinite(bar.low) ? (bar.low as number) : bar.close;
+ const typical = (high + low + bar.close) / 3;
+ const vol = Number.isFinite(bar.volume) ? (bar.volume as number) : 0;
+ amount += typical * vol;
+ volume += vol;
+ return volume > 0 ? amount / volume : bar.close;
+ });
+}
+
/** 时间戳所属的交易日 `YYYY-MM-DD`(与 stamp 同口径:按本机时区还原出的那一天) */
export function sessionKeyOf(timestamp: number): string {
const d = new Date(timestamp);
@@ -82,7 +111,8 @@ export function sessionKeyOf(timestamp: number): string {
}
/**
- * 分时图 bar:只保留数据里最后一个交易日,按时间升序、时间戳去重。
+ * 分时图 bar:只保留数据里最后一个交易日,按时间升序、时间戳去重,并补上当日累计均价
+ * (`avgPrice`,见 cumulativeAvgPrices)。
* @param base 时间戳缺日期时的基准日(默认当前时间),仅为兼容旧后端存在。
*/
export function mapMinuteBars(data: MinuteData[], base: Date = new Date()): KCLineData[] {
@@ -102,13 +132,16 @@ export function mapMinuteBars(data: MinuteData[], base: Date = new Date()): KCLi
if (s.day === session) byTimestamp.set(s.bar.timestamp, s.bar);
}
- return [...byTimestamp.values()].sort((a, b) => a.timestamp - b.timestamp);
+ const bars = [...byTimestamp.values()].sort((a, b) => a.timestamp - b.timestamp);
+ const avgPrices = cumulativeAvgPrices(bars);
+ return bars.map((bar, i) => ({ ...bar, avgPrice: avgPrices[i] }));
}
/**
* 所画交易日的昨收 —— 窗口里紧邻它前面那根 bar 的收盘价,也就是上一个交易日的收盘。
*
- * 纵轴以昨收为中心对称,而「昨收」是相对**画出来那一天**说的:盘前窗口里画的是昨日行情,
+ * 纵轴的 0%(涨跌幅刻度与自适应区间的锚点)是相对**画出来那一天**说的:盘前窗口里画的是
+ * 昨日行情,
* 这时实时行情的 `price - change` 说的是今日昨收,两者差着昨日一整个涨跌幅,曲线会被推到
* 中心线一侧。所以基准优先从数据里取。
*
diff --git a/src/utils/movingAverage.spec.ts b/src/utils/movingAverage.spec.ts
new file mode 100644
index 0000000..862edb6
--- /dev/null
+++ b/src/utils/movingAverage.spec.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { Chart } from 'klinecharts';
+import {
+ DEFAULT_MOVING_AVERAGE_PERIODS,
+ MAX_MOVING_AVERAGE_COUNT,
+ MAX_MOVING_AVERAGE_PERIOD,
+ MIN_MOVING_AVERAGE_PERIOD,
+ nextMovingAveragePeriod,
+ parseMovingAveragePeriods,
+ normalizeMovingAveragePeriods,
+ syncMovingAverage,
+} from './movingAverage';
+
+describe('moving average settings', () => {
+ it('uses the existing four-line configuration for missing or invalid values', () => {
+ expect(parseMovingAveragePeriods(undefined)).toEqual([5, 10, 20, 60]);
+ expect(parseMovingAveragePeriods('{')).toEqual([5, 10, 20, 60]);
+ expect(parseMovingAveragePeriods('{"periods":"5"}')).toEqual([5, 10, 20, 60]);
+ expect(parseMovingAveragePeriods('{"periods":[5]}')).toEqual([5]);
+ expect(parseMovingAveragePeriods('[7,14]')).toEqual([7, 14]);
+ });
+
+ it('keeps valid positive integer periods in order and limits the count to ten', () => {
+ expect(normalizeMovingAveragePeriods([20, 5, 10.7, 0, -3, '30', 60])).toEqual([20, 5, 60]);
+ expect(normalizeMovingAveragePeriods(Array.from({ length: 12 }, (_, i) => i + 1)))
+ .toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
+ expect(normalizeMovingAveragePeriods([MAX_MOVING_AVERAGE_PERIOD + 1]))
+ .toEqual([MAX_MOVING_AVERAGE_PERIOD]);
+ expect(normalizeMovingAveragePeriods([])).toEqual(DEFAULT_MOVING_AVERAGE_PERIODS);
+ expect(normalizeMovingAveragePeriods([MIN_MOVING_AVERAGE_PERIOD - 1]))
+ .toEqual(DEFAULT_MOVING_AVERAGE_PERIODS);
+ expect(MAX_MOVING_AVERAGE_COUNT).toBe(10);
+ });
+
+ it('chooses the next unused preset, then finds an unused period', () => {
+ expect(nextMovingAveragePeriod([5, 10, 20, 60])).toBe(120);
+ expect(nextMovingAveragePeriod([5, 10, 20, 60, 120, 250, 500, 750, 1000, 1500]))
+ .toBe(1501);
+ });
+});
+
+describe('syncMovingAverage', () => {
+ it('creates an MA overlay with the configured periods and line colors', () => {
+ const chart = {
+ getIndicators: vi.fn(() => []),
+ createIndicator: vi.fn(),
+ overrideIndicator: vi.fn(),
+ } as unknown as Chart;
+
+ syncMovingAverage(chart, [5, 12, 26], 'candle_pane', ['#111', '#222', '#333']);
+
+ expect(chart.createIndicator).toHaveBeenCalledWith({
+ name: 'MA',
+ calcParams: [5, 12, 26],
+ paneId: 'candle_pane',
+ styles: {
+ lines: [
+ { style: 'solid', smooth: false, size: 1, color: '#111' },
+ { style: 'solid', smooth: false, size: 1, color: '#222' },
+ { style: 'solid', smooth: false, size: 1, color: '#333' },
+ ],
+ },
+ }, true);
+ });
+
+ it('overrides the existing indicator when periods change', () => {
+ const chart = {
+ getIndicators: vi.fn(() => [{ name: 'MA' }]),
+ createIndicator: vi.fn(),
+ overrideIndicator: vi.fn(),
+ } as unknown as Chart;
+
+ syncMovingAverage(chart, [7, 14], 'candle_pane', ['#111', '#222']);
+
+ expect(chart.overrideIndicator).toHaveBeenCalledWith(expect.objectContaining({
+ name: 'MA',
+ calcParams: [7, 14],
+ paneId: 'candle_pane',
+ }));
+ expect(chart.createIndicator).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/utils/movingAverage.ts b/src/utils/movingAverage.ts
new file mode 100644
index 0000000..f08b6f8
--- /dev/null
+++ b/src/utils/movingAverage.ts
@@ -0,0 +1,77 @@
+import type { Chart } from 'klinecharts';
+
+export const DEFAULT_MOVING_AVERAGE_PERIODS = [5, 10, 20, 60] as const;
+export const MIN_MOVING_AVERAGE_PERIOD = 1;
+export const MAX_MOVING_AVERAGE_PERIOD = 9999;
+export const MAX_MOVING_AVERAGE_COUNT = 10;
+
+const PERIOD_PRESETS = [120, 250, 500, 750, 1000, 1500];
+
+export function normalizeMovingAveragePeriods(value: unknown): number[] {
+ if (!Array.isArray(value)) return [...DEFAULT_MOVING_AVERAGE_PERIODS];
+
+ const periods = value
+ .filter((period): period is number => typeof period === 'number' && Number.isInteger(period))
+ .filter((period) => period >= MIN_MOVING_AVERAGE_PERIOD)
+ .map((period) => Math.min(period, MAX_MOVING_AVERAGE_PERIOD))
+ .slice(0, MAX_MOVING_AVERAGE_COUNT);
+
+ return periods.length > 0 ? periods : [...DEFAULT_MOVING_AVERAGE_PERIODS];
+}
+
+export function parseMovingAveragePeriods(raw: string | undefined): number[] {
+ if (!raw) return [...DEFAULT_MOVING_AVERAGE_PERIODS];
+
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (Array.isArray(parsed)) return normalizeMovingAveragePeriods(parsed);
+ if (!parsed || typeof parsed !== 'object' || !('periods' in parsed)) {
+ return [...DEFAULT_MOVING_AVERAGE_PERIODS];
+ }
+ return normalizeMovingAveragePeriods(parsed.periods);
+ } catch {
+ return [...DEFAULT_MOVING_AVERAGE_PERIODS];
+ }
+}
+
+export function nextMovingAveragePeriod(periods: readonly number[]): number {
+ const used = new Set(periods);
+ const preset = PERIOD_PRESETS.find((period) => !used.has(period));
+ if (preset !== undefined) return preset;
+
+ const maxPeriod = Math.max(0, ...periods);
+ if (maxPeriod < MAX_MOVING_AVERAGE_PERIOD) return maxPeriod + 1;
+
+ for (let period = MIN_MOVING_AVERAGE_PERIOD; period <= MAX_MOVING_AVERAGE_PERIOD; period += 1) {
+ if (!used.has(period)) return period;
+ }
+
+ return MAX_MOVING_AVERAGE_PERIOD;
+}
+
+export function syncMovingAverage(
+ chart: Chart,
+ periods: readonly number[],
+ paneId: string,
+ colors: readonly string[],
+): void {
+ const calcParams = normalizeMovingAveragePeriods(periods);
+ const lines = calcParams.map((_, index) => ({
+ style: 'solid' as const,
+ smooth: false,
+ size: 1,
+ color: colors[index % colors.length] ?? '#8b949e',
+ }));
+ const indicator = {
+ name: 'MA',
+ calcParams,
+ paneId,
+ styles: { lines },
+ };
+
+ if (chart.getIndicators({ paneId, name: 'MA' }).length > 0) {
+ chart.overrideIndicator(indicator);
+ } else {
+ chart.createIndicator(indicator, true);
+ }
+}
diff --git a/src/utils/paneSize.spec.ts b/src/utils/paneSize.spec.ts
new file mode 100644
index 0000000..b5ae341
--- /dev/null
+++ b/src/utils/paneSize.spec.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from 'vitest';
+import { subPaneHeight } from './paneSize';
+
+describe('subPaneHeight', () => {
+ it('按图区高度的 28% 取,夹在 48–80px', () => {
+ expect(subPaneHeight(200)).toBe(56);
+ expect(subPaneHeight(1000)).toBe(80);
+ expect(subPaneHeight(100)).toBe(48);
+ });
+
+ it('图区高度未知时给兜底值,不产生 NaN', () => {
+ expect(subPaneHeight(0)).toBe(72);
+ expect(subPaneHeight(NaN)).toBe(72);
+ });
+});
diff --git a/src/utils/paneSize.ts b/src/utils/paneSize.ts
new file mode 100644
index 0000000..0727365
--- /dev/null
+++ b/src/utils/paneSize.ts
@@ -0,0 +1,22 @@
+// src/utils/paneSize.ts
+
+/**
+ * 图表副图窗格(pane)的目标高度。
+ *
+ * klinecharts 的 pane 高度是**固定像素**,主图吃掉剩余空间。默认 100px 在小视口下会占到
+ * 图区三分之一以上,喧宾夺主;这里按图区高度的 28% 计算并夹在 48–80px:大窗口不会无限
+ * 长高,小窗口也保得住主图的面积。
+ *
+ * K 线的指标副图与分时图的成交量副图共用这一份口径 —— 两张图在详情面板里占同一块
+ * 区域,切换周期时副图高度不该跳。
+ */
+const SUB_PANE_RATIO = 0.28;
+const SUB_PANE_MIN = 48;
+const SUB_PANE_MAX = 80;
+/** 图区还没量到高度时的兜底值(约等于中等窗口下的一档) */
+const SUB_PANE_FALLBACK = 72;
+
+export function subPaneHeight(totalHeight: number): number {
+ if (!(totalHeight > 0)) return SUB_PANE_FALLBACK;
+ return Math.round(Math.min(SUB_PANE_MAX, Math.max(SUB_PANE_MIN, totalHeight * SUB_PANE_RATIO)));
+}