94 lines
2.1 KiB
TypeScript
94 lines
2.1 KiB
TypeScript
/**
|
|
* 自定义均价线指标
|
|
*
|
|
* 用于分时图显示橙黄色均价线
|
|
* 计算公式:累计成交额 / 累计成交量
|
|
*/
|
|
|
|
import type { Indicator, KLineData } from 'klinecharts';
|
|
|
|
export const avgPriceIndicator: Indicator = {
|
|
name: 'AVG',
|
|
shortName: 'AVG',
|
|
calcParams: [],
|
|
shouldOhlc: false, // 不显示 OHLC 信息
|
|
shouldFormatBigNumber: false,
|
|
precision: 2,
|
|
minValue: null,
|
|
maxValue: null,
|
|
|
|
figures: [
|
|
{
|
|
key: 'avg',
|
|
title: '均价: ',
|
|
type: 'line',
|
|
},
|
|
],
|
|
|
|
/**
|
|
* 计算均价
|
|
* @param dataList K线数据列表
|
|
* @returns 均价数据
|
|
*/
|
|
calc: (dataList: KLineData[]) => {
|
|
let totalAmount = 0; // 累计成交额
|
|
let totalVolume = 0; // 累计成交量
|
|
|
|
return dataList.map((kLineData) => {
|
|
const { close = 0, volume = 0 } = kLineData;
|
|
|
|
totalAmount += close * volume;
|
|
totalVolume += volume;
|
|
|
|
const avgPrice = totalVolume > 0 ? totalAmount / totalVolume : close;
|
|
|
|
return { avg: avgPrice };
|
|
});
|
|
},
|
|
|
|
/**
|
|
* 绘制样式配置
|
|
*/
|
|
styles: {
|
|
lines: [
|
|
{
|
|
color: '#FF9800', // 橙黄色
|
|
size: 2,
|
|
style: 'solid',
|
|
smooth: true,
|
|
},
|
|
],
|
|
},
|
|
|
|
/**
|
|
* Tooltip 格式化(显示均价 + 涨跌幅)
|
|
*/
|
|
createTooltipDataSource: ({ kLineData, indicator, defaultStyles }: any) => {
|
|
if (!indicator?.avg) {
|
|
return {
|
|
title: { text: '均价', color: defaultStyles.tooltip.text.color },
|
|
value: { text: '--', color: '#FF9800' },
|
|
};
|
|
}
|
|
|
|
const avgPrice = indicator.avg;
|
|
const prevClose = kLineData?.prev_close;
|
|
|
|
// 计算均价涨跌幅
|
|
let changeText = `¥${avgPrice.toFixed(2)}`;
|
|
if (prevClose && prevClose > 0) {
|
|
const changePercent = ((avgPrice - prevClose) / prevClose * 100).toFixed(2);
|
|
const changeValue = (avgPrice - prevClose).toFixed(2);
|
|
changeText = `¥${avgPrice.toFixed(2)} (${changeValue}, ${changePercent}%)`;
|
|
}
|
|
|
|
return {
|
|
title: { text: '均价', color: defaultStyles.tooltip.text.color },
|
|
value: {
|
|
text: changeText,
|
|
color: '#FF9800',
|
|
},
|
|
};
|
|
},
|
|
};
|