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

统计近50根K线内指标信号次数的代码问题求助

近50根K线指标信号计数问题

需求说明

统计近50根K线中指标的信号触发次数,规则如下:

  • 指标发出Buy信号时,long_count累加1
  • 指标发出Sell信号时,short_count累加1
  • 最终净值为long_count与short_count的差值
  • 示例:若近50根K线中longCondition满足5次,long_count应为5;shortCondition满足3次,short_count应为3

遇到的问题

尝试用if条件累加计数,但当前代码仅统计当前K线的信号,无法保留历史累计值。如果最后一根K线无信号,计数会返回初始值,无法实现近50根K线的信号累计统计。

当前代码片段

long_count = 0.5
short_count = 0.5
i1 = longCondition ? 1: shortCondition  ? -1: 0
   

if i1 == 1
    long_count += 1
else if i1 == -1
    short_count += 1

解决方案

核心问题分析

当前代码的问题在于long_count和short_count是逐K线重新初始化的,每根K线都会重置为0.5,导致无法保留历史累计值。需要用var关键字声明变量,确保变量在脚本运行期间持续保留数值。

固定窗口计数实现(每50根K线重置)

//@version=5
indicator("近50K线信号计数(固定窗口)", overlay=false)

// 替换为实际的多空条件
longCondition = close > open and ta.rsi(close, 14) < 30
shortCondition = close < open and ta.rsi(close, 14) > 70

// 用var初始化计数变量,仅在首次运行时赋值
var float long_count = 0
var float short_count = 0

// 每50根K线重置计数
if bar_index % 50 == 0
    long_count := 0
    short_count := 0

// 信号判断与计数累加
i1 = longCondition ? 1 : shortCondition ? -1 : 0
if i1 == 1
    long_count += 1
else if i1 == -1
    short_count += 1

// 计算净值
net_value = long_count - short_count

// 可视化输出
plot(long_count, color=color.green, title="多单信号次数")
plot(short_count, color=color.red, title="空单信号次数")
plot(net_value, color=color.blue, title="净值")

滚动窗口计数实现(严格最近50根K线)

如果需要统计连续的最近50根K线(而非每50根重置一次),可以用数组存储信号出现的K线索引,实时移除超出50根K线范围的旧信号:

//@version=5
indicator("近50K线信号计数(滚动窗口)", overlay=false)

// 替换为实际的多空条件
longCondition = close > open and ta.rsi(close, 14) < 30
shortCondition = close < open and ta.rsi(close, 14) > 70

// 用数组存储信号对应的K线索引
var int long_signal_bars[] = array.new_int()
var int short_signal_bars[] = array.new_int()

// 记录多单信号
if longCondition
    array.push(long_signal_bars, bar_index)
// 移除50根K线以外的旧信号
while array.size(long_signal_bars) > 0 and bar_index - array.get(long_signal_bars, 0) >= 50
    array.remove(long_signal_bars, 0)

// 记录空单信号
if shortCondition
    array.push(short_signal_bars, bar_index)
while array.size(short_signal_bars) > 0 and bar_index - array.get(short_signal_bars, 0) >= 50
    array.remove(short_signal_bars, 0)

// 计算当前计数
long_count = array.size(long_signal_bars)
short_count = array.size(short_signal_bars)
net_value = long_count - short_count

// 可视化输出
plot(long_count, color=color.green, title="多单信号次数")
plot(short_count, color=color.red, title="空单信号次数")
plot(net_value, color=color.blue, title="净值")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 12:25:16