Kaufman Adaptive Band-Channel Trend [SchizoQuant]

SchizoQuant · study · 163 行 · 点赞 86 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// 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("Kaufman Adaptive Band-Channel Trend", overlay=true)
 
// USER INPUTS
string sourceTip      = "Price series used to calculate Kaufman's Adaptive Moving Average, market efficiency, and the adaptive volatility bands."
string efficiencyTip  = "Measures net directional price progress relative to total price movement. Higher values indicate more efficient trends."
string fastTip        = "Fastest KAMA smoothing period during efficient directional movement. Lower values allow faster adaptation to emerging trends."
string slowTip        = "Slowest KAMA smoothing period during inefficient movement. Higher values provide a steadier reference during sideways markets."
string bandTip        = "Lookback used to calculate the root-mean-square displacement between price and KAMA. Higher values produce a steadier volatility envelope."
string multiplierTip  = "Controls the width of the adaptive RMS bands. Higher values allow greater displacement from KAMA before the band boundary approaches price."
string atrTip         = "ATR period used to establish the minimum width of the adaptive volatility bands."
string floorTip       = "Minimum band distance expressed in ATR units. Prevents the bands from becoming excessively narrow during quiet markets."
string fastChannelTip = "Shorter Donchian lookback used to detect recent support and resistance. Lower values make the structural defense more responsive."
string slowChannelTip = "Longer Donchian lookback used to defend established trends. Higher values allow more substantial countertrend pullbacks."
string residenceTip   = "Measures how consistently price closes on the favorable side of KAMA. Sustained directional residence increases the influence of the wider Donchian structure."
string weightTip      = "Controls the maximum influence of Donchian structure relative to the adaptive KAMA volatility bands. Higher values place greater emphasis on historical price extremes."
string averageTip     = "Displays the Kaufman Adaptive Moving Average, colored according to the active trend regime."
string bandsTip       = "Displays the adaptive upper and lower RMS volatility bands around KAMA."
string bandLineTip    = "Controls transparency of both RMS band lines. 0 is fully opaque and 100 is invisible. This does not affect signals."
string bandFillTip    = "Controls transparency of the shaded region between the RMS bands. 0 is fully opaque and 100 is invisible."
string channelTip     = "Displays the completed longer-term Donchian channel used by the structural defense."
string defenseTip     = "Displays the active adaptive trend defense. The line advances in the favorable direction and resets when the trend reverses."
string signalsTip     = "Displays LONG and SHORT triangles when price confirms a reversal through the active adaptive defense."
string barsTip        = "Colors price candles according to the confirmed bullish or bearish trend regime."
string colorTip       = "Bullish Color represents bullish trends, while Bearish Color represents bearish trends."
 
