Klinger Volume Oscillator (KVO) + Signals

TomQuixote · study · 169 行 · 点赞 17 · TradingView 原页

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

Pine Script

//@version=6
// Based on HPotter's Klinger Volume Oscillator (KVO) v1.0, adapted with cross signals
// Threshold and cross-strength filters are normalized to KVO's own standard deviation,
// so they are chart-scale independent and portable across symbols/timeframes.
indicator(title = "Klinger Volume Oscillator (KVO) + Signals", shorttitle = "KVO Signals", format = format.volume, max_labels_count = 500)
 
// ── Inputs ──────────────────────────────────────────────
trigLen   = input.int(13, "Trigger Length", minval = 1)
fastX     = input.int(34, "Fast Length",    minval = 1)
slowX     = input.int(55, "Slow Length",    minval = 1)
 
grpF      = "Signal Filters (units = % of KVO std dev)"
normLen   = input.int(200, "Normalization Lookback (bars)", minval = 20, group = grpF,
     tooltip = "Bars used to measure KVO's standard deviation. Both filters below are expressed as % of this.")
useZero   = input.bool(true, "Use zero-line filter", group = grpF,
     tooltip = "Off = Buy/Sell on any qualifying cross regardless of where it happens.")
threshold = input.int(20, "Zero-Line Distance (%)", minval = -300, maxval = 300, group = grpF,
     tooltip = "Sell: Blue must be above +X% of std dev at the cross. Buy: below -X%.\n0 = just above/below zero.\nNegative = allows crosses slightly on the wrong side (e.g. -10 lets a Buy fire up to 10% ABOVE zero, and a Sell up to 10% below).")
minGap    = input.int(50, "Min Run-Up Gap (%)", minval = 0, group = grpF,
     tooltip = "Blue must have been at least X% of std dev away from Red (on the far side) within the last Run-Up Bars before the cross. Blocks weaving/chop crosses. 0 = off.")
gapBars   = input.int(10, "Run-Up Bars", minval = 2, group = grpF)
minStr    = input.int(0, "Min Cross Strength", minval = 0, group = grpF,
     tooltip = "How fast the Blue-Red gap opens through the cross: change in (KVO - Trigger) over Strength Bars, as % of std dev. Flat chop crosses score low. 0 = off.")
strBars   = input.int(3, "Strength Bars", minval = 1, group = grpF,
     tooltip = "Bars over which the gap change is measured.")
showStr   = input.bool(false, "Show filter values on crosses (for tuning)", group = grpF,
     tooltip = "Labels EVERY Blue/Red cross with each filter's value and ✓/✗: Zero = KVO position as % of std dev (signed), Gap = run-up gap %, Str = cross strength (if on), DC = midline slope. Blue label = passed all cross filters (awaiting confirmation), gray = blocked. Orange = armed cross that failed confirmation, with reason.")
 
lblSizeIn = input.string("Normal", "Diagnostic label size", options = ["Small", "Normal", "Large", "Huge"], group = grpF)
lblSize   = lblSizeIn == "Small" ? size.small : lblSizeIn == "Normal" ? size.normal : lblSizeIn == "Large" ? size.large : size.huge
 
grpC      = "Confirmation (blocks barely-crossed fakeouts)"
confBars  = input.int(1, "Confirmation Bars", minval = 0, maxval = 10, group = grpC,
     tooltip = "Signal fires this many bars AFTER the cross, only if Blue stayed on the new side of Red every bar. 0 = fire on the cross bar.")
minMargin = input.int(10, "Min Close-Through Margin (%)", minval = 0, group = grpC,
     tooltip = "On the signal bar, Blue must be at least X% of std dev past Red (convincing close). 0 = off.")
useCandle = input.bool(true, "Signal candle must close in trade direction", group = grpC,
     tooltip = "Buy: signal bar close > open. Sell: close < open.")
 
