如何修改Williams Fractals的upFractal条件,无需plotshape偏移显示对应位置?
要实现不用offset(-6)就能让形状显示在正确的分型bar位置(和用offset效果一致,接受延迟),你可以通过记录分型对应的bar索引,在对应bar位置触发绘图的方式来实现,具体修改如下:
修改思路
原代码的upFractal是在当前bar确认往前n根的bar是向上分型,直接plot会把形状画在当前bar,加offset才会移到目标分型bar。现在我们把确认的分型bar索引存起来,当走到该bar的位置时(延迟n根bar后,该bar已成为历史bar),触发绘图,无需依赖offset参数。
修改后的完整代码
//@version=5 indicator("Williams Fractals", shorttitle="Fractals", format=format.price, precision=0, overlay=true) n = input.int(title="Periods", defval=6, minval=2) // 存储分型bar索引的持久化数组 var array<int> upFractalBars = array.new_int() // UpFractal 判断逻辑(保留原逻辑,确认往前n根的bar是否为向上分型) bool upflagDownFrontier = true bool upflagUpFrontier0 = true bool upflagUpFrontier1 = true bool upflagUpFrontier2 = true bool upflagUpFrontier3 = true bool upflagUpFrontier4 = true for i = 1 to n upflagDownFrontier := upflagDownFrontier and (high[n-i] < high[n]) upflagUpFrontier0 := upflagUpFrontier0 and (high[n+i] < high[n]) upflagUpFrontier1 := upflagUpFrontier1 and (high[n+1] <= high[n] and high[n+i + 1] < high[n]) upflagUpFrontier2 := upflagUpFrontier2 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+i + 2] < high[n]) upflagUpFrontier3 := upflagUpFrontier3 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+i + 3] < high[n]) upflagUpFrontier4 := upflagUpFrontier4 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+4] <= high[n] and high[n+i + 4] < high[n]) flagUpFrontier = upflagUpFrontier0 or upflagUpFrontier1 or upflagUpFrontier2 or upflagUpFrontier3 or upflagUpFrontier4 upFractalConfirmed = upflagDownFrontier and flagUpFrontier // 确认分型时,将目标bar的索引存入数组(去重避免重复添加) if upFractalConfirmed targetBarIndex = bar_index - n if not array.includes(upFractalBars, targetBarIndex) array.push(upFractalBars, targetBarIndex) // 判断当前bar是否是已确认的分型bar isUpFractalBar = array.includes(upFractalBars, bar_index) // 绘制分型形状,无需设置offset plotshape(isUpFractalBar, title="Up Fractal", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)
关键修改点说明
- 新增分型索引数组:用
var array<int>创建持久化数组,存储已确认的向上分型bar的索引,确保数组不会在每根bar重置。 - 存储目标分型bar索引:当确认某根历史bar是分型时,计算其索引
bar_index - n并加入数组,同时做去重处理避免重复绘图。 - 触发绘图逻辑:通过
array.includes检查当前bar是否在分型索引数组中,以此触发plotshape,形状会直接显示在分型对应的bar位置。
这种方式的显示时机和原代码用offset(-6)完全一致,都会延迟n根bar才显示分型,但无需依赖offset参数。
内容的提问来源于stack exchange,提问作者Shuman Rotula
相关产品推荐
相关产品推荐

