Extreme Volumes
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Scipt Author: © LucasVivien
// Special credits: Matthew J. Slabosz / Zen & The Art of Trading

//@version=4
study("Extreme Volumes")

// Input
LabelLoc = input(title="Label Location"       , type=input.string , defval="Right", options=["Right", "Above", "Below"], tooltip="Label text = How many times the current volume has to be above to selected EMA to be considered extreme. Which corresponds (=) to X % of occurences over chart's total bars count")
MAlenght = input(title="EMA Lenght"           , type=input.integer, defval=200                                         , tooltip="EMA lookback period")
Trigger  = input(title="Extrem Volume Trigger", type=input.float  , defval=5, step=0.1                                 , tooltip="Current volume has to be X times above EMA to be considered Extreme")

// Volume 
Vol = volume
MA = sma(Vol, MAlenght)
ExtVol = Vol / MA
ExtVolAlert = ExtVol >= Trigger

// Counts
var BarCount = 0 
var ExtVolcount = 0
if close > 0
    BarCount := BarCount + 1
if ExtVolAlert == true
    ExtVolcount := ExtVolcount + 1

// Label Location
var LabelStyle = label.style_label_left 
if LabelLoc ==  "Above"
    LabelStyle := label.style_label_down
if LabelLoc ==  "Below"
    LabelStyle := label.style_label_up

// Plots
plot(Vol         , title="Volume"   , color=ExtVolAlert ? color.yellow : close > open ? color.green : color.red, style=plot.style_columns)
plot(MA          , title="MA"       , color=color.blue)
plot(MA * Trigger, title="ExtVol*MA", color=color.yellow)

Lab = label.new(bar_index, MA*Trigger, color=color.yellow, text="Volume " + tostring(Trigger) + "* > EMA" + tostring(MAlenght) + " (=) " + tostring(round(ExtVolcount/BarCount*100, 2)) + "%", style=LabelStyle)
label.delete(Lab[1])

// Alert
alertcondition(ExtVolAlert, title="Extreme Volume Alert", message="Extreme Volume alert for {{ticker}}")