grpT      = "Trend Filter (Donchian midline)"
useDC     = input.bool(true, "Use Donchian midline slope", group = grpT,
     tooltip = "Sell only when the midline is flat or falling; Buy only when flat or rising.")
dcLen     = input.int(20, "Donchian Length", minval = 1, group = grpT)
dcLook    = input.int(3, "Slope Lookback (bars)", minval = 1, group = grpT,
     tooltip = "Midline now vs. this many bars ago.")
dcTolTk   = input.int(0, "Flat Tolerance (ticks)", minval = 0, group = grpT,
     tooltip = "A change within this many ticks counts as flat.")
 
grpD        = "Display"
showOnPrice = input.bool(true, "Show signals on price chart",     group = grpD)
showInPane  = input.bool(true, "Show signals in oscillator pane", group = grpD)
 
// ── KVO calculation (unchanged logic) ───────────────────
xTrend   = hlc3 > hlc3[1] ? volume * 100 : -volume * 100
xFast    = ta.ema(xTrend, fastX)
xSlow    = ta.ema(xTrend, slowX)
xKVO     = xFast - xSlow
xTrigger = ta.ema(xKVO, trigLen)
 
// ── Normalization ───────────────────────────────────────
sd       = ta.stdev(xKVO, normLen)
safeSd   = nz(sd) > 0 ? sd : na
thrLevel = threshold / 100.0 * nz(sd)              // threshold in raw KVO units (for plotting)
spread   = xKVO - xTrigger
strength = math.abs(ta.change(spread, strBars)) / safeSd * 100.0
 
// Run-up gap: biggest separation on the far side before the cross (prior bars)
gapAbove = ta.highest(spread, gapBars)[1] / safeSd * 100.0     // Blue above Red (precedes a Sell)
gapBelow = -ta.lowest(spread, gapBars)[1] / safeSd * 100.0     // Blue below Red (precedes a Buy)
 
// Donchian midline slope
dcMid    = math.avg(ta.highest(high, dcLen), ta.lowest(low, dcLen))
dcChg    = dcMid - dcMid[dcLook]
dcTol    = dcTolTk * syminfo.mintick
dcShortOK = not useDC or dcChg <= dcTol
dcLongOK  = not useDC or dcChg >= -dcTol
 
// ── Signals ─────────────────────────────────────────────
crossDn  = ta.crossunder(xKVO, xTrigger) and (not useZero or xKVO >  thrLevel)
crossUp  = ta.crossover(xKVO, xTrigger)  and (not useZero or xKVO < -thrLevel)
strOK    = minStr == 0 or nz(strength) >= minStr
gapSellOK = minGap == 0 or nz(gapAbove) >= minGap
gapBuyOK  = minGap == 0 or nz(gapBelow) >= minGap
armSell  = crossDn and strOK and gapSellOK and dcShortOK and not na(safeSd)
armBuy   = crossUp and strOK and gapBuyOK  and dcLongOK  and not na(safeSd)
 
// Confirmation: wait confBars, Blue must stay on the new side and clear the margin
marginLvl = minMargin / 100.0 * nz(sd)
minSpr    = ta.lowest(spread,  confBars + 1)     // over cross bar .. now
maxSpr    = ta.highest(spread, confBars + 1)
var int buyArmBar  = na
var int sellArmBar = na
if armBuy
    buyArmBar  := bar_index
    sellArmBar := na
if armSell
    sellArmBar := bar_index
    buyArmBar  := na
 
buySig     = false
sellSig    = false
buyFailed  = false
sellFailed = false
if not na(buyArmBar) and bar_index - buyArmBar == confBars
    buySig    := minSpr > 0 and spread >= marginLvl and (not useCandle or close > open)
    buyFailed := not buySig
    buyArmBar := na
if not na(sellArmBar) and bar_index - sellArmBar == confBars
    sellSig    := maxSpr < 0 and spread <= -marginLvl and (not useCandle or close < open)
    sellFailed := not sellSig
    sellArmBar := na
 
