You need to enable JavaScript to run this app. TradingView PineScript 1秒图表调用15分钟数据security函数可变参数报错问询
优惠活动
大模型
产品
解决方案
定价
更多

TradingView PineScript 1秒图表调用15分钟数据security函数可变参数报错问询

PineScript跨周期调用解决方案(1秒图表用15分钟周期计算指标)

错误原因说明

你遇到的Cannot use a mutable variable as an argument of the security function报错,是因为security函数的入参要求是编译期即可确定的不可变值(比如input参数、const常量、字面量),如果把当前1秒周期运行时动态更新的可变变量(比如你代码里的lw/hg/last_l这类var变量)传入security,就会触发该错误。

可行实现方案

核心思路是:把你需要的low[x1] > low[last_l]计算逻辑完全封装到15分钟周期的执行上下文内,所有计算都在15分钟周期完成后,再将最终布尔结果拉回1秒周期使用,不需要在1秒周期处理大量K线,性能开销极低。

实现代码

//@version=4
study("15min Zigzag Core Logic", overlay=true)

// 原有参数保留(均为不可变input,可传入security)
Depth       = input(7, "Depth", input.integer, minval=1, step=1)
Deviation   = input(5, "Deviation", input.integer, minval=1, step=1)
Backstep    = input(2, "Backstep", input.integer, minval=2, step=1)
repaint     = input(true, "Repaint Levels")

// 核心逻辑封装:仅保留计算low[x1] > low[last_l]所需的代码,去掉画线/标签等冗余逻辑
get_15min_logic() =>
    var last_h = 1, last_h := last_h + 1
    var last_l = 1, last_l := last_l + 1
    var lw = 1, var hg = 1
    lw := lw + 1, hg := hg + 1
    p_lw = -lowestbars(Depth), p_hg = -highestbars(Depth)
    lowing = lw == p_lw or low - low[p_lw] > Deviation*syminfo.mintick
    highing = hg == p_hg or high[p_hg] - high > Deviation*syminfo.mintick
    lh = barssince(not highing[1]), ll = barssince(not lowing[1])
    down = barssince(not (lh > ll)) >= Backstep, lower = low[lw] > low[p_lw], higher = high[hg] < high[p_hg]
    if lw != p_lw and (not down[1] or lower)
        lw := p_lw < hg ? p_lw : 0
    if hg != p_hg and (down[1] or higher)
        hg := p_hg < lw ? p_hg : 0
    x1 = down ? lw : hg
    // 仅返回你需要的核心布尔结果
    low[x1] > low[last_l]

// 跨周期调用15分钟数据的计算结果
// 不需要重绘就用barmerge.lookahead_off,需要实时重绘就换成barmerge.lookahead_on
logic_result = security(syminfo.tickerid, "15", get_15min_logic(), barmerge.lookahead_off)

// 你可以在1秒图表上直接使用logic_result变量做后续判断/信号触发
plotshape(logic_result, style=shape.triangleup, location=location.belowbar, color=color.lime, size=size.small)

方案优势

  • 所有计算都仅在15分钟K线的节点执行,1秒周期仅复用计算结果,不需要处理数千根1秒K线,无性能问题
  • 完全保留原指标的参数和计算逻辑,结果和直接在15分钟周期跑原指标的结果完全一致
  • 可通过barmerge参数自由控制是否允许重绘,匹配你原有的repaint参数需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 05:24:04