float source               = input.source(title="Source", defval=close, group="Trend Settings", tooltip=sourceTip)
int   efficiencyLen        = input.int(title="Efficiency Length", defval=14, minval=2, group="Trend Settings", tooltip=efficiencyTip)
int   kamaFast             = input.int(title="KAMA Fast Length", defval=2, minval=1, group="Trend Settings", tooltip=fastTip)
int   kamaSlow             = input.int(title="KAMA Slow Length", defval=30, minval=2, group="Trend Settings", tooltip=slowTip)
int   bandLength           = input.int(title="RMS Band Length", defval=20, minval=2, group="Band Settings", tooltip=bandTip)
float bandMultiplier       = input.float(title="Band Multiplier", defval=1.8, minval=0.1, step=0.1, group="Band Settings", tooltip=multiplierTip)
int   atrLength            = input.int(title="ATR Length", defval=14, minval=1, group="Band Settings", tooltip=atrTip)
float atrFloor             = input.float(title="ATR Floor", defval=0.7, minval=0.1, step=0.05, group="Band Settings", tooltip=floorTip)
int   fastChannelLen       = input.int(title="Fast Channel Length", defval=12, minval=2, group="Channel Settings", tooltip=fastChannelTip)
int   slowChannelLen       = input.int(title="Slow Channel Length", defval=28, minval=3, group="Channel Settings", tooltip=slowChannelTip)
int   residenceLength      = input.int(title="Residence Length", defval=8, minval=2, group="Adaptive Settings", tooltip=residenceTip)
float structurePower       = input.float(title="Structure Influence", defval=0.55, minval=0.0, maxval=0.85, step=0.05, group="Adaptive Settings", tooltip=weightTip)
bool  showAverage          = input.bool(title="Show Adaptive Average", defval=true, group="Visualization", tooltip=averageTip)
bool  showBands            = input.bool(title="Show Adaptive Bands", defval=true, group="Visualization", tooltip=bandsTip)
int   bandTransparency     = input.int(title="Band Transparency", defval=40, minval=0, maxval=100, group="Visualization", tooltip=bandLineTip)
int   fillTransparency     = input.int(title="Band Fill Transparency", defval=80, minval=0, maxval=100, group="Visualization", tooltip=bandFillTip)
bool  showChannel          = input.bool(title="Show Donchian Channel", defval=true, group="Visualization", tooltip=channelTip)
bool  showDefense          = input.bool(title="Show Trend Defense", defval=true, group="Visualization", tooltip=defenseTip)
bool  showSignals          = input.bool(title="Show Signals", defval=true, group="Visualization", tooltip=signalsTip)
bool  colorBars            = input.bool(title="Color Bars", defval=true, group="Visualization", tooltip=barsTip)
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 priceMovement   = math.abs(source - source[1])
float totalMovement   = ta.sma(priceMovement, efficiencyLen) * efficiencyLen
float netProgress     = math.abs(source - source[efficiencyLen])
float efficiency      = not na(totalMovement) and totalMovement > 0.0 ? math.min(netProgress / totalMovement, 1.0) : 0.0
 
float fastConstant    = 2.0 / (kamaFast + 1.0)
float slowConstant    = 2.0 / (kamaSlow + 1.0)
float smoothingRate   = math.pow(efficiency * (fastConstant - slowConstant) + slowConstant, 2.0)
 
var float kama        = na
kama                 := na(kama[1]) ? source : kama[1] + smoothingRate * (source - kama[1])
 
float atrValue        = ta.atr(atrLength)
float residual        = source - kama
float rms             = math.sqrt(ta.sma(residual * residual, bandLength))
float bandDistance    = math.max(rms * bandMultiplier, atrValue * atrFloor)
float upperBand       = kama + bandDistance
float lowerBand       = kama - bandDistance
 
int effectiveSlowLen  = math.max(slowChannelLen, fastChannelLen + 1)
float fastHigh        = ta.highest(high[1], fastChannelLen)
float fastLow         = ta.lowest(low[1], fastChannelLen)
float slowHigh        = ta.highest(high[1], effectiveSlowLen)
float slowLow         = ta.lowest(low[1], effectiveSlowLen)
 
float bullishResidence = ta.sma(close > kama ? 1.0 : 0.0, residenceLength)
float bearishResidence = ta.sma(close < kama ? 1.0 : 0.0, residenceLength)
 
float longSlowWeight  = efficiency * bullishResidence
float shortSlowWeight = efficiency * bearishResidence
 
float longStructure   = fastLow * (1.0 - longSlowWeight) + slowLow * longSlowWeight
float shortStructure  = fastHigh * (1.0 - shortSlowWeight) + slowHigh * shortSlowWeight
 
float structureWeight = 0.15 + structurePower * efficiency
float bandWeight      = 1.0 - structureWeight
 
float longBoundary    = lowerBand * bandWeight + longStructure * structureWeight
float shortBoundary   = upperBand * bandWeight + shortStructure * structureWeight
 
bool ready            = not na(totalMovement) and not na(atrValue) and not na(bandDistance) and not na(fastHigh) and not na(fastLow) and not na(slowHigh) and not na(slowLow) and not na(bullishResidence) and not na(bearishResidence)
 
var int SQ            = 0
var float trendDefense = na
 
