RC Tools - VIDYA Adaptive Trend

RC-Tools · study · 180 行 · 点赞 18 · 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/
// © RAC97
 
//@version=6
indicator("RC Tools - VIDYA Adaptive Trend", shorttitle="RC VIDYA", overlay=true)
 
// ─────────────────────────────────────────────────────────────────────────────
// ABOUT
// ─────────────────────────────────────────────────────────────────────────────
// VIDYA (Variable Index Dynamic Average) — Tushar Chande, early 1990s. A
// public, well-documented technique. Independent implementation, built from
// the public formula.
//
// VIDYA is an exponential moving average whose smoothing speed is not fixed.
// It is scaled each bar by the Chande Momentum Oscillator (CMO), a measure of
// how one-directional recent price movement has been. In a strongly trending
// window the average speeds up and hugs price. In a choppy, back-and-forth
// window it slows right down and goes nearly flat, rather than whipsawing
// the way a fixed-speed average does.
//
// This version adds an ATR-based confirmation buffer with hysteresis: the
// Bullish/Bearish state only flips when price clears the line by a set
// multiple of ATR, and holds otherwise.
//
// State classification updates ONLY on confirmed bar close, so nothing
// classified here repaints. The VIDYA line itself plots live, same as any
// moving average on any chart — that is normal, expected behaviour.
// ─────────────────────────────────────────────────────────────────────────────
 
 
// ─────────────────────────────────────────────────────────────────────────────
// INPUTS
// ─────────────────────────────────────────────────────────────────────────────
float src = input.source(close, "Source", group="VIDYA")
int length = input.int(14, "Length", minval=5, maxval=100, step=1, group="VIDYA",
     tooltip="Sets the CMO lookback, the base smoothing speed (as an EMA of this length), and the ATR period for the confirmation buffer. Whole-bar steps only.")
float bufferMult = input.float(0.25, "Confirmation Buffer (ATR multiple)", minval=0.0, maxval=2.0, step=0.1, group="VIDYA",
     tooltip="Price must clear the VIDYA line by this many ATRs before the state flips. Inside the buffer, the previous state holds. 0 = flip the instant price crosses the line.")
bool showBuffer = input.bool(true, "Show Buffer Band", group="VIDYA")
 
bool   showTable = input.bool(true, "Show Live/Confirmed Table", group="Table")
string tablePos  = input.string("Top Right", "Table Position", options=["Top Right","Top Left","Bottom Right","Bottom Left"], group="Table")
 
color colBull        = input.color(color.new(color.lime, 60), "Bullish", group="Colours")
color colBear        = input.color(color.new(color.red,  60), "Bearish", group="Colours")
bool  paintMainChart = input.bool(false, "Paint Chart Background", group="Colours",
     tooltip="Tints the chart background by the confirmed Bullish/Bearish state.")
 
 
// ─────────────────────────────────────────────────────────────────────────────
// CMO, TREND INDEX & VIDYA
// ─────────────────────────────────────────────────────────────────────────────
// CMO = (sum of up-moves - sum of down-moves) / (sum of up-moves + sum of
//       down-moves) over `length` bars. Range -1..+1.
// VI  = |CMO|, 0..1. High = strongly one-directional window; low = choppy.
// alpha = 2 / (length + 1)           (standard EMA smoothing constant)
// VIDYA[t] = (alpha * VI) * price[t] + (1 - alpha * VI) * VIDYA[t-1]
float upMove = math.max(src - src[1], 0.0)
float dnMove = math.max(src[1] - src, 0.0)
float sumUp  = math.sum(upMove, length)
float sumDn  = math.sum(dnMove, length)
float denom  = sumUp + sumDn
float cmo    = denom != 0.0 ? (sumUp - sumDn) / denom : 0.0
float vi     = math.abs(cmo)
 
float alpha = 2.0 / (length + 1.0)
float k     = alpha * vi
 
// Seeds on price until the CMO window has enough data, then recurses.
var float vidya = na
vidya := na(vidya[1]) ? src : k * src + (1.0 - k) * vidya[1]
 
// ── Confirmation buffer ───────────────────────────────────────────────────────
float atrVal    = ta.atr(length)
float upperBand = vidya + bufferMult * atrVal
float lowerBand = vidya - bufferMult * atrVal
 
bool ready = bar_index > length
 
// Live state: price clears the upper band => Bullish, clears the lower band
// => Bearish, otherwise holds the previous state (hysteresis).
var int liveSig = 0
if src > upperBand
    liveSig := 1
else if src < lowerBand
    liveSig := 0
 
// ── Confirmed (non-repainting) snapshot — latched once per bar at close ──────
// State codes: 0 = Bearish, 1 = Bullish
var int   currentState = na
var float dispVi       = na
if barstate.isconfirmed
    currentState := ready ? liveSig : na
    dispVi       := ready ? vi : na
 
 
