You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pine Script中如何检测两条指标线同步穿越零轴?

Pine Script 同步检测两条量能线穿越零轴的实现

指标截图

我用Pine Script编写了一个量能流指标,包含两条不同周期的线:白色线vfinal(周期约40)、绿色线vfinal2(周期约130)。需要标记出两条线同步穿越零轴的位置——红竖线对应做空信号,绿竖线对应做多信号,黄竖线是二者非同步穿越的位置。

我尝试了这段代码:

var int mode = 0

if (vfinal[1] > 0 and vfinal < 0)
    mode := 1

if (vfinal2[1] > 0 and vfinal2 < 0 and mode == 1)
    lab = label.new(x = bar_index, y = 0, yloc = yloc.abovebar, style = label.style_label_down, text = "Sell", textcolor = color.white, size = size.normal, color = color.blue)

但这段代码无法确保两条线是同步穿越零轴,需要实现准确检测同步穿越的逻辑。


解决方案:同步穿越逻辑实现

核心思路是判断两条线在同一根K线内完成方向一致的零轴穿越:

1. 定义同步穿越条件

  • 同步做空:vfinal和vfinal2同时从正数下穿到负数
  • 同步做多:vfinal和vfinal2同时从负数上穿到正数

2. 完整实现代码

// 定义同步穿越条件
isSellSync = (vfinal[1] > 0 and vfinal < 0) and (vfinal2[1] > 0 and vfinal2 < 0)
isBuySync = (vfinal[1] < 0 and vfinal > 0) and (vfinal2[1] < 0 and vfinal2 > 0)

// 标记同步做空信号(标签/竖线二选一)
if (isSellSync)
    label.new(bar_index, high, text="Sell", color=color.red, textcolor=color.white, style=label.style_label_down, size=size.normal)
    // line.new(bar_index, low, bar_index, high, color=color.red, width=2)

// 标记同步做多信号(标签/竖线二选一)
if (isBuySync)
    label.new(bar_index, low, text="Buy", color=color.green, textcolor=color.white, style=label.style_label_up, size=size.normal)
    // line.new(bar_index, low, bar_index, high, color=color.green, width=2)

// 标记非同步穿越(可选)
isSingleCross = ((vfinal[1] > 0 and vfinal < 0) != (vfinal2[1] > 0 and vfinal2 < 0)) or 
               ((vfinal[1] < 0 and vfinal > 0) != (vfinal2[1] < 0 and vfinal2 > 0))
if (isSingleCross)
    line.new(bar_index, low, bar_index, high, color=color.yellow, width=1)

代码说明

  • isSellSync/isBuySync:通过逻辑与and确保两条线在同一K线内完成同方向穿越
  • 非同步穿越用!=判断两条线的穿越状态不一致,用黄线标记
  • 可根据需求选择用label(文字标签)或line(竖线)标记信号

内容的提问来源于stack exchange,提问作者Peter Pen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 18:30:22