Pine Script实现K线高低点数字根计算与标注需求
Pine Script实现价格数字根计算及K线标注功能
以下是完整的实现代码,满足你提出的两个需求:
//@version=5 indicator("价格数字根标注", overlay=true) // 计算数字根的函数,支持带小数的价格 getDigitalRoot(float price) => // 将价格转为整数(保留两位小数后取整,避免小数位丢失) int num = math.round(math.abs(price) * 100) int root = num // 循环计算数字根,直到得到个位数 while root >= 10 int sum = 0 while root > 0 sum += root % 10 root := root / 10 root := sum root // 筛选最近50根K线 isRecentKline = bar_index >= ta.barssince(ta.bar_index) - 49 // 计算当前K线High和Low的数字根 highDigitalRoot = getDigitalRoot(high) lowDigitalRoot = getDigitalRoot(low) // 顶部标注High价格及数字根,自动维护最近50个标签 var label[] highLabelList = array.new_label() if isRecentKline // 移除超过50的旧标签 if array.size(highLabelList) > 50 label.delete(array.shift(highLabelList)) // 创建新标签,显示价格和数字根 highLabel = label.new( bar_index, high, str.tostring(high) + "\n根: " + str.tostring(highDigitalRoot), color=color.new(color.green, 0), textcolor=color.white, style=label.style_label_down, size=size.small ) array.push(highLabelList, highLabel) // 底部标注Low价格及数字根,自动维护最近50个标签 var label[] lowLabelList = array.new_label() if isRecentKline if array.size(lowLabelList) > 50 label.delete(array.shift(lowLabelList)) lowLabel = label.new( bar_index, low, str.tostring(low) + "\n根: " + str.tostring(lowDigitalRoot), color=color.new(color.red, 0), textcolor=color.white, style=label.style_label_up, size=size.small ) array.push(lowLabelList, lowLabel)
关键功能说明
- 数字根计算:函数
getDigitalRoot先将价格转为整数(处理小数位),再通过嵌套循环逐位累加,直到得到个位数,完全匹配你给出的示例逻辑 - 最近50根K线筛选:通过
bar_index判断只在最新的50根K线上添加标注 - 标签管理:使用动态数组存储标签对象,当标签数量超过50时自动移除最早的标签,避免界面拥挤
- 标注样式:顶部用绿色向下标签显示High价格和数字根,底部用红色向上标签显示Low价格和数字根,清晰区分
内容的提问来源于stack exchange,提问作者Sitaram Dhuri
相关产品推荐
相关产品推荐

