本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// ══════════════════════════════════════════════════════════
// ADAPTIVE VOLATILITY TREND [WillyAlgoTrader]
// ══════════════════════════════════════════════════════════
// Author: Willy | WillyAlgoTrader
// Version: 1.0.0
// Date: 2025-02-17
//
// ── CHANGELOG ─────────────────────────────────────────────
// v1.0.0 2025-02-17 Initial release
// • Adaptive trend filter using Kaufman Efficiency Ratio + ATR
// • Momentum scoring system (0-100)
// • Volume-confirmed signals with forex bypass
// • Dashboard, alerts, webhook, theme support
// • Full na-protection and anti-repaint compliance
// ══════════════════════════════════════════════════════════
indicator(
title = "Adaptive Volatility Trend [WillyAlgoTrader]",
shorttitle = "AVT",
overlay = true,
max_labels_count = 500,
max_lines_count = 500,
max_boxes_count = 200)
// ══════════════════════════════════════
// CONSTANTS
// ══════════════════════════════════════
GRP_MAIN = "⚙️ Main Settings"
GRP_FILTER = "🔍 Filters"
GRP_VISUAL = "🎨 Visual"
GRP_DASH = "📊 Dashboard"
GRP_ALERT = "🔔 Alerts"
GRP_COLORS = "🎨 Colors"
GRP_ADV = "🔧 Advanced"
INDICATOR_VERSION = "v1.0.0"
// ══════════════════════════════════════
// INPUTS — Main Settings
// ══════════════════════════════════════
sourceInput = input.source(close, "Source", group = GRP_MAIN,
tooltip = "Price source for all calculations.\n• close (default) is most stable\n• hl2 or hlc3 for smoother response")
lengthInput = input.int(21, "Trend Length", minval = 5, maxval = 200, step = 1, group = GRP_MAIN,
tooltip = "Lookback period for the adaptive trend filter.\n" +
"• Higher = smoother trend, fewer signals\n" +
"• Lower = faster response, more noise\n" +
"• Recommended: 14-30")
atrLenInput = input.int(14, "ATR Length", minval = 5, maxval = 100, step = 1, group = GRP_MAIN,
tooltip = "Period for ATR-based volatility bands.\n" +
"• Higher = wider bands, fewer whipsaws\n" +
"• Lower = tighter bands, faster reaction\n" +
"• Recommended: 10-20")
atrMultInput = input.float(2.0, "Band Multiplier", minval = 0.5, maxval = 5.0, step = 0.1, group = GRP_MAIN,
tooltip = "Multiplier for ATR-based channel width.\n" +
"• Higher = wider channel, fewer false signals\n" +
"• Lower = tighter channel, earlier entries\n" +
"• Recommended: 1.5-3.0")
presetInput = input.string("Default", "Preset",
options = ["Conservative", "Default", "Aggressive", "Scalping"],
group = GRP_MAIN,
tooltip = "Quick presets (override Length/ATR/Mult):\n" +
"• Conservative: 30 / 20 / 2.5 — fewer signals, higher reliability\n" +
"• Default: 20 / 14 / 2.0 — balanced\n" +
"• Aggressive: 12 / 10 / 1.5 — more signals, faster\n" +
"• Scalping: 8 / 7 / 1.2 — optimized for 1-5min")
// ══════════════════════════════════════
// INPUTS — Filters
// ══════════════════════════════════════
useRsiFilterInput = input.bool(true, "RSI Momentum Filter", group = GRP_FILTER,
tooltip = "Require RSI confirmation for signals.\n" +
"• Buy only when RSI is not overbought\n" +
"• Sell only when RSI is not oversold\n" +
"• Reduces false signals in ranging markets")
rsiLenInput = input.int(14, "RSI Length", minval = 5, maxval = 50, step = 1, group = GRP_FILTER,
tooltip = "RSI calculation period.\n• Recommended: 14")
rsiObInput = input.int(70, "RSI Overbought", minval = 60, maxval = 90, step = 5, group = GRP_FILTER,
tooltip = "RSI level above which bullish signals are filtered out")
rsiOsInput = input.int(30, "RSI Oversold", minval = 10, maxval = 40, step = 5, group = GRP_FILTER,
tooltip = "RSI level below which bearish signals are filtered out")
useVolFilterInput = input.bool(true, "Volume Filter", group = GRP_FILTER,
tooltip = "Require above-average volume for signal confirmation.\n" +
"• Automatically disabled on instruments with no volume (forex)\n" +
"• Helps avoid low-conviction breakouts")
volMultInput = input.float(1.2, "Volume Threshold", minval = 0.5, maxval = 3.0, step = 0.1, group = GRP_FILTER,
tooltip = "Signal requires volume > SMA(volume) × this multiplier.\n" +
"• Higher = stricter volume filter\n" +
"• Recommended: 1.0-1.5")
// ══════════════════════════════════════
// INPUTS — Visual
// ══════════════════════════════════════
themeInput = input.string("Auto", "Theme",
options = ["Auto", "Dark", "Light"],
group = GRP_VISUAL,
tooltip = "Chart color theme.\n" +
"• Auto: detects from chart background\n" +
"• Dark: optimized for dark backgrounds\n" +
"• Light: optimized for light/white backgrounds")
showSignalsInput = input.bool(true, "Show Buy/Sell Signals", group = GRP_VISUAL,
tooltip = "Display BUY/SELL labels on chart")
showBandsInput = input.bool(true, "Show Trend Bands", group = GRP_VISUAL,
tooltip = "Display the adaptive volatility channel bands")
showFillInput = input.bool(true, "Show Band Fill", group = GRP_VISUAL,
tooltip = "Fill area between trend line and bands")
showTrendLineInput = input.bool(true, "Show Trend Line", group = GRP_VISUAL,
tooltip = "Display the main adaptive trend line")
showBarColorInput = input.bool(false, "Bar Coloring", group = GRP_VISUAL,
tooltip = "Color candles based on trend direction")
showBgInput = input.bool(false, "Background Shading", group = GRP_VISUAL,
tooltip = "Light background tint based on trend direction")
showWatermarkInput = input.bool(true, "Show Watermark", group = GRP_VISUAL,
tooltip = "Display 'WillyAlgoTrader - by Willy' watermark on chart")
// ══════════════════════════════════════
// INPUTS — Dashboard
// ══════════════════════════════════════
showDashInput = input.bool(true, "Show Dashboard", group = GRP_DASH,
tooltip = "Display information panel with trend, signal, and score")
dashPosStr = input.string("Top Right", "Position",
options = ["Top Left", "Top Right", "Bottom Left", "Bottom Right"],
group = GRP_DASH,
tooltip = "Dashboard position on chart")
// ══════════════════════════════════════
// INPUTS — Alerts
// ══════════════════════════════════════
webhookInput = input.bool(false, "Webhook JSON Format", group = GRP_ALERT,
tooltip = "Send alerts in JSON format for webhook integrations.\n" +
"• Enable for 3Commas, Alertatron, custom bots\n" +
"• Disable for standard TradingView notifications")
// ══════════════════════════════════════
// INPUTS — Colors
// ══════════════════════════════════════
bullColorInput = input.color(#00E676, "Bull", inline = "colors", group = GRP_COLORS,
tooltip = "Color for bullish signals and trend")
bearColorInput = input.color(#FF5252, "Bear", inline = "colors", group = GRP_COLORS,
tooltip = "Color for bearish signals and trend")
neutralColorInput = input.color(#FFEB3B, "Neutral", inline = "colors", group = GRP_COLORS,
tooltip = "Color for neutral/ranging conditions")
// ══════════════════════════════════════
// INPUTS — Advanced
// ══════════════════════════════════════
erSmoothInput = input.int(5, "Efficiency Smoothing", minval = 1, maxval = 20, step = 1, group = GRP_ADV,
tooltip = "Smoothing for Kaufman Efficiency Ratio.\n" +
"• Higher = smoother adaptation\n" +
"• Lower = faster adaptation\n" +
"• Recommended: 3-8")
minScoreInput = input.int(40, "Min Signal Score", minval = 0, maxval = 80, step = 5, group = GRP_ADV,
tooltip = "Minimum composite score (0-100) required for a signal.\n" +
"• Higher = fewer but higher quality signals\n" +
"• Lower = more signals, including weaker ones\n" +
"• Recommended: 30-60")
// ══════════════════════════════════════
// PRESET OVERRIDES
// ══════════════════════════════════════
effectiveLength = switch presetInput
"Conservative" => 30
"Aggressive" => 12
"Scalping" => 8
=> lengthInput
effectiveAtrLen = switch presetInput
"Conservative" => 20
"Aggressive" => 10
"Scalping" => 7
=> atrLenInput
effectiveMult = switch presetInput
"Conservative" => 2.5
"Aggressive" => 1.5
"Scalping" => 1.2
=> atrMultInput
// ══════════════════════════════════════
// THEME DETECTION & PALETTE
// ══════════════════════════════════════
isDark = switch themeInput
"Dark" => true
"Light" => false
=> color.r(chart.bg_color) < 128
// ── Texts ───────────────────────────────────────────────
TEXT_COLOR = isDark ? #E0E0E0 : #1A1A1A
TEXT_MUTED = isDark ? color.new(#9E9E9E, 0) : color.new(#757575, 0)
TEXT_BRIGHT = isDark ? #FFFFFF : #000000
// ── Dashboard / Tables ──────────────────────────────────
TABLE_BG = isDark ? color.new(#131722, 5) : color.new(#FFFFFF, 5)
TABLE_BORDER = isDark ? color.new(#2A2E39, 0) : color.new(#D0D0D0, 0)
TABLE_ROW_ALT = isDark ? color.new(#1C2030, 0) : color.new(#F0F4F8, 0)
HEADER_BG = color.new(#2962FF, 0)
HEADER_TEXT = #FFFFFF
// ── Labels ──────────────────────────────────────────────
LABEL_TEXT = #FFFFFF
// ── Lines ───────────────────────────────────────────────
LINE_SUBTLE = isDark ? color.new(#555555, 0) : color.new(#AAAAAA, 0)
// ── Watermark ───────────────────────────────────────────
WM_COLOR = isDark ? color.new(#FFFFFF, 80) : color.new(#000000, 80)
// ── Backgrounds ─────────────────────────────────────────
BULL_BG = color.new(bullColorInput, 88)
BEAR_BG = color.new(bearColorInput, 88)
// ══════════════════════════════════════
// FUNCTIONS
// ══════════════════════════════════════
// Safe division (na + zero protection)
safeDiv(float num, float den, float fallback = 0.0) =>
den != 0 and not na(num) and not na(den) ? num / den : fallback
// Kaufman Efficiency Ratio — measures trend efficiency (0 = chop, 1 = perfect trend)
calcEfficiencyRatio(float src, int len) =>
float direction = math.abs(nz(src, 0.0) - nz(src[len], src))
float volatility = math.sum(math.abs(nz(src, 0.0) - nz(src[1], src)), len)
safeDiv(direction, volatility, 0.0)
// Adaptive EMA — speed adjusts based on efficiency ratio
calcAdaptiveMA(float src, int len, int smooth) =>
float er = calcEfficiencyRatio(src, len)
float erSmth = nz(ta.ema(er, smooth), 0.5)
float fastSC = 2.0 / (2.0 + 1.0) // fast constant
float slowSC = 2.0 / (30.0 + 1.0) // slow constant
float sc = math.pow(erSmth * (fastSC - slowSC) + slowSC, 2)
var float adaptMA = na
float safeSrc = nz(src, close)
adaptMA := na(adaptMA) ? safeSrc : nz(adaptMA[1], safeSrc) + sc * (safeSrc - nz(adaptMA[1], safeSrc))
[adaptMA, erSmth]
// Signal score calculator (0-100)
calcSignalScore(bool isBull, float er, float rsiVal, float volRatio, bool hasVol) =>
// Trend strength component (0-40)
float trendScore = math.min(er * 60.0, 40.0)
// Momentum component (0-30): distance of RSI from neutral
float rsiDist = isBull ? math.max(rsiVal - 50.0, 0.0) : math.max(50.0 - rsiVal, 0.0)
float momScore = math.min(rsiDist * 1.0, 30.0)
// Volume component (0-30)
float volScore = hasVol ? math.min(math.max(volRatio - 1.0, 0.0) * 30.0, 30.0) : 15.0
float total = trendScore + momScore + volScore
math.round(math.min(total, 100.0))
// ══════════════════════════════════════
// DASHBOARD POSITION
// ══════════════════════════════════════
dashPos = switch dashPosStr
"Top Left" => position.top_left
"Top Right" => position.top_right
"Bottom Left" => position.bottom_left
"Bottom Right" => position.bottom_right
=> position.top_right
// ══════════════════════════════════════
// CALCULATIONS (na-protected)
// ══════════════════════════════════════
// Warmup — no signals until enough bars
int WARMUP_BARS = math.max(effectiveLength * 2, 50)
bool isWarmedUp = bar_index >= WARMUP_BARS
// Core: Adaptive Moving Average
[adaptLine, effRatio] = calcAdaptiveMA(sourceInput, effectiveLength, erSmoothInput)
float safeLine = nz(adaptLine, close)
// ATR for channel width
float atrRaw = nz(ta.atr(effectiveAtrLen), 0.0)
// Adaptive width: narrows in trend (high ER), widens in chop (low ER)
float erFactor = 1.0 - nz(effRatio, 0.5) * 0.4 // 0.6x in trend, 1.0x in chop
float bandWidth = atrRaw * effectiveMult * erFactor
float upperBand = safeLine + bandWidth
float lowerBand = safeLine - bandWidth
// Trend direction via adaptive line slope
var int trendDir = 0
float lineDelta = safeLine - nz(safeLine[1], safeLine)
float threshold = atrRaw * 0.05 // small threshold to avoid noise
trendDir := lineDelta > threshold ? 1 : lineDelta < -threshold ? -1 : trendDir
bool isBullTrend = trendDir == 1
bool isBearTrend = trendDir == -1
// RSI
float rsiValue = nz(ta.rsi(sourceInput, rsiLenInput), 50.0)
// Volume
bool hasVolume = nz(volume, 0) > 0
float volSma = hasVolume ? nz(ta.sma(volume, 20), volume) : 0.0
float volRatio = hasVolume and volSma > 0 ? volume / volSma : 1.0
bool volConfirm = not useVolFilterInput or not hasVolume or (volRatio >= volMultInput)
// RSI filter
bool rsiBuyOk = not useRsiFilterInput or rsiValue < rsiObInput
bool rsiSellOk = not useRsiFilterInput or rsiValue > rsiOsInput
// ══════════════════════════════════════
// SIGNAL LOGIC
// ══════════════════════════════════════
// Trend change detection
bool trendFlipBull = isBullTrend and not isBullTrend[1]
bool trendFlipBear = isBearTrend and not isBearTrend[1]
// Price must be on the right side of the adaptive line
bool priceAbove = sourceInput > safeLine
bool priceBelow = sourceInput < safeLine
// Composite buy/sell conditions
bool buyCondition = trendFlipBull and priceAbove and rsiBuyOk and volConfirm
bool sellCondition = trendFlipBear and priceBelow and rsiSellOk and volConfirm
// Signal scoring
int buyScore = buyCondition ? calcSignalScore(true, nz(effRatio, 0.0), rsiValue, volRatio, hasVolume) : 0
int sellScore = sellCondition ? calcSignalScore(false, nz(effRatio, 0.0), rsiValue, volRatio, hasVolume) : 0
// Confirmed signals (anti-repaint + warmup + minimum score)
bool confirmedBuy = buyCondition and barstate.isconfirmed and isWarmedUp and buyScore >= minScoreInput
bool confirmedSell = sellCondition and barstate.isconfirmed and isWarmedUp and sellScore >= minScoreInput
// Track last signal for dashboard
var string lastSignal = "—"
var color lastSignalClr = color.gray
var int lastSignalBar = 0
var int lastScore = 0
if confirmedBuy
lastSignal := "BUY"
lastSignalClr := bullColorInput
lastSignalBar := bar_index
lastScore := buyScore
if confirmedSell
lastSignal := "SELL"
lastSignalClr := bearColorInput
lastSignalBar := bar_index
lastScore := sellScore
// ══════════════════════════════════════
// PLOTS & VISUALS
// ══════════════════════════════════════
// Trend line
trendColor = isBullTrend ? bullColorInput : isBearTrend ? bearColorInput : neutralColorInput
plot(showTrendLineInput ? safeLine : na, "Adaptive Trend", color = trendColor, linewidth = 3)
// Bands
pUpper = plot(showBandsInput ? upperBand : na, "Upper Band", color = color.new(bullColorInput, 70), linewidth = 1)
pLower = plot(showBandsInput ? lowerBand : na, "Lower Band", color = color.new(bearColorInput, 70), linewidth = 1)
pTrend = plot(showBandsInput and showFillInput ? safeLine : na, "Trend (fill anchor)", color = na, display = display.none)
// Band fills
fill(pUpper, pTrend, color = showFillInput ? color.new(bullColorInput, 90) : na, title = "Upper Fill")
fill(pLower, pTrend, color = showFillInput ? color.new(bearColorInput, 90) : na, title = "Lower Fill")
// Background shading
bgcolor(showBgInput and isBullTrend ? BULL_BG : showBgInput and isBearTrend ? BEAR_BG : na, title = "Trend Background")
// Bar coloring
trendBarColor = isBullTrend and priceAbove ? (sourceInput > sourceInput[1] ? bullColorInput : color.new(bullColorInput, 40)) : isBearTrend and priceBelow ? (sourceInput < sourceInput[1] ? bearColorInput : color.new(bearColorInput, 40)) : na
barcolor(showBarColorInput ? trendBarColor : na)
// ══════════════════════════════════════
// SIGNAL LABELS
// ══════════════════════════════════════
plotshape(showSignalsInput and confirmedBuy ? low : na, "Buy Signal",
style = shape.labelup,
location = location.belowbar,
color = bullColorInput,
textcolor = LABEL_TEXT,
text = "▲",
size = size.small)
plotshape(showSignalsInput and confirmedSell ? high : na, "Sell Signal",
style = shape.labeldown,
location = location.abovebar,
color = bearColorInput,
textcolor = LABEL_TEXT,
text = "▼",
size = size.small)
// ══════════════════════════════════════
// DASHBOARD
// ══════════════════════════════════════
if showDashInput and barstate.islast
var dashTable = table.new(dashPos, 2, 8, TABLE_BG, TABLE_BORDER, 1, TABLE_BORDER, 1)
// Header
table.cell(dashTable, 0, 0, "AVT", text_color = HEADER_TEXT,
bgcolor = HEADER_BG, text_size = size.small, text_halign = text.align_center)
table.merge_cells(dashTable, 0, 0, 1, 0)
// Row 1 — Trend
string trendStr = isBullTrend ? "Bullish" : isBearTrend ? "Bearish" : "Neutral"
color trendClr = isBullTrend ? bullColorInput : isBearTrend ? bearColorInput : neutralColorInput
table.cell(dashTable, 0, 1, "Trend", text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_BG)
table.cell(dashTable, 1, 1, trendStr, text_color = trendClr, text_size = size.small, bgcolor = TABLE_BG)
// Row 2 — Signal
table.cell(dashTable, 0, 2, "Signal", text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_ROW_ALT)
table.cell(dashTable, 1, 2, lastSignal, text_color = lastSignalClr, text_size = size.small, bgcolor = TABLE_ROW_ALT)
// Row 3 — Score
string scoreStr = lastScore > 0 ? str.tostring(lastScore) + " / 100" : "—"
color scoreClr = lastScore >= 70 ? bullColorInput : lastScore >= 40 ? neutralColorInput : TEXT_MUTED
table.cell(dashTable, 0, 3, "Score", text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_BG)
table.cell(dashTable, 1, 3, scoreStr, text_color = scoreClr, text_size = size.small, bgcolor = TABLE_BG)
// Row 4 — Efficiency
string erStr = na(effRatio) ? "—" : str.tostring(effRatio * 100, "#.0") + "%"
table.cell(dashTable, 0, 4, "Efficiency", text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_ROW_ALT)
table.cell(dashTable, 1, 4, erStr, text_color = TEXT_COLOR, text_size = size.small, bgcolor = TABLE_ROW_ALT)
// Row 5 — RSI
string rsiStr = na(rsiValue) ? "—" : str.tostring(rsiValue, "#.0")
color rsiClr = rsiValue > rsiObInput ? bearColorInput : rsiValue < rsiOsInput ? bullColorInput : TEXT_COLOR
table.cell(dashTable, 0, 5, "RSI", text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_BG)
table.cell(dashTable, 1, 5, rsiStr, text_color = rsiClr, text_size = size.small, bgcolor = TABLE_BG)
// Row 6 — Timeframe
table.cell(dashTable, 0, 6, "TF", text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_ROW_ALT)
table.cell(dashTable, 1, 6, timeframe.period, text_color = TEXT_COLOR, text_size = size.small, bgcolor = TABLE_ROW_ALT)
// Row 7 — Version
table.cell(dashTable, 0, 7, "Version", text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_BG)
table.cell(dashTable, 1, 7, INDICATOR_VERSION, text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_BG)
// ══════════════════════════════════════
// WATERMARK — WillyAlgoTrader
// ══════════════════════════════════════
if barstate.islast and showWatermarkInput
var wmTable = table.new(
position = position.bottom_center,
columns = 1,
rows = 1,
bgcolor = color.new(color.black, 100),
border_color = color.new(color.black, 100),
border_width = 0,
frame_color = color.new(color.black, 100),
frame_width = 0)
table.cell(wmTable, 0, 0, "WillyAlgoTrader",
text_color = WM_COLOR,
text_size = size.normal,
text_halign = text.align_center,
bgcolor = color.new(color.black, 100))
// ══════════════════════════════════════
// ALERTS
// ══════════════════════════════════════
string buyMsg = webhookInput ? '{"action":"buy","ticker":"' + syminfo.tickerid + '","price":' + str.tostring(close) + ',"tf":"' + timeframe.period + '","score":' + str.tostring(buyScore) + '}' : "🟢 BUY | " + syminfo.tickerid + " | TF: " + timeframe.period + " | Price: " + str.tostring(close, format.mintick) + " | Score: " + str.tostring(buyScore) + " | Time: " + str.format_time(time, "yyyy-MM-dd HH:mm", syminfo.timezone)
string sellMsg = webhookInput ? '{"action":"sell","ticker":"' + syminfo.tickerid + '","price":' + str.tostring(close) + ',"tf":"' + timeframe.period + '","score":' + str.tostring(sellScore) + '}' : "🔴 SELL | " + syminfo.tickerid + " | TF: " + timeframe.period + " | Price: " + str.tostring(close, format.mintick) + " | Score: " + str.tostring(sellScore) + " | Time: " + str.format_time(time, "yyyy-MM-dd HH:mm", syminfo.timezone)
if confirmedBuy
alert(buyMsg, alert.freq_once_per_bar_close)
if confirmedSell
alert(sellMsg, alert.freq_once_per_bar_close)