Pinescript v5中如何查找当前SMA上涨趋势前的上一次上涨趋势?
实现思路与代码示例
步骤1:定义SMA趋势状态
先明确SMA的涨跌判定逻辑,用连续两根K线的SMA差值区分状态:
- 上涨状态:
smaVal > smaVal[1] - 下跌状态:
smaVal < smaVal[1] - 平盘状态默认延续前一根K线的趋势,避免干扰切换判断
步骤2:标记趋势切换点
捕捉两种核心趋势切换信号:
- 从非上涨转上涨:
trendUpSwitch = isUp and not isUp[1] - 从非下跌转下跌:
trendDownSwitch = isDown and not isDown[1]
步骤3:回溯目标上涨趋势
- 用
barssince()获取当前上涨趋势的起始K线位置 - 先找到当前上涨趋势起始点之前的最后一次下跌切换点(即衔接的下跌趋势起点)
- 再在该下跌切换点之前,定位最后一次上涨趋势的首尾位置
完整Pine Script代码示例
//@version=5 indicator("Previous SMA Up Trend Tracker", overlay=true) // 自定义SMA参数 smaLength = input.int(20, title="SMA周期") smaVal = ta.sma(close, smaLength) // 定义趋势状态 isUp = smaVal > smaVal[1] isDown = smaVal < smaVal[1] // 标记趋势切换临界点 trendUpSwitch = isUp and not isUp[1] trendDownSwitch = isDown and not isDown[1] // 确认当前是否处于上涨趋势,并获取起始点 currentUpStartBar = barssince(trendUpSwitch) isInCurrentUpTrend = currentUpStartBar != 0 // 存储前次上涨趋势的首尾K线索引 var int prevUpStart = na var int prevUpEnd = na if isInCurrentUpTrend // 找到当前上涨前的最后一次下跌切换点 lastDownSwitchIdx = ta.valuewhen(trendDownSwitch, bar_index, 0) // 在该下跌切换点之前,定位最后一次上涨的起始点 prevUpStart = ta.valuewhen(trendUpSwitch, bar_index, ta.barssince(bar_index < lastDownSwitchIdx)) // 定位该上涨趋势结束的下跌切换点(即趋势终点) prevUpEnd = ta.valuewhen(trendDownSwitch, bar_index, ta.barssince(bar_index > prevUpStart)) // 可视化标记前次上涨趋势区间 var color prevUpColor = color.new(color.green, 70) if not na(prevUpStart) and not na(prevUpEnd) bgcolor(prevUpColor, offset=-prevUpStart, length=prevUpEnd - prevUpStart + 1) // 最后一根K线输出区间信息 if barstate.islast and isInCurrentUpTrend label.new(bar_index, high, str.format("前次上涨区间:Bar {0} 至 {1}", prevUpStart, prevUpEnd), color=color.green, textcolor=color.white)
代码说明
- 用
trendUpSwitch和trendDownSwitch精准捕捉趋势起始点,排除平盘状态的干扰 - 通过
ta.valuewhen()配合ta.barssince()实现两层回溯,定位到目标趋势区间 - 背景色标记和文本标签可直观展示结果,便于验证逻辑正确性
内容的提问来源于stack exchange,提问作者Renaud
相关产品推荐
相关产品推荐

