基于开盘价数字求和标记特定K线的Pine Script开发需求
Pine Script 标签与射线绘制问题修复
需求说明
- 计算逻辑:取当日开盘价(示例:48786),将各位数字求和后简化为单个数字:
4+8+7+8+6=33→3+3=6 - 图表标记:在5分钟周期日内图中,标记第6根K线,可在K线上方添加标注,或为该K线的高点、低点绘制水平射线
- 交易逻辑:突破该K线高点做多,跌破该K线低点做空
现有问题
已实现数字简化为单个数字的功能,但无法正常绘制标签与水平射线,现有代码如下:
// 数字取整函数 round_off(num) => math.round(num) // 数字各位求和函数 sum_digits(num) => sum = 0 temp_num = num while temp_num > 0 sum := sum + (temp_num % 10) temp_num := math.floor(temp_num / 10) sum // 简化为单个数字函数 reduce_to_single_digit(num) => temp = num while temp >= 10 temp := sum_digits(temp) temp // 获取当日开盘价 day_open = request.security(syminfo.tickerid, "D", open) // 对开盘价取整 rounded_open = math.floor(day_open) // 将取整后的开盘价简化为单个数字 single_digit_sum = reduce_to_single_digit(rounded_open) // 尝试在图表上绘制标签 onedigit= label.new( x =start915, y = Upper_ProfitBooking_Level, text = str.tostring(rounded_open)+"=" + str.tostring(single_digit_sum)+"", style = label.style_label_down, color = color.blue, textcolor = color.white,xloc=xloc.bar_time) label.delete(onedigit[1])
问题分析与修复方案
问题根源
现有代码中使用了未定义的变量start915和Upper_ProfitBooking_Level,导致标签无法定位;同时缺少绘制水平射线的逻辑。
修复后的完整代码
//@version=5 indicator("开盘价数字简化K线标记", overlay=true) // 数字取整函数 round_off(num) => math.round(num) // 数字各位求和函数 sum_digits(num) => sum = 0 temp_num = num while temp_num > 0 sum := sum + (temp_num % 10) temp_num := math.floor(temp_num / 10) sum // 简化为单个数字函数 reduce_to_single_digit(num) => temp = num while temp >= 10 temp := sum_digits(temp) temp // 获取当日开盘价 day_open = request.security(syminfo.tickerid, "D", open) // 对开盘价取整 rounded_open = math.floor(day_open) // 将取整后的开盘价简化为单个数字 single_digit_sum = reduce_to_single_digit(rounded_open) // 定位当日第N根K线(N为简化后的单个数字) is_target_bar = bar_index == ta.barssince(ta.change(time("D"))) + single_digit_sum // 存储目标K线的高低点 var float target_high = na var float target_low = na if is_target_bar target_high := high target_low := low // 绘制目标K线的水平射线 hline(target_high, "目标K线高点", color=color.green, linestyle=hline.style_dashed) hline(target_low, "目标K线低点", color=color.red, linestyle=hline.style_dashed) // 在目标K线上方绘制标签 if is_target_bar label.new(bar_index, high * 1.001, str.tostring(rounded_open) + "→" + str.tostring(single_digit_sum), style=label.style_label_down, color=color.blue, textcolor=color.white) // 交易信号绘制 long_signal = ta.crossover(close, target_high) short_signal = ta.crossunder(close, target_low) plotshape(long_signal, title="做多信号", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small) plotshape(short_signal, title="做空信号", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small)
修复说明
- 补充
//@version=5声明,确保脚本兼容Pine Script v5版本 - 移除未定义变量,通过
ta.barssince(ta.change(time("D")))定位当日第一根K线,叠加single_digit_sum精准找到目标K线 - 使用
var关键字存储目标K线高低点,避免数值随K线刷新被覆盖 - 通过
hline函数绘制高低点的水平射线,清晰标记关键价位 - 在目标K线触发时绘制标签,位置设为K线上方避免遮挡K线本身
- 新增交易信号可视化标记,直观展示多空入场点
内容的提问来源于stack exchange,提问作者K Karan
相关产品推荐
相关产品推荐

