Cumulative Volume Delta (CVD)

Quantum-Edge-Capital · study · 226 行 · 点赞 4 · 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/
// © Quantum-Edge-Capital
//@version=6
indicator('Cumulative Volume Delta (CVD)', overlay = false)
 
//              ╔════════════════════════════════╗              //
//              ║      USER-DEFINED SETTINGS     ║              //
//              ╚════════════════════════════════╝              //
 
var string calculation_settings = '════════ Calculation Parameters ════════'
var string visual_settings = '════════ Visualization Settings ════════'
 
tooltip_auto_timeframe = 'Automatically selects the optimal lower timeframe based on your chart timeframe for more granular CVD calculation. Recommended for most users. When enabled, the indicator intelligently chooses: 1S for <= 1min charts, 5S for <= 5min, 1min for <= 1H, 5min for <= 4H, 15min for <= 1D, 60min for higher timeframes. Disable to manually specify a lower timeframe. If unavailable, falls back to current timeframe data.'
tooltip_manual_timeframe = 'Manually specify the lower timeframe for CVD calculation when Auto-Select is disabled. Common choices: 1min for hourly charts, 5min for 4H charts, 15min for daily charts. If data is unavailable, the indicator will automatically use current timeframe data as fallback.'
tooltip_signal_length = 'Period for the EMA signal line used to identify trend direction. Shorter periods (5-10) make the signal line more responsive to recent CVD changes, providing earlier trend signals but potentially more noise. Longer periods (15-30) create smoother signals with fewer false crossovers but slower response. The signal line helps identify momentum shifts: CVD crossing above signal = bullish, crossing below = bearish.'
tooltip_smoothing_length = 'Period for smoothing the CVD line when using Oscillator (Smooth) display mode. Applies a simple moving average to reduce noise while preserving overall trend structure. Lower values (10-20) maintain more detail and respond faster to changes. Higher values (30-50) create cleaner, smoother curves with less volatility. Only affects Oscillator (Smooth) mode.'
tooltip_rolling_length = 'Window length for Rolling CVD calculation, which shows the cumulative delta over the last N bars rather than from the beginning of chart history. This removes historical bias and focuses on recent volume pressure. Shorter periods (10-20) are more reactive to immediate volume shifts. Longer periods (30-50) provide more stable baseline. Only applies to Oscillator (Rolling) mode.'
tooltip_display_style = 'Choose how to visualize the CVD data:\n\n• Oscillator (Raw): Raw cumulative volume delta from chart start with EMA signal line. Best for identifying overall trend and major reversals.\n\n• Oscillator (Smooth): Smoothed CVD with signal line. Reduces noise for cleaner signals, ideal for trending markets.\n\n• Oscillator (Rolling): CVD calculated over rolling window. Removes historical influence, focuses on recent N bars of volume pressure.\n\n• Histogram: Per-bar volume delta as histogram bars. Shows immediate buying/selling pressure on each bar, not cumulative.\n\n• Candles: CVD as OHLC candlesticks. Reveals intra-bar volume flow dynamics and delta range within each bar.'
tooltip_color_preset = 'Pre-configured color schemes optimized for different chart themes and visual preferences. Each preset maintains strong contrast for clear bullish vs bearish identification. Select Custom to use your own color choices below.'
tooltip_bullish_color = 'Color for bullish conditions (CVD above signal line or positive delta). Represents periods of buying pressure where buy volume exceeds sell volume. This indicates accumulation and potential upward price movement. Typically shown in green/cyan tones to signal positive momentum.'
tooltip_bearish_color = 'Color for bearish conditions (CVD below signal line or negative delta). Represents periods of selling pressure where sell volume exceeds buy volume. This indicates distribution and potential downward price movement. Typically shown in red/orange tones to signal negative momentum.'
tooltip_color_price_bars = 'When enabled, colors the price candles on your main chart based on the current CVD trend. Bullish CVD conditions will color price bars with the bullish color, bearish CVD conditions will use the bearish color. This provides visual confirmation of volume flow directly on the price chart, making it easier to spot divergences between price action and volume delta.'
tooltip_show_label = 'Display an information label showing current chart timeframe, data timeframe source, selected display mode, and current CVD value. Provides quick reference of indicator status and settings without needing to open the settings panel. Shows "LTF unavailable" if lower timeframe data cannot be accessed.'
tooltip_label_position = 'Position of the information label on the indicator pane. Choose from all 9 possible positions to avoid overlapping with other indicators or important data points on your chart.'
tooltip_label_size = 'Text size for the information label. Adjust based on your screen resolution and personal preference for readability.'
 
