Volume Spike



Volume Spike by andrew_LWTco on TradingView.com

//@version=5
indicator("Top 10% Volume Bars with Filled Area", overlay=true)

// Input for lookback period to calculate the top 10% volume threshold
lookback = input.int(100, title="Lookback Period", minval=1)

// Create an array to hold volume values
var float[] volumeArray = array.new_float(lookback, na)

// Default variables for threshold and condition
var float volumeThreshold = na
var bool is_top_volume = false

// Populate the array with initial values during the first bars
if bar_index < lookback
    array.set(volumeArray, bar_index, volume)
else
    array.shift(volumeArray)       // Remove the oldest value
    array.push(volumeArray, volume) // Add the latest value

// Ensure the array has valid values before processing
if bar_index >= lookback - 1
    // Sort the array and determine the 90th percentile
    sortedVolumes = array.copy(volumeArray)
    array.sort(sortedVolumes, order.descending)
    index90Percentile = math.round(array.size(sortedVolumes) * 0.01) - 1
    volumeThreshold := array.get(sortedVolumes, index90Percentile)
    
    // Check if the current volume exceeds or equals the threshold
    is_top_volume := volume >= volumeThreshold

// Apply bar color in the global scope
barcolor(is_top_volume ? color.blue : na)

// Initialize variables to hold high and low levels
var float highLevel = na
var float lowLevel = na

if is_top_volume
    highLevel := high
    lowLevel := low

// Plot high and low levels (for fill)
plot(highLevel, color=color.blue, linewidth=1, title="High Level", style=plot.style_line)
plot(lowLevel, color=color.blue, linewidth=1, title="Low Level", style=plot.style_line)

// Fill between high and low levels
fill(plot(highLevel), plot(lowLevel), color=color.new(color.blue, 90))