// ─────────────────────────────────────────────────────────────────────────────
// LABELS & COLOURS
// ─────────────────────────────────────────────────────────────────────────────
stateName(s) => s == 1 ? "Bullish" : s == 0 ? "Bearish" : "Warming up…"
stateColor(s) => s == 1 ? colBull : s == 0 ? colBear : na
 
 
// ─────────────────────────────────────────────────────────────────────────────
// STATE STREAK
// ─────────────────────────────────────────────────────────────────────────────
var int lastState = na
var int streak     = 0
if barstate.isconfirmed
    if currentState == lastState
        streak := streak + 1
    else
        streak := 1
        lastState := currentState
 
 
// ─────────────────────────────────────────────────────────────────────────────
// PLOTS
// ─────────────────────────────────────────────────────────────────────────────
color lineCol = ready and not na(currentState) ? (currentState == 1 ? color.new(color.lime, 0) : color.new(color.red, 0)) : color.gray
plot(vidya, "VIDYA", color=lineCol, linewidth=2)
plot(showBuffer ? upperBand : na, "Upper Buffer", color=color.new(color.gray, 70), style=plot.style_circles)
plot(showBuffer ? lowerBand : na, "Lower Buffer", color=color.new(color.gray, 70), style=plot.style_circles)
 
bgcolor(paintMainChart and ready ? stateColor(currentState) : na, title="VIDYA Background")
 
 
// ─────────────────────────────────────────────────────────────────────────────
// TABLE
// ─────────────────────────────────────────────────────────────────────────────
getPosition(p) =>
    p == "Top Left"     ? position.top_left :
     p == "Bottom Right" ? position.bottom_right :
     p == "Bottom Left"  ? position.bottom_left : position.top_right
 
string liveLabel = ready ? (liveSig == 1 ? "BULL" : "BEAR") : "—"
color  liveColor = ready ? (liveSig == 1 ? colBull : colBear) : color.gray
string confLabel = ready and not na(currentState) ? (currentState == 1 ? "BULL" : "BEAR") : "—"
color  confColor = ready and not na(currentState) ? (currentState == 1 ? colBull : colBear) : color.gray
 
if showTable and barstate.islast
    var table t = table.new(getPosition(tablePos), 2, 6,
         bgcolor=color.new(color.black, 15), border_width=1, border_color=color.gray,
         frame_color=color.gray, frame_width=1)
 
    table.cell(t, 0, 0, "VIDYA Adaptive Trend", text_color=color.white, text_size=size.small, bgcolor=color.new(color.black, 0))
    table.cell(t, 1, 0, "", bgcolor=color.new(color.black, 0))
 
    table.cell(t, 0, 1, "Live (intrabar)", text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 1, liveLabel, text_color=color.white, bgcolor=color.new(liveColor, 45), text_halign=text.align_center, text_size=size.small)
 
    table.cell(t, 0, 2, "Confirmed", text_color=color.white, text_size=size.small)
    table.cell(t, 1, 2, confLabel, text_color=color.white, bgcolor=color.new(confColor, 25), text_halign=text.align_center, text_size=size.small)
 
    table.cell(t, 0, 3, "In state for", text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 3, ready and not na(currentState) ? str.tostring(streak) + " bars" : "—", text_color=color.gray, text_halign=text.align_center, text_size=size.small)
 
    table.cell(t, 0, 4, "Adaptivity (VI)", text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 4, not na(dispVi) ? str.tostring(dispVi * 100.0, "#") + "% of base speed" : "—", text_color=color.gray, text_halign=text.align_center, text_size=size.small)
 
    table.cell(t, 0, 5, "⚠ Live can change until close — trade off Confirmed only", text_color=color.white, bgcolor=color.new(color.orange, 65), text_halign=text.align_left, text_size=size.small)
    table.merge_cells(t, 0, 5, 1, 5)
 
 
// ─────────────────────────────────────────────────────────────────────────────
// LIMITATIONS (see published description for the full-length version)
// ─────────────────────────────────────────────────────────────────────────────
// - VIDYA is still a moving average. It lags price by construction; adaptivity
//   reduces whipsaw in chop but does not remove lag.
// - In a long, genuinely one-directional move VIDYA speeds up toward a plain
//   EMA; in a sideways market it goes nearly flat. A flat line is the tool
//   working as designed, not a fault.
// - The confirmation buffer is a trade-off: it cuts false flips but delays
//   genuine ones. 0 = instant flips, higher = fewer but later.
// - The VIDYA line plots live like any moving average. Only the state and
//   colour are held to confirmed bars. That is not repainting.
// - Length drives three things at once (CMO window, base speed, ATR period).
//   That is faithful to Chande's single-window design but means one input
//   changes several behaviours together.
// ─────────────────────────────────────────────────────────────────────────────

← 返回列表