如何在任意时间框架显示满足均线条件的4小时K线计数?
需求与问题
- 需统计满足以下条件的4小时K线数量:收盘价大于20周期移动平均线(
close > ma),且移动平均线处于上升状态(ma > ma[1]) - 当任一条件不满足时,计数器重置为0
- 要求在任意时间框架(如5分钟、2小时)中,都能显示基于4小时周期计算出的该计数,而非当前图表时间框架的K线数
原代码存在的问题:当前代码的计数器逻辑运行在图表当前时间框架下,导致小周期中会重复对同一根4小时K线的条件进行判断,从而错误累加出当前时间框架的K线数量(如截图中显示的553BARS)。
原代码
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © jeckwilke //@version=5 indicator("My script") ma = request.security(syminfo.tickerid, "240", ta.sma(close, 20)) lma = request.security(syminfo.tickerid, "240", ta.sma(close[1], 20)) _close = request.security(syminfo.tickerid, "240", close) var counter = 0 if _close > ma and ma > lma counter += 1 else counter := 0 plot(counter)
修改后的代码
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © jeckwilke //@version=5 indicator("4H Condition Counter", overlay=false) // 在4小时周期内计算符合条件的K线计数 counter_4h = request.security(syminfo.tickerid, "240", var int cnt = 0 ma = ta.sma(close, 20) ma_prev = ta.sma(close[1], 20) if close > ma and ma > ma_prev cnt += 1 else cnt := 0 cnt ) // 绘制4小时周期的计数结果 plot(counter_4h, title="4H满足条件K线数", color=color.new(color.blue, 0), linewidth=2)
代码说明
- 将计数器的逻辑完全封装在
request.security的4小时周期上下文中,确保仅在每根4小时K线闭合时进行一次条件判断和计数器更新 - 通过这种方式,无论当前图表使用何种时间框架,都会返回最新的4小时周期计数结果,不会出现小周期下重复累加的问题
- 变量
counter_4h会同步4小时周期计算出的计数器值,直接绘制该变量即可得到需求中的结果
内容的提问来源于stack exchange,提问作者Eduardo Moreira
相关产品推荐
相关产品推荐

