自定义RSI指标回溯着色需求:满足条件修改历史线段颜色
自定义RSI回溯着色解决方案
问题描述
需编写自定义RSI指标,当RSI下跌幅度达到20点及以上时,回溯将下跌区间(从下跌起点到幅度达标终点)的RSI线段改为红色。目前已实现标记区间的起点和终点,但无法修改区间内的线段颜色。
可行实现方案
Pine Script无法直接回溯修改已绘制的plot线段颜色,因此可通过事后绘制红色线段覆盖目标区间的方式实现需求。以下是修改后的完整代码:
//@version=5 indicator(title="Custom RSI Retrospective Coloring", overlay=false, format=format.price, precision=2) // RSI计算 len = input.int(14, minval=1, title="Length") src = input.source(close, "Source") up = ta.rma(math.max(ta.change(src), 0), len) down = ta.rma(-math.min(ta.change(src), 0), len) rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down)) // RSI水平带 band1 = hline(70, "Upper Band", color=color.new(#434651, 0)) band0 = hline(30, "Lower Band", color=color.new(#434651, 0)) band3 = hline(50, "Middle Band", color=color.new(#434651, 50)) fill(band1, band0, color=color.new(#727171, 90), title="Background") // 存储下跌趋势信息的变量 var bool downRSITrend = false // 是否处于下跌趋势 var float downTrendStartRSI = na // 下跌起点的RSI值 var int downTrendStartBar = na // 下跌起点的bar索引 var line[] redLines = array.new_line() // 存储红色线段的数组 var label labelHi = na var label labelLow = na // 识别下跌趋势起点(RSI出现顶部拐点) if rsi[1] > rsi[2] and rsi[0] < rsi[1] downRSITrend := true downTrendStartRSI := rsi[1] downTrendStartBar := bar_index[1] // 识别下跌趋势终点(RSI出现底部拐点)并判断幅度是否达标 if downRSITrend and rsi[1] < rsi[2] and rsi[0] > rsi[1] downRSITrend := false // 检查下跌幅度是否≥20点 if downTrendStartRSI - rsi[1] >= 20 downTrendEndBar := bar_index[1] // 标记起点和终点 labelHi := label.new(downTrendStartBar, y=downTrendStartRSI, style=label.style_circle, color=color.new(#eb2f1673, 55), size=size.tiny) labelLow := label.new(downTrendEndBar, y=rsi[1], style=label.style_circle, color=#eb2f1673, size=size.tiny) // 绘制红色线段覆盖下跌区间的RSI线 newLine = line.new( x1=downTrendStartBar, y1=downTrendStartRSI, x2=downTrendEndBar, y2=rsi[1], color=#eb2f16, width=2, extend=extend.none ) array.push(redLines, newLine) // 绘制默认RSI线 plot(rsi, "RSI", color=#425c70, linewidth=2)
方案说明
- 核心逻辑:当检测到符合条件的下跌区间时,使用
line.new()绘制红色线段,覆盖在默认蓝色RSI线上,实现回溯着色效果。 - 线段管理:用
line[]数组存储所有红色线段,避免内存泄漏,也方便后续对线段进行批量操作(如删除旧线段)。 - 拐点识别:通过对比RSI前后bar的数值变化,精准识别下跌趋势的顶部起点和底部终点,确保区间判断的准确性。
内容的提问来源于stack exchange,提问作者fbalazs
相关产品推荐
相关产品推荐