// ── Plots ───────────────────────────────────────────────
hline(0, "Zero", color = color.gray, linestyle = hline.style_solid)
plot(useZero ?  thrLevel : na, "Sell Threshold", color = color.new(color.red,   60), style = plot.style_line)
plot(useZero ? -thrLevel : na, "Buy Threshold",  color = color.new(color.green, 60), style = plot.style_line)
 
plot(xKVO,     "KVO",     color = color.blue)
plot(xTrigger, "Trigger", color = color.red)
 
// Markers in the oscillator pane
plotshape(showInPane and buySig,  "Buy (pane)",  shape.triangleup,   location.bottom, color.green, size = size.tiny)
plotshape(showInPane and sellSig, "Sell (pane)", shape.triangledown, location.top,    color.red,   size = size.tiny)
 
// Markers on the price chart
plotshape(showOnPrice and buySig,  "Buy",  shape.labelup,   location.belowbar, color.green, text = "BUY",  textcolor = color.white, size = size.small, force_overlay = true)
plotshape(showOnPrice and sellSig, "Sell", shape.labeldown, location.abovebar, color.red,   text = "SELL", textcolor = color.white, size = size.small, force_overlay = true)
 
// Tuning labels: EVERY Blue/Red cross, showing each filter's value and pass (✓) / fail (✗)
rawUp = ta.crossover(xKVO, xTrigger)
rawDn = ta.crossunder(xKVO, xTrigger)
ck(bool ok) => ok ? "✓" : "✗"
if showStr and (rawUp or rawDn) and not na(safeSd)
    zPct  = xKVO / safeSd * 100.0
    zOK   = rawUp ? crossUp : crossDn
    g     = rawUp ? gapBelow : gapAbove
    gOK   = rawUp ? gapBuyOK : gapSellOK
    dcOK  = rawUp ? dcLongOK : dcShortOK
    armed = rawUp ? armBuy : armSell
    txt   = "Zero " + str.tostring(zPct, "#") + ck(zOK) +
         "\nGap " + str.tostring(g, "#") + ck(gOK) +
         (minStr > 0 ? "\nStr " + str.tostring(strength, "#") + ck(strOK) : "") +
         (useDC ? "\nDC " + ck(dcOK) : "")
    label.new(bar_index, xKVO, txt,
         style     = rawUp ? label.style_label_up : label.style_label_down,
         color     = armed ? color.new(color.blue, 30) : color.new(color.gray, 40),
         textcolor = color.white,
         size      = lblSize)
 
// Tuning: armed crosses that failed confirmation, with the reason
if showStr and (buyFailed or sellFailed)
    m       = (buyFailed ? spread : -spread) / nz(safeSd, 1) * 100.0
    stayed  = buyFailed ? minSpr > 0 : maxSpr < 0
    candOK  = not useCandle or (buyFailed ? close > open : close < open)
    reason  = not stayed ? "recrossed" : m < minMargin ? "margin " + str.tostring(m, "#") : not candOK ? "candle" : ""
    label.new(bar_index, xKVO, "no confirm: " + reason,
         style     = buyFailed ? label.style_label_up : label.style_label_down,
         color     = color.new(color.orange, 20),
         textcolor = color.black,
         size      = lblSize)
 
// Data window readout
plot(strength, "Cross Strength", display = display.data_window)
plot(gapAbove, "Run-Up Gap (above)", display = display.data_window)
plot(gapBelow, "Run-Up Gap (below)", display = display.data_window)
 
// ── Alerts ──────────────────────────────────────────────
alertcondition(buySig,  "KVO Buy",  "KVO Buy: Blue crossed up over Red below -threshold with filters + confirmation")
alertcondition(sellSig, "KVO Sell", "KVO Sell: Blue crossed down over Red above +threshold with filters + confirmation")

← 返回列表