本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This work is licensed under an Attribution-ShareAlike 4.0 International License (CC BY-SA 4.0)
// https://creativecommons.org/licenses/by-sa/4.0/
// © Uptrick
//@version=6
// ██╗ ██╗██████╗ ████████╗██████╗ ██╗ ██████╗██╗ ██╗
// ██║ ██║██╔══██╗╚══██╔══╝██╔══██╗██║██╔════╝██║ ██╔╝
// ██║ ██║██████╔╝ ██║ ██████╔╝██║██║ █████╔╝
// ██║ ██║██╔═══╝ ██║ ██╔══██╗██║██║ ██╔═██╗
// ╚██████╔╝██║ ██║ ██║ ██║██║╚██████╗██║ ██╗
// ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═════╝╚═╝ ╚═╝
indicator("Uptrick: Volatility Adjusted Mean", shorttitle="Volatility Adjusted Mean", overlay=true, max_labels_count=500)
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 01 · APPEARANCE
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
gStyle = "01 · Appearance"
bullColor = input.color(#00FFE5, "Bullish Color", group=gStyle, tooltip="Color for bullish candles, the trend line, gradient and 𝓑𝓾𝔂 labels.")
bearColor = input.color(#7030A0, "Bearish Color", group=gStyle, tooltip="Color for bearish candles, the trend line, gradient and 𝓢𝓮𝓵𝓵 labels.")
signalTextBull = input.color(#000000, "Buy Text", group=gStyle, tooltip="Text color inside bullish signal labels.")
signalTextBear = input.color(#FFFFFF, "Sell Text", group=gStyle, tooltip="Text color inside bearish signal labels.")
tpColor = input.color(#FFFFFF, "TP X Color", group=gStyle, tooltip="Color of take-profit X markers.")
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 02 · VECTOR ENGINE
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
gTrend = "02 · Vector Engine"
centerLength = input.int(18, "Center Responsiveness", minval=2, group=gTrend, tooltip="Efficiency-ratio lookback for the adaptive center line. Lower = faster, higher = smoother.")
fastLength = input.int(4, "Fast Response", minval=1, group=gTrend, tooltip="Fastest possible response of the adaptive center line during directional movement.")
slowLength = input.int(30, "Slow Response", minval=3, group=gTrend, tooltip="Slowest possible response of the adaptive center line during sideways movement.")
centerSmooth = input.int(5, "Center Smoothing", minval=1, group=gTrend, tooltip="Final EMA smoothing of the adaptive center line. A larger value produces a calmer line.")
atrLength = input.int(14, "ATR Length", minval=1, group=gTrend, tooltip="ATR period for volatility-adjusted signal thresholds and TP levels.")
breakoutATR = input.float(0.50, "Switch Buffer", minval=0.0, step=0.05, group=gTrend, tooltip="Price must close this many ATR beyond the center line to flip direction. Higher = fewer switches.")
slopeBars = input.int(3, "Slope Lookback", minval=1, group=gTrend, tooltip="Number of bars used to check whether the adaptive center line is rising or falling.")
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 03 · SIGNALS
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
gSignals = "03 · Signals"
showSignals = input.bool(true, "Show Buy / Sell", group=gSignals, tooltip="Show the 𝓑𝓾𝔂 and 𝓢𝓮𝓵𝓵 labels on confirmed trend reversals.")
signalCenterATR = input.float(0.7, "Signal Center Offset", minval=0.0, step=0.05, group=gSignals, tooltip="Buy labels are placed this many ATR below the smooth center line; Sell labels the same distance above it. Labels are anchored to the MIDLINE, not the candle highs/lows.")
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 04 · NOISE FILTERS
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
gFilters = "04 · Noise Filters"
useADX = input.bool(true, "Trend Strength (ADX)", group=gFilters, tooltip="Requires directional movement strength. Useful for avoiding flat, sideways conditions.")
adxLength = input.int(14, "ADX Period", minval=2, group=gFilters, tooltip="Lookback for directional movement and ADX smoothing.")
minADX = input.float(20.0, "Minimum ADX", minval=0, step=1, group=gFilters, tooltip="A higher threshold filters out more sideways price action. 20 is a moderate starting point.")
useRSI = input.bool(true, "Momentum Confirmation (RSI)", group=gFilters, tooltip="A Buy needs RSI above the bullish threshold; a Sell needs RSI below the bearish threshold.")
rsiLength = input.int(14, "RSI Period", minval=2, group=gFilters, tooltip="Momentum measurement length.")
rsiBullThreshold = input.float(52, "Buy RSI Above", minval=50, maxval=100, step=1, group=gFilters, tooltip="Higher means stricter bullish momentum confirmation.")
rsiBearThreshold = input.float(48, "Sell RSI Below", minval=0, maxval=50, step=1, group=gFilters, tooltip="Lower means stricter bearish momentum confirmation.")
useSlopeStrength = input.bool(true, "Minimum Center Slope", group=gFilters, tooltip="Requires the smooth center line to move meaningfully relative to volatility, not just tilt slightly.")
minSlopeATR = input.float(0.12, "Minimum Slope (ATR)", minval=0, step=0.02, group=gFilters, tooltip="Center-line movement over the slope lookback must exceed this fraction of one ATR.")
confirmationBars = input.int(2, "Consecutive Confirmations", minval=1, maxval=10, group=gFilters, tooltip="Number of closed candles that must consecutively meet the breakout and filter conditions before a signal.")
cooldownBars = input.int(6, "Bars Between Signals", minval=0, group=gFilters, tooltip="Minimum closed-bar spacing between Buy/Sell signals; 0 disables the cooldown.")
useHTF = input.bool(false, "Higher Timeframe Alignment", group=gFilters, tooltip="Optional stronger trend filter. Uses the last completed candle on the selected higher timeframe to avoid repainting.")
htfTF = input.timeframe("240", "Higher Timeframe", group=gFilters, tooltip="For a 1H chart, 4H is a typical confirmation timeframe. Select a timeframe HIGHER than the chart timeframe.")
htfEMALength = input.int(50, "Higher Timeframe EMA", minval=2, group=gFilters, tooltip="Buys require the last completed HTF close above its EMA; sells require it below its EMA.")
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 05 · TAKE PROFITS
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
gTP = "05 · Take Profits"
showTP = input.bool(true, "Show TP Xs", group=gTP, tooltip="Display each reached take-profit level once per signal.")
tp1ATR = input.float(1.0, "TP1 Distance", minval=0.1, step=0.1, group=gTP, tooltip="Distance from signal close, in ATR units.")
tp2ATR = input.float(2.0, "TP2 Distance", minval=0.1, step=0.1, group=gTP, tooltip="Distance from signal close, in ATR units.")
tp3ATR = input.float(3.25, "TP3 Distance", minval=0.1, step=0.05, group=gTP, tooltip="Distance from signal close, in ATR units.")
tpXOffsetATR = input.float(0.6, "TP X Offset", minval=0.0, step=0.1, group=gTP, tooltip="Plot TP X markers this many ATR above bullish candles or below bearish candles.")
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 06 · DISPLAY
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
gDisplay = "06 · Display"
showGradient = input.bool(true, "Vertical Gradient", group=gDisplay, tooltip="Fade the active trend color smoothly from the center line toward price.")
showCandles = input.bool(true, "Trend Candles", group=gDisplay, tooltip="Overlay candles painted with the bullish or bearish scheme.")
showCenter = input.bool(true, "Smooth Center Line", group=gDisplay, tooltip="Show or hide the adaptive midline. Signal positions remain tied to it even if hidden.")
gradientTransparency = input.int(72, "Gradient At Center", minval=0, maxval=100, group=gDisplay, tooltip="Transparency of the gradient where it touches the center line.")
lineTransparency = input.int(20, "Center Transparency", minval=0, maxval=100, group=gDisplay, tooltip="Transparency of the smooth center line.")
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ADAPTIVE CENTER LINE — EFFICIENCY RATIO / KAMA-STYLE SMOOTHING
// Different from Adaptive Trend Matrix's EMA + ratcheting trails + votes.
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
source = hlc3
changeAbs = math.abs(source - source[centerLength])
noise = math.sum(math.abs(ta.change(source)), centerLength)
efficiency = noise > 0 ? changeAbs / noise : 0.0
fastSC = 2.0 / (fastLength + 1.0)
slowSC = 2.0 / (slowLength + 1.0)
smoothingConstant = math.pow(efficiency * (fastSC - slowSC) + slowSC, 2)
var float adaptive = na
adaptive := na(adaptive[1]) ? source : adaptive[1] + smoothingConstant * (source - adaptive[1])
center = ta.ema(adaptive, centerSmooth)
atr = ta.atr(atrLength)
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// VOLATILITY-GATED CENTER CROSSINGS + SLOPE CONFIRMATION
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
upperSwitch = center + atr * breakoutATR
lowerSwitch = center - atr * breakoutATR
upwardSlope = center > center[slopeBars]
downwardSlope = center < center[slopeBars]
var int trend = 0
if trend == 0 and not na(center[slopeBars])
trend := close >= center ? 1 : -1
// A qualifying breakout must persist, rather than flicker across the band.
[plusDI, minusDI, adxValue] = ta.dmi(adxLength, adxLength)
rsiValue = ta.rsi(close, rsiLength)
strongSlopeUp = center - center[slopeBars] >= atr * minSlopeATR
strongSlopeDown = center[slopeBars] - center >= atr * minSlopeATR
// The [1] values are from the last confirmed HTF candle (non-repainting).
htfBull = request.security(syminfo.tickerid, htfTF, close[1] > ta.ema(close, htfEMALength)[1], lookahead=barmerge.lookahead_on)
htfBear = request.security(syminfo.tickerid, htfTF, close[1] < ta.ema(close, htfEMALength)[1], lookahead=barmerge.lookahead_on)
htfValid = timeframe.in_seconds(htfTF) > timeframe.in_seconds(timeframe.period)
allowBuy = (not useADX or (adxValue >= minADX and plusDI > minusDI)) and (not useRSI or rsiValue > rsiBullThreshold) and (not useSlopeStrength or strongSlopeUp) and (not useHTF or (htfValid and htfBull))
allowSell = (not useADX or (adxValue >= minADX and minusDI > plusDI)) and (not useRSI or rsiValue < rsiBearThreshold) and (not useSlopeStrength or strongSlopeDown) and (not useHTF or (htfValid and htfBear))
qualifiedBuy = close > upperSwitch and upwardSlope and allowBuy
qualifiedSell = close < lowerSwitch and downwardSlope and allowSell
var int buyStreak = 0
var int sellStreak = 0
buyStreak := barstate.isconfirmed and qualifiedBuy ? buyStreak + 1 : barstate.isconfirmed ? 0 : buyStreak
sellStreak := barstate.isconfirmed and qualifiedSell ? sellStreak + 1 : barstate.isconfirmed ? 0 : sellStreak
var int lastSignalBar = na
cooldownPassed = na(lastSignalBar) or bar_index - lastSignalBar > cooldownBars
buySignal = barstate.isconfirmed and trend == -1 and buyStreak >= confirmationBars and cooldownPassed
sellSignal = barstate.isconfirmed and trend == 1 and sellStreak >= confirmationBars and cooldownPassed
if buySignal
trend := 1
lastSignalBar := bar_index
else if sellSignal
trend := -1
lastSignalBar := bar_index
trendColor = trend == 1 ? bullColor : bearColor
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// TAKE-PROFIT TRACKING
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
var int tradeDirection = 0
var int signalBar = na
var float tp1 = na
var float tp2 = na
var float tp3 = na
var bool tp1Hit = false
var bool tp2Hit = false
var bool tp3Hit = false
if buySignal or sellSignal
tradeDirection := buySignal ? 1 : -1
signalBar := bar_index
tp1 := close + tradeDirection * atr * tp1ATR
tp2 := close + tradeDirection * atr * tp2ATR
tp3 := close + tradeDirection * atr * tp3ATR
tp1Hit := false
tp2Hit := false
tp3Hit := false
canCheckTP = barstate.isconfirmed and not na(signalBar) and bar_index > signalBar
longTP1 = canCheckTP and tradeDirection == 1 and not tp1Hit and high >= tp1
longTP2 = canCheckTP and tradeDirection == 1 and not tp2Hit and high >= tp2
longTP3 = canCheckTP and tradeDirection == 1 and not tp3Hit and high >= tp3
shortTP1 = canCheckTP and tradeDirection == -1 and not tp1Hit and low <= tp1
shortTP2 = canCheckTP and tradeDirection == -1 and not tp2Hit and low <= tp2
shortTP3 = canCheckTP and tradeDirection == -1 and not tp3Hit and low <= tp3
longX = high + atr * tpXOffsetATR
shortX = low - atr * tpXOffsetATR
plotchar(showTP ? (longTP1 ? longX : shortTP1 ? shortX : na) : na, title="Volatility Adjusted Mean TP1", char="X", location=location.absolute, color=tpColor, size=size.tiny)
plotchar(showTP ? (longTP2 ? longX : shortTP2 ? shortX : na) : na, title="Volatility Adjusted Mean TP2", char="X", location=location.absolute, color=tpColor, size=size.tiny)
plotchar(showTP ? (longTP3 ? longX : shortTP3 ? shortX : na) : na, title="Volatility Adjusted Mean TP3", char="X", location=location.absolute, color=tpColor, size=size.tiny)
if barstate.isconfirmed
if longTP1 or shortTP1
tp1Hit := true
if longTP2 or shortTP2
tp2Hit := true
if longTP3 or shortTP3
tp3Hit := true
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// SMOOTH CENTER, VERTICAL GRADIENT & TREND CANDLES
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
pCenter = plot(showCenter or showGradient ? center : na, "Volatility Adjusted Mean Smooth Center", color=color.new(trendColor, showCenter ? lineTransparency : 100), linewidth=4)
pPrice = plot(close, "Volatility Adjusted Mean Price Anchor", color=color.new(trendColor, 100), display=display.none)
gradientTop = math.max(close, center)
gradientBottom = math.min(close, center)
priceAboveCenter = close >= center
centerFade = color.new(trendColor, gradientTransparency)
priceFade = color.new(trendColor, 100)
fill(pCenter, pPrice, gradientTop, gradientBottom, showGradient ? (priceAboveCenter ? priceFade : centerFade) : na, showGradient ? (priceAboveCenter ? centerFade : priceFade) : na, title="Volatility Adjusted Mean Gradient")
plotcandle(showCandles ? open : na, showCandles ? high : na, showCandles ? low : na, showCandles ? close : na, title="Volatility Adjusted Mean Candles", color=trendColor, wickcolor=trendColor, bordercolor=trendColor)
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// MIDLINE-ANCHORED STYLIZED BUY / SELL LABELS
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
buyAnchor = center - atr * signalCenterATR
sellAnchor = center + atr * signalCenterATR
if showSignals and buySignal
label.new(bar_index, buyAnchor, "𝓑𝓾𝔂", yloc=yloc.price, style=label.style_label_up, color=bullColor, textcolor=signalTextBull, size=size.normal, tooltip="Volatility Adjusted Mean Buy\n\nConfirmed bullish breakout with enabled trend-strength and momentum filters.")
if showSignals and sellSignal
label.new(bar_index, sellAnchor, "𝓢𝓮𝓵𝓵", yloc=yloc.price, style=label.style_label_down, color=bearColor, textcolor=signalTextBear, size=size.normal, tooltip="Volatility Adjusted Mean Sell\n\nConfirmed bearish breakout with enabled trend-strength and momentum filters.")
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ALERTS
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
alertcondition(buySignal, "Volatility Adjusted Mean Buy", "Uptrick Volatility Adjusted Mean Buy on {{ticker}}")
alertcondition(sellSignal, "Volatility Adjusted Mean Sell", "Uptrick Volatility Adjusted Mean Sell on {{ticker}}")
alertcondition(longTP1 or shortTP1, "Volatility Adjusted Mean TP1", "Uptrick Volatility Adjusted Mean TP1 reached on {{ticker}}")
alertcondition(longTP2 or shortTP2, "Volatility Adjusted Mean TP2", "Uptrick Volatility Adjusted Mean TP2 reached on {{ticker}}")
alertcondition(longTP3 or shortTP3, "Volatility Adjusted Mean TP3", "Uptrick Volatility Adjusted Mean TP3 reached on {{ticker}}")
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// READ-ONLY MARKET DASHBOARD — NO EFFECT ON TRADING SIGNALS
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
var table dashboard = table.new(position.top_right, 2, 7, bgcolor=#000000, frame_color=color.white, frame_width=1, border_color=color.white, border_width=1)
// The header occupies both columns; the dashboard is display-only.
if barstate.isfirst
table.merge_cells(dashboard, 0, 0, 1, 0)
if barstate.islast
string trendName = trend == 1 ? "𝓑𝓾𝓵𝓵𝓲𝓼𝓱" : trend == -1 ? "𝓑𝓮𝓪𝓻𝓲𝓼𝓱" : "𝓝𝓮𝓾𝓽𝓻𝓪𝓵"
string slopeName = upwardSlope ? "𝓡𝓲𝓼𝓲𝓷𝓰" : downwardSlope ? "𝓕𝓪𝓵𝓵𝓲𝓷𝓰" : "𝓕𝓵𝓪𝓽"
string strengthName = adxValue >= minADX ? "𝓢𝓽𝓻𝓸𝓷𝓰" : "𝓦𝓮𝓪𝓴"
string tpName = tradeDirection == 0 ? "𝓝𝓸 𝓣𝓻𝓪𝓭𝓮" : (tp3Hit ? "𝓣𝓟3 𝓗𝓲𝓽" : tp2Hit ? "𝓣𝓟2 𝓗𝓲𝓽" : tp1Hit ? "𝓣𝓟1 𝓗𝓲𝓽" : "𝓐𝓬𝓽𝓲𝓿𝓮")
table.cell(dashboard, 0, 0, "𝓤𝓹𝓽𝓻𝓲𝓬𝓴: 𝓥𝓸𝓵𝓪𝓽𝓲𝓵𝓲𝓽𝔂 𝓐𝓭𝓳𝓾𝓼𝓽𝓮𝓭 𝓜𝓮𝓪𝓷", text_color=color.white, text_size=size.normal, text_halign=text.align_center, bgcolor=color.black)
table.cell(dashboard, 0, 1, "𝓓𝓲𝓻𝓮𝓬𝓽𝓲𝓸𝓷", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 1, trendName, text_color=color.white, text_size=size.small)
table.cell(dashboard, 0, 2, "𝓒𝓮𝓷𝓽𝓮𝓻 𝓛𝓲𝓷𝓮", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 2, str.tostring(center, format.mintick), text_color=color.white, text_size=size.small)
table.cell(dashboard, 0, 3, "𝓛𝓲𝓷𝓮 𝓢𝓵𝓸𝓹𝓮", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 3, slopeName, text_color=color.white, text_size=size.small)
table.cell(dashboard, 0, 4, "𝓐𝓓𝓧 𝓢𝓽𝓻𝓮𝓷𝓰𝓽𝓱", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 4, str.tostring(adxValue, "#.0") + " · " + strengthName, text_color=color.white, text_size=size.small)
table.cell(dashboard, 0, 5, "𝓡𝓢𝓘 𝓜𝓸𝓶𝓮𝓷𝓽𝓾𝓶", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 5, str.tostring(rsiValue, "#.0"), text_color=color.white, text_size=size.small)
table.cell(dashboard, 0, 6, "𝓣𝓪𝓴𝓮 𝓟𝓻𝓸𝓯𝓲𝓽𝓼", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 6, tpName, text_color=color.white, text_size=size.small)