Volatility Pivot Support and Resistance [Loxx]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx

//@version=5
indicator("Volatility Pivot Support and Resistance [Loxx]", 
     shorttitle="VPSR [Loxx]", 
     overlay = true, 
     timeframe="", 
     timeframe_gaps = true)

greencolor = #2DD204
redcolor = #D2042D 

atrrng = input.int(100, "ATR Range", group = "Basic Settings")
inpAtrFactor = input.int(3, "ATR Factor", group = "Basic Settings")
marng = input.int(10, "MA Range", group = "Basic Settings")

colorbars = input.bool(false, "Color bars?", group = "UI Options")

out = math.sum(ta.tr(true), atrrng)/atrrng
atr = 0.
atr := ta.ema(out, marng)
val = close

_deltaStop = atr * inpAtrFactor

while (true) 
    if (close == nz(val[1])) 
        val := nz(val[1]) 
        break 
    if (nz(close[1]) < nz(val[1]) and close < nz(val[1]))
        val := math.min(nz(val[1]), close + _deltaStop) 
        break 
    if (nz(close[1]) > nz(val[1]) and close > nz(val[1]))
        val := math.max(nz(val[1]), close - _deltaStop) 
        break
    if (close  > nz(val[1]))
        val := close - _deltaStop 
    else 
        val := close + _deltaStop
    break

goLong_pre = ta.crossover(val, val[1])
goShort_pre = ta.crossunder(val, val[1])

contSwitch = 0
contSwitch := nz(contSwitch[1])
contSwitch := goLong_pre ? 1 : goShort_pre ? -1 : contSwitch

goLong = goLong_pre and ta.change(contSwitch)
goShort = goShort_pre and ta.change(contSwitch)

plot(val,"Volatility Pivot", color = contSwitch == 1  ? greencolor : redcolor, linewidth = 3)

barcolor(colorbars ? contSwitch == 1 ? greencolor : redcolor : na)




