使用'Macd Line == Signal Line'条件无法显示提示文本,求解决方法
解决Pine Script中MACD线与信号线相等时显示提示文本的问题
你的代码无法生效的核心原因是浮点数精度问题:MACD线与信号线都是经过计算得到的浮点数值,在行情数据中几乎不会完全相等,直接用==进行判断的条件几乎永远不会触发。
解决这个问题有两种常用思路:
思路1:利用交叉信号判断(推荐)
当MACD线与信号线交叉时,就是两者相等的瞬间,用ta.crossover或ta.crossunder来捕捉这个时刻,这是更可靠的方式:
//@version=5 indicator(title='macd esit', overlay=true) [macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9) // 捕捉MACD线与信号线交叉的瞬间(包括金叉和死叉) alarm = ta.crossover(macdLine, signalLine) or ta.crossunder(macdLine, signalLine) // 使用shape.label更适合显示文本,也可以保留triangledown并叠加文本 plotshape(alarm, style=shape.labeldown, text='ALARM', color=color.white, textcolor=color.black, location=location.belowbar, size=size.small)
思路2:设置精度阈值判断
如果一定要判断两者数值接近相等,可以设置一个极小的阈值(比如0.001),当两者差值的绝对值小于这个阈值时触发:
//@version=5 indicator(title='macd esit', overlay=true) [macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9) // 设置精度阈值,判断差值绝对值小于0.001 threshold = 0.001 alarm = math.abs(macdLine - signalLine) < threshold plotshape(alarm, style=shape.triangledown, text='ALARM', color=color.new(color.white, 0), location=location.belowbar, size=size.small)
补充说明:
- 如果你希望只在特定交叉方向触发(比如仅金叉),可以去掉
or ta.crossunder(...)部分 - 使用
shape.labeldown或shape.labelup样式会比triangledown更清晰地显示文本内容
内容的提问来源于stack exchange,提问作者sperci0
相关产品推荐
相关产品推荐