useAutoTimeframe = input.bool(true, 'Auto-Select Lower Timeframe', group = calculation_settings, tooltip = tooltip_auto_timeframe)
manualTimeframe = input.timeframe('1', 'Manual Lower Timeframe', group = calculation_settings, tooltip = tooltip_manual_timeframe)
displayStyle = input.string('Oscillator (Rolling)', 'Display', options = ['Oscillator (Raw)', 'Oscillator (Smooth)', 'Oscillator (Rolling)', 'Histogram', 'Candles'], group = calculation_settings, tooltip = tooltip_display_style)
signalLength = input.int(12, 'Signal Line Length', minval = 1, group = calculation_settings, tooltip = tooltip_signal_length)
smoothingLength = input.int(20, 'Smoothing Length', minval = 1, group = calculation_settings, tooltip = tooltip_smoothing_length)
rollingLength = input.int(20, 'Rolling Window Length', minval = 1, group = calculation_settings, tooltip = tooltip_rolling_length)
 
colorPreset = input.string('Custom', 'Color Preset', options = ['Classic', 'Aqua', 'Cosmic', 'Ember', 'Neon', 'Custom'], group = visual_settings, tooltip = tooltip_color_preset)
bullishColorInput = input.color(#00ffaa, 'Bullish Color', group = visual_settings, tooltip = tooltip_bullish_color)
bearishColorInput = input.color(#ff0000, 'Bearish Color', group = visual_settings, tooltip = tooltip_bearish_color)
colorPriceBars = input.bool(false, 'Color Price Bars', group = visual_settings, tooltip = tooltip_color_price_bars)
 
[bullishColor, bearishColor] = switch colorPreset
    'Classic' => [#00ff00, #ff0000]
    'Aqua' => [#00bfff, #ff8c00]
    'Cosmic' => [#49ffce, #9932cc]
    'Ember' => [#ff6600, #00cccc]
    'Neon' => [#ffff00, #ff00ff]
    'Custom' => [bullishColorInput, bearishColorInput]
 
showLabel = input.bool(true, 'Show Info Label', group = visual_settings, tooltip = tooltip_show_label)
labelPosition = input.string('Bottom Center', 'Label Position', options = ['Top Left', 'Top Center', 'Top Right', 'Middle Left', 'Middle Center', 'Middle Right', 'Bottom Left', 'Bottom Center', 'Bottom Right'], group = visual_settings, tooltip = tooltip_label_position)
labelSize = input.string('Normal', 'Label Size', options = ['Tiny', 'Small', 'Normal', 'Large'], group = visual_settings, tooltip = tooltip_label_size)
 
//              ╔════════════════════════════════╗              //
//              ║    TIMEFRAME CONFIGURATION     ║              //
//              ╚════════════════════════════════╝              //
 
getAutoTimeframe() =>
    int chartSeconds = timeframe.in_seconds()
    chartSeconds <= 60 ? '1S' : chartSeconds <= 300 ? '5S' : chartSeconds <= 3600 ? '1' : chartSeconds <= 14400 ? '5' : chartSeconds <= 86400 ? '15' : '60'
 
lowerTimeframe = useAutoTimeframe ? getAutoTimeframe() : manualTimeframe
 
//              ╔════════════════════════════════╗              //
//              ║    VOLUME DELTA CALCULATION    ║              //
//              ╚════════════════════════════════╝              //
 
getDelta() =>
    close > open ? volume : close < open ? -volume : 0
 
array<float> deltaValues = request.security_lower_tf(syminfo.tickerid, lowerTimeframe, getDelta())
 
float barDelta = 0.0
if array.size(deltaValues) > 0
    for i = 0 to array.size(deltaValues) - 1 by 1
        barDelta := barDelta + array.get(deltaValues, i)
        barDelta
else
    barDelta := getDelta()
    barDelta
 
//              ╔════════════════════════════════╗              //
//              ║      CVD CANDLE GENERATION     ║              //
//              ╚════════════════════════════════╝              //
 
var float cvdClose = 0.0
float cvdOpen = cvdClose
float cvdHigh = cvdOpen
float cvdLow = cvdOpen
 
if array.size(deltaValues) > 0
    float runningCVD = cvdOpen
    for i = 0 to array.size(deltaValues) - 1 by 1
        runningCVD := runningCVD + array.get(deltaValues, i)
        cvdHigh := math.max(cvdHigh, runningCVD)
        cvdLow := math.min(cvdLow, runningCVD)
        cvdLow
    cvdClose := runningCVD
    cvdClose
else
    cvdClose := cvdOpen + barDelta
    cvdHigh := math.max(cvdOpen, cvdClose)
    cvdLow := math.min(cvdOpen, cvdClose)
    cvdLow
 
//              ╔════════════════════════════════╗              //
//              ║       CVD CALCULATIONS         ║              //
//              ╚════════════════════════════════╝              //
 
rawCVD = ta.cum(barDelta)
smoothCVD = ta.sma(rawCVD, smoothingLength)
rollingCVD = math.sum(barDelta, rollingLength)
 
signalRaw = ta.ema(rawCVD, signalLength)
signalSmooth = ta.ema(smoothCVD, signalLength)
signalRolling = ta.ema(rollingCVD, signalLength)
 
//              ╔════════════════════════════════╗              //
//              ║    SIGNAL & TREND DETECTION    ║              //
//              ╚════════════════════════════════╝              //
 
isBullishRaw = rawCVD > signalRaw
isBearishRaw = rawCVD < signalRaw
isBullishSmooth = smoothCVD > signalSmooth
isBearishSmooth = smoothCVD < signalSmooth
isBullishRolling = rollingCVD > signalRolling
isBearishRolling = rollingCVD < signalRolling
 
isBullishHist = barDelta >= 0
isBearishHist = barDelta < 0
 
isBullishCandle = cvdClose >= cvdOpen
isBearishCandle = cvdClose < cvdOpen
 
bullishCrossRaw = ta.crossover(rawCVD, signalRaw)
bearishCrossRaw = ta.crossunder(rawCVD, signalRaw)
bullishCrossSmooth = ta.crossover(smoothCVD, signalSmooth)
bearishCrossSmooth = ta.crossunder(smoothCVD, signalSmooth)
bullishCrossRolling = ta.crossover(rollingCVD, signalRolling)
bearishCrossRolling = ta.crossunder(rollingCVD, signalRolling)
 
histogramBullishCross = ta.crossover(barDelta, 0)
histogramBearishCross = ta.crossunder(barDelta, 0)
 
//              ╔════════════════════════════════╗              //
//              ║         VISUALIZATION          ║              //
//              ╚════════════════════════════════╝              //
 
isRawMode = displayStyle == 'Oscillator (Raw)'
colorRaw = isBullishRaw ? color.new(bullishColor, 0) : color.new(bearishColor, 0)
fillRaw = isBullishRaw ? color.new(bullishColor, 80) : color.new(bearishColor, 80)
plotRaw = plot(isRawMode ? rawCVD : na, color = colorRaw, linewidth = 3, title = 'Raw CVD')
plotSignalRaw = plot(isRawMode ? signalRaw : na, color = color.new(color.gray, 30), linewidth = 2, title = 'Signal Line')
fill(plotRaw, plotSignalRaw, color = fillRaw, title = 'CVD Fill')
 
isSmoothMode = displayStyle == 'Oscillator (Smooth)'
colorSmooth = isBullishSmooth ? color.new(bullishColor, 0) : color.new(bearishColor, 0)
fillSmooth = isBullishSmooth ? color.new(bullishColor, 80) : color.new(bearishColor, 80)
plotSmooth = plot(isSmoothMode ? smoothCVD : na, color = colorSmooth, linewidth = 3, title = 'Smooth CVD')
plotSignalSmooth = plot(isSmoothMode ? signalSmooth : na, color = color.new(color.gray, 30), linewidth = 2, title = 'Signal Line')
fill(plotSmooth, plotSignalSmooth, color = fillSmooth, title = 'CVD Fill')
 
isRollingMode = displayStyle == 'Oscillator (Rolling)'
colorRolling = isBullishRolling ? color.new(bullishColor, 0) : color.new(bearishColor, 0)
fillRolling = isBullishRolling ? color.new(bullishColor, 80) : color.new(bearishColor, 80)
plotRolling = plot(isRollingMode ? rollingCVD : na, color = colorRolling, linewidth = 3, title = 'Rolling CVD')
plotSignalRolling = plot(isRollingMode ? signalRolling : na, color = color.new(color.gray, 30), linewidth = 2, title = 'Signal Line')
fill(plotRolling, plotSignalRolling, color = fillRolling, title = 'CVD Fill')
 
isHistMode = displayStyle == 'Histogram'
plot(isHistMode ? barDelta : na, style = plot.style_histogram, color = isBullishHist ? bullishColor : bearishColor, linewidth = 4, title = 'Delta Histogram')
 
isCandleMode = displayStyle == 'Candles'
plotcandle(isCandleMode ? cvdOpen : na, isCandleMode ? cvdHigh : na, isCandleMode ? cvdLow : na, isCandleMode ? cvdClose : na, title = 'CVD Candles', color = isBullishCandle ? bullishColor : bearishColor, wickcolor = color.gray, bordercolor = na)
 
hline(isCandleMode ? na : 0, 'Zero Line', color = color.new(color.white, 50), linestyle = hline.style_dashed)
 
cvdBarColor = switch displayStyle
    'Oscillator (Raw)' => isBullishRaw ? bullishColor : bearishColor
    'Oscillator (Smooth)' => isBullishSmooth ? bullishColor : bearishColor
    'Oscillator (Rolling)' => isBullishRolling ? bullishColor : bearishColor
    'Histogram' => isBullishHist ? bullishColor : bearishColor
    'Candles' => isBullishCandle ? bullishColor : bearishColor
    => na
 
barcolor(colorPriceBars ? cvdBarColor : na, title = 'CVD Price Bar Color')
 
var string finalPosition = switch labelPosition
    'Top Left' => position.top_left
    'Top Center' => position.top_center
    'Top Right' => position.top_right
    'Middle Left' => position.middle_left
    'Middle Center' => position.middle_center
    'Middle Right' => position.middle_right
    'Bottom Left' => position.bottom_left
    'Bottom Center' => position.bottom_center
    'Bottom Right' => position.bottom_right
    => position.bottom_center
 
var string finalSize = switch labelSize
    'Tiny' => size.tiny
    'Small' => size.small
    'Large' => size.large
    => size.normal
 
if showLabel and barstate.islast
    var table infoTable = table.new(finalPosition, 1, 1)
    string dataSource = array.size(deltaValues) > 0 ? lowerTimeframe : timeframe.period + ' (LTF unavailable)'
    string cvdValue = displayStyle == 'Candles' ? str.tostring(math.round(cvdClose)) : displayStyle == 'Oscillator (Smooth)' ? str.tostring(math.round(smoothCVD)) : displayStyle == 'Oscillator (Rolling)' ? str.tostring(math.round(rollingCVD)) : displayStyle == 'Histogram' ? str.tostring(math.round(barDelta)) : str.tostring(math.round(rawCVD))
    table.cell(infoTable, 0, 0, 'Chart: ' + timeframe.period + ' | Data: ' + dataSource + ' | ' + displayStyle + ': ' + cvdValue, text_color = color.white, bgcolor = color.new(color.black, 100), text_size = finalSize)
 
//              ╔════════════════════════════════╗              //
//              ║             ALERTS             ║              //
//              ╚════════════════════════════════╝              //
 
alertcondition(bullishCrossRaw and displayStyle == 'Oscillator (Raw)', title = 'Bullish Momentum Shift (Raw)', message = 'CVD: Bullish momentum shift detected on {{exchange}}:{{ticker}} {{interval}} - CVD crossed above signal line')
alertcondition(bearishCrossRaw and displayStyle == 'Oscillator (Raw)', title = 'Bearish Momentum Shift (Raw)', message = 'CVD: Bearish momentum shift detected on {{exchange}}:{{ticker}} {{interval}} - CVD crossed below signal line')
 
alertcondition(bullishCrossSmooth and displayStyle == 'Oscillator (Smooth)', title = 'Bullish Momentum Shift (Smooth)', message = 'CVD: Bullish momentum shift detected on {{exchange}}:{{ticker}} {{interval}} - Smooth CVD crossed above signal line')
alertcondition(bearishCrossSmooth and displayStyle == 'Oscillator (Smooth)', title = 'Bearish Momentum Shift (Smooth)', message = 'CVD: Bearish momentum shift detected on {{exchange}}:{{ticker}} {{interval}} - Smooth CVD crossed below signal line')
 
alertcondition(bullishCrossRolling and displayStyle == 'Oscillator (Rolling)', title = 'Bullish Momentum Shift (Rolling)', message = 'CVD: Bullish momentum shift detected on {{exchange}}:{{ticker}} {{interval}} - Rolling CVD crossed above signal line')
alertcondition(bearishCrossRolling and displayStyle == 'Oscillator (Rolling)', title = 'Bearish Momentum Shift (Rolling)', message = 'CVD: Bearish momentum shift detected on {{exchange}}:{{ticker}} {{interval}} - Rolling CVD crossed below signal line')
 
alertcondition(histogramBullishCross and displayStyle == 'Histogram', title = 'Buying Pressure Detected', message = 'CVD: Buying pressure detected on {{exchange}}:{{ticker}} {{interval}} - Delta turned positive')
alertcondition(histogramBearishCross and displayStyle == 'Histogram', title = 'Selling Pressure Detected', message = 'CVD: Selling pressure detected on {{exchange}}:{{ticker}} {{interval}} - Delta turned negative')
 
alertcondition(isBullishCandle[1] == false and isBullishCandle and displayStyle == 'Candles', title = 'Bullish CVD Candle', message = 'CVD: Bullish CVD candle formed on {{exchange}}:{{ticker}} {{interval}} - CVD close above open')
alertcondition(isBearishCandle[1] == false and isBearishCandle and displayStyle == 'Candles', title = 'Bearish CVD Candle', message = 'CVD: Bearish CVD candle formed on {{exchange}}:{{ticker}} {{interval}} - CVD close below open')

← 返回列表