// SIGNALS
bool longSignal       = false
bool shortSignal      = false
if barstate.isconfirmed and ready
    if SQ == 0
        SQ           := close >= kama ? 1 : -1
        trendDefense := SQ == 1 ? math.min(longBoundary, close - syminfo.mintick) : math.max(shortBoundary, close + syminfo.mintick)
    else if SQ == 1
        if close < trendDefense
            SQ           := -1
            shortSignal  := true
            trendDefense := math.max(shortBoundary, close + syminfo.mintick)
        else
            float candidateDefense = math.min(longBoundary, close - syminfo.mintick)
            trendDefense := math.max(trendDefense, candidateDefense)
    else if SQ == -1
        if close > trendDefense
            SQ           := 1
            longSignal   := true
            trendDefense := math.min(longBoundary, close - syminfo.mintick)
        else
            float candidateDefense = math.max(shortBoundary, close + syminfo.mintick)
            trendDefense := math.min(trendDefense, candidateDefense)
 
// COLORS
color col             = SQ == 1 ? longColor : SQ == -1 ? shortColor : color.gray
color colors          = colorBars and SQ != 0 ? col : na
color averageColor    = color.new(col, 0)
color upperColor      = color.new(shortColor, bandTransparency)
color lowerColor      = color.new(longColor, bandTransparency)
color channelColor    = color.new(col, 78)
color bandFillColor   = color.new(col, fillTransparency)
 
float bullishDefense  = SQ == 1 ? trendDefense : na
float bearishDefense  = SQ == -1 ? trendDefense : na
float activeStructure = SQ == 1 ? longStructure : SQ == -1 ? shortStructure : na
 
// PLOTS
plot(showAverage ? kama : na, title="Kaufman Adaptive Average", color=averageColor, linewidth=2)
upperPlot = plot(showBands ? upperBand : na, title="Upper Adaptive Band", color=upperColor, linewidth=1)
lowerPlot = plot(showBands ? lowerBand : na, title="Lower Adaptive Band", color=lowerColor, linewidth=1)
fill(upperPlot, lowerPlot, title="Adaptive Band Fill", color=showBands ? bandFillColor : na)
plot(showChannel ? slowHigh : na, title="Upper Donchian Channel", color=channelColor, linewidth=1)
plot(showChannel ? slowLow : na, title="Lower Donchian Channel", color=channelColor, linewidth=1)
plot(showDefense ? bullishDefense : na, title="Bullish Trend Defense", color=longColor, linewidth=2, style=plot.style_linebr)
plot(showDefense ? bearishDefense : na, title="Bearish Trend Defense", color=shortColor, linewidth=2, style=plot.style_linebr)
plot(efficiency, title="Kaufman Efficiency Ratio", display=display.data_window)
plot(rms, title="Tracking Error RMS", display=display.data_window)
plot(bandDistance, title="Adaptive Band Distance", display=display.data_window)
plot(bullishResidence, title="Bullish Price Residence", display=display.data_window)
plot(bearishResidence, title="Bearish Price Residence", display=display.data_window)
plot(structureWeight, title="Structural Weight", display=display.data_window)
plot(longSlowWeight, title="Bullish Slow Channel Weight", display=display.data_window)
plot(shortSlowWeight, title="Bearish Slow Channel Weight", display=display.data_window)
plot(activeStructure, title="Active Structural Boundary", display=display.data_window)
plot(trendDefense, title="Active Trend Defense", display=display.data_window)
plot(float(SQ), title="Trend State", display=display.data_window)
plotshape(showSignals and longSignal, title="Long Signal", style=shape.triangleup, location=location.belowbar, size=size.small, color=longColor, text="LONG", textcolor=color.white, force_overlay=true)
plotshape(showSignals and shortSignal, title="Short Signal", style=shape.triangledown, location=location.abovebar, size=size.small, color=shortColor, text="SHORT", textcolor=color.white, force_overlay=true)
barcolor(colors, title = "Color Bars")
plotcandle(open, high, low, close, "Color Bars", colors, colors, bordercolor = colors, force_overlay = true)
 
// ALERTS
alertcondition(longSignal, title="Long Signal", message="Kaufman Adaptive Band-Channel Trend LONG on {{ticker}}")
alertcondition(shortSignal, title="Short Signal", message="Kaufman Adaptive Band-Channel Trend SHORT on {{ticker}}")

← 返回列表