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

Pine Script v5:30根K线内RSI超卖交叉≥3次时绘制买入信号

实现Pine Script v5 RSI超卖密集交叉买入信号

需求说明

当ta.crossunder(RSIMain, BuyAlertLevel)信号在最近30根K线内至少出现3次时,绘制额外的买入信号。

错误原因分析

你之前使用ta.valuewhen(Buysignal, close, 3) <= 30的逻辑错误:ta.valuewhen第二个参数传close会返回第3次信号发生时的收盘价,和30比较没有意义。正确做法是获取第3次信号对应的K线索引,计算当前K线与该K线的间隔是否≤30。

解决方案

方法1:跟踪第3次信号的时间间隔

使用ta.valuewhen获取第3次超卖交叉信号的K线索引,计算当前K线与它的差值,同时确保该信号存在(避免无信号时的错误):

// 计算最近第3次Buysignal的K线索引,无足够信号时返回na
third_buy_signal_bar = ta.valuewhen(Buysignal, bar_index, 2) // 索引从0开始,2对应第3次
// 判断当前K线与第3次信号的间隔是否≤30,且信号存在
aggressive_buy = not na(third_buy_signal_bar) and (bar_index - third_buy_signal_bar) <= 30

方法2:统计最近30根K线内的信号次数

使用ta.summation直接统计指定周期内的信号数量,当数量≥3时触发:

// 统计最近30根K线内的Buysignal次数
buy_count_in_range = ta.summation(Buysignal, 30)
aggressive_buy = buy_count_in_range >= 3

完整代码

将上述逻辑整合到你的现有代码中,这里采用方法1(更精准追踪第3次信号后的触发时机):

//@version=5
indicator("RSI 超卖密集买入信号", overlay=true)

RSIPeriod = input(13, "RSI Period")
BuyAlertLevel = input(-34, "RSI Buy Alert")
SellAlertLevel = input(34, "RSI Sell Alert")
RSIHistoModify = input(1.618, "RSI Fib Factor")
// 新增:调整密集信号的参数
signal_window = input(30, "信号统计窗口(K线数)")
required_signals = input(3, "窗口内需要的最少信号次数")

xPrice2 = close[1]
RSIMain = (ta.rsi(xPrice2, RSIPeriod) - 50) * RSIHistoModify

Buysignal = ta.crossunder(RSIMain, BuyAlertLevel)
Sellsignal = ta.crossover(RSIMain, SellAlertLevel)

// 计算密集买入信号
third_buy_signal_bar = ta.valuewhen(Buysignal, bar_index, required_signals - 1)
aggressive_buy = not na(third_buy_signal_bar) and (bar_index - third_buy_signal_bar) <= signal_window

show_rsi_signals = input(true, "显示基础RSI信号")
show_aggressive_buy = input(true, "显示密集买入信号")

// 绘制基础信号
plotchar(show_rsi_signals ? Buysignal: na, title="RSI 买入", char="•", location=location.belowbar, size=size.normal, color=color.rgb(255, 255, 255, 85))    
plotchar(show_rsi_signals ? Sellsignal: na, title="RSI 卖出", char="•", location=location.abovebar, size=size.normal, color=color.rgb(255, 255, 255, 85))

// 绘制密集买入信号(用不同字符区分)
plotchar(show_aggressive_buy ? aggressive_buy: na, title="密集买入", char="▲", location=location.belowbar, size=size.large, color=color.new(color.green, 0))

代码说明

  • 新增了可配置的signal_window(统计窗口)和required_signals(需要的信号次数),方便调整参数
  • 方法1中ta.valuewhen(Buysignal, bar_index, required_signals - 1):因为索引从0开始,第3次信号对应索引2
  • 密集买入信号用绿色三角形区分,和基础信号的圆点形成差异

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:20:33