基于TradingView内置Auto Fib Retracement,如何在Pine Script中获取斐波那契水平价格计算差值?
在Pine Script中获取Auto Fib Retracement的0级与1级价格并计算差值
TradingView内置的Auto Fib工具无法直接在Pine Script中读取数值,你需要自己实现自动识别高低点+计算斐波那契水平的逻辑,以下是两种实用方案:
方案1:基于固定周期的高低点计算
适合需要稳定区间的场景,用最近N根K线的高低点作为斐波那契区间:
//@version=5 indicator("Auto Fib 0-1 Level Difference", overlay=false) // 调整回溯周期,控制高低点的选取范围 lookbackPeriod = 20 highLevel = ta.highest(high, lookbackPeriod) lowLevel = ta.lowest(low, lookbackPeriod) // 定义斐波那契水平:0级取高点,1级取23.6%回撤位(可替换为0.382/0.5等比例) fib0 = highLevel fib1 = highLevel - (highLevel - lowLevel) * 0.236 // 计算0级与1级的价格差值 levelDiff = fib0 - fib1 // 绘制差值曲线 plot(levelDiff, title="0-1 Level Difference", color=color.blue, linewidth=2) // 可选:在主图标记斐波那契水平(需将indicator的overlay设为true) var line fib0Line = na var line fib1Line = na if barstate.islast fib0Line := line.new(bar_index - lookbackPeriod, fib0, bar_index, fib0, color=color.red, width=2) fib1Line := line.new(bar_index - lookbackPeriod, fib1, bar_index, fib1, color=color.green, width=2)
方案2:基于摆动高低点自动更新区间
模拟内置Auto Fib的动态切换逻辑,识别市场的摆动高低点作为区间:
//@version=5 indicator("Auto Fib Swing High-Low Difference", overlay=false) // 调整摆动点识别周期(左右各n根K线内的极值) pivotLength = 5 swingHigh = ta.pivothigh(pivotLength, pivotLength) swingLow = ta.pivotlow(pivotLength, pivotLength) // 记录最新的有效摆动高低点 var float currentHigh = na var float currentLow = na if not na(swingHigh) currentHigh := swingHigh if not na(swingLow) currentLow := swingLow // 仅当高低点都存在时计算差值 levelDiff = na if not na(currentHigh) and not na(currentLow) fib0 = currentHigh fib1 = currentHigh - (currentHigh - currentLow) * 0.236 levelDiff = fib0 - fib1 // 绘制差值曲线 plot(levelDiff, title="0-1 Level Difference", color=color.blue, linewidth=2) // 主图动态更新斐波那契水平线 var line fib0Line = na var line fib1Line = na if barstate.islast and not na(levelDiff) line.delete(fib0Line) line.delete(fib1Line) fib0Line := line.new(bar_index - 20, fib0, bar_index, fib0, color=color.red, width=2) fib1Line := line.new(bar_index - 20, fib1, bar_index, fib1, color=color.green, width=2)
关键调整点
- 斐波那契比例:将代码中的
0.236替换为你需要的1级水平比例(如0.382、0.5) - 周期参数:修改
lookbackPeriod或pivotLength可以调整高低点的识别范围 - 显示控制:将
overlay=false改为true可以让指标直接显示在主图上
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

