本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SchizoQuant
//@version=6
indicator("Volatility Adaptive Filtered Trend", overlay=true)
// USER INPUTS
string adaptiveTrendTip = "Volatility Length controls how far back the indicator measures ATR and directional price movement, while Normalization Length sets the reference window used to judge whether current conditions are unusually active or quiet. Lower either value for faster adaptation, or increase them for a steadier response."
string smoothingLimitTip = "Minimum Smoothing sets the slowest response the adaptive trend can use, while Maximum Smoothing sets the fastest. Lower Minimum Smoothing for more filtering during quiet conditions, and increase Maximum Smoothing for quicker reactions during stronger movement."
string ehlersTip = "Filter Length controls how many recent EMA-smoothed adaptive trend observations contribute to the displacement-weighted filter, while Momentum Length controls how far apart those observations are compared when calculating their weights. Increase Filter Length for a smoother trendline, and increase Momentum Length to emphasize movement across a broader span of bars."
string bandMultiplierTip = "Upper Multiplier controls how far the bullish threshold sits above the filtered trendline, while Lower Multiplier controls how far the bearish threshold sits below it. Increase either multiplier to widen that side of the bands and require a larger price move before a regime change."
string colorTip = "Bullish Color is used for bullish regimes, LONG signals, the upper band, and bullish candle coloring, while Bearish Color is used for bearish regimes, SHORT signals, the lower band, and bearish candle coloring."
float src = input.source(title="Source", defval=hlc3, group="Adaptive Trend Settings", tooltip="Choose the price source used throughout the adaptive trend calculation. HLC3 provides a balanced view of each candle by averaging the high, low, and close.")
int volLength = input.int(title="Volatility Length", defval=15, minval=2, group="Adaptive Trend Settings", inline="AT1", tooltip=adaptiveTrendTip)
int normalLength = input.int(title="Normalization Length", defval=30, minval=5, group="Adaptive Trend Settings", inline="AT1", tooltip=adaptiveTrendTip)
float minSC = input.float(title="Minimum Smoothing", defval=0.084, minval=0.001, maxval=1.0, step=0.001, group="Smoothing Limits", inline="SL1", tooltip=smoothingLimitTip)
float maxSC = input.float(title="Maximum Smoothing", defval=0.330, minval=0.001, maxval=1.0, step=0.001, group="Smoothing Limits", inline="SL1", tooltip=smoothingLimitTip)
int emaLength = input.int(title="EMA Smoothing", defval=5, minval=1, group="Smoothing", tooltip="Adds an extra smoothing step to the adaptive trend before the final filter is applied. Increase it to reduce short-term noise or decrease it to preserve more responsiveness.")
int ehlersLength = input.int(title="Filter Length", defval=9, minval=2, group="Ehlers Filter", inline="EF1", tooltip=ehlersTip)
int ehlersMomentum = input.int(title="Momentum Length", defval=2, minval=1, group="Ehlers Filter", inline="EF1", tooltip=ehlersTip)
int bandVolLength = input.int(title="Volatility Length", defval=22, minval=2, group="Volatility Bands", tooltip="Sets how much return history is used to estimate band volatility. Lower values make the bands adjust faster to changing volatility, while higher values create a steadier band width.")
float upperMult = input.float(title="Upper Multiplier", defval=2.0, minval=0.1, step=0.1, group="Volatility Bands", inline="VB1", tooltip=bandMultiplierTip)
float lowerMult = input.float(title="Lower Multiplier", defval=2.0, minval=0.1, step=0.1, group="Volatility Bands", inline="VB1", tooltip=bandMultiplierTip)
bool showBands = input.bool(title="Show Bands", defval=true, group="Visualization", tooltip="Show or hide the upper and lower volatility bands around the filtered trendline. Turning this off only changes the chart display and does not affect the trend calculations or signals.")
bool showFill = input.bool(title="Show Fill", defval=true, group="Visualization", tooltip="Show or hide the shaded area between the upper and lower volatility bands. This is visual only and does not change the indicator calculations.")
bool showSignals = input.bool(title="Show Signals", defval=true, group="Visualization", tooltip="Show or hide LONG and SHORT markers when the active trend regime changes. Turning this off does not change the underlying regime calculation.")
bool colorBars = input.bool(title="Color Bars", defval=true, group="Visualization", tooltip="Color price candles according to the currently active trend regime. Turning this off only removes candle coloring and does not affect the signals.")
color longColor = input.color(title="Bullish Color", defval=color.rgb(57, 255, 20), group="Color Settings", inline="COL1", tooltip=colorTip)
color shortColor = input.color(title="Bearish Color", defval=color.rgb(138, 43, 226), group="Color Settings", inline="COL1", tooltip=colorTip)
// CALCULATIONS
float atr = ta.atr(volLength)
float netChange = math.abs(src - src[volLength])
float atrBaseline = ta.sma(atr, normalLength)
float changeBaseline = ta.sma(netChange, normalLength)
float atrFactor = atrBaseline != 0.0 ? atr / atrBaseline : 1.0
float changeFactor = changeBaseline != 0.0 ? netChange / changeBaseline : 1.0
float combinedFactor = (atrFactor + changeFactor) * 0.5
float normalizedFactor = math.max(0.0, math.min(1.0, combinedFactor / 2.0))
float adaptiveSC = minSC + (maxSC - minSC) * normalizedFactor
var float adaptiveTrend = na
adaptiveTrend := na(adaptiveTrend[1]) ? src : adaptiveTrend[1] + adaptiveSC * (src - adaptiveTrend[1])
float emaTrend = ta.ema(adaptiveTrend, emaLength)
float ehlersNumerator = 0.0
float ehlersCoefficientSum = 0.0
for i = 0 to ehlersLength - 1
float currentSample = emaTrend[i]
float referenceSample = emaTrend[i + ehlersMomentum]
if not na(currentSample) and not na(referenceSample)
float coefficient = math.abs(currentSample - referenceSample)
ehlersNumerator += coefficient * currentSample
ehlersCoefficientSum += coefficient
float ehlersFallback = ta.sma(emaTrend, ehlersLength)
float trendMA = ehlersCoefficientSum > 0.0 ? ehlersNumerator / ehlersCoefficientSum : ehlersFallback
float priceReturn = src[1] != 0.0 ? (src - src[1]) / src[1] : 0.0
float volatility = ta.stdev(priceReturn, bandVolLength)[1]
float upperBand = trendMA + upperMult * volatility * trendMA
float lowerBand = trendMA - lowerMult * volatility * trendMA
// SIGNALS
bool long = close > upperBand
bool short = close < lowerBand
var int SQ = 0
if long
SQ := 1
else if short
SQ := -1
bool longSignal = SQ == 1 and SQ[1] != 1
bool shortSignal = SQ == -1 and SQ[1] != -1
// COLORS
color col = SQ == 1 ? longColor : shortColor
// PLOTS
plot(trendMA, title="Filtered Adaptive Trend", color=col, linewidth=2)
upperPlot = plot(showBands ? upperBand : na, title="Upper Volatility Band", color=color.new(longColor, 35), linewidth=1)
lowerPlot = plot(showBands ? lowerBand : na, title="Lower Volatility Band", color=color.new(shortColor, 35), linewidth=1)
fill(upperPlot, lowerPlot, title="Volatility Band Fill", color=showFill ? color.new(col, 90) : na)
plotshape(showSignals and longSignal, title="Long Signal", style=shape.triangleup, location=location.belowbar, size=size.small, color=longColor, text="LONG", textcolor=color.white)
plotshape(showSignals and shortSignal, title="Short Signal", style=shape.triangledown, location=location.abovebar, size=size.small, color=shortColor, text="SHORT", textcolor=color.white)
barcolor(colorBars ? col : na)
// ALERTS
alertcondition(longSignal, title="Long Signal", message="Volatility Adaptive Filtered Trend Long Signal on {{ticker}}")
alertcondition(shortSignal, title="Short Signal", message="Volatility Adaptive Filtered Trend Short Signal on {{ticker}}")