Percentage of direction alternation
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Koalems
// @version=5

indicator(
  title         = "Percentage of direction alternation", 
  shorttitle    = "% of direction alternation",
  overlay       = false
  )

Group0000 = 'Show'
poaShowPoa                            = input.bool(true,                            '% of alternation',                                         group=Group0000)
poaShowPoaWeighted                    = input.bool(true,                            '% of weighted alternation',                                group=Group0000)
poaShowInvered                        = input.bool(false,                           'Invert',                                                   group=Group0000)

Group0010 = 'Settings'
poaMinBarsForCompare    = 2
poaLen                                = input.int(8,                                'Length',                                                   group=Group0010, minval=poaMinBarsForCompare)

poaAlternated           = 0
poaMaxCompares          = poaLen - poaMinBarsForCompare + 1
poaMaxWeight            = poaMaxCompares
poaMaxWeightAlt         = 0
poaWeightedAlternated   = 0

for i = 0 to poaLen - poaMinBarsForCompare
    s1 = math.sign(close[i    ] - open[i    ])
    s2 = math.sign(close[i + 1] - open[i + 1])
    weight           = poaMaxWeight - i
    poaMaxWeightAlt += weight
    if s1 == 1 and s2 == -1 or s1 == -1 and s2 == 1
        poaAlternated         += 1
        poaWeightedAlternated += weight

poaPoa                 = 100 * (poaAlternated         / poaMaxCompares)
poaWeightedAlternated := 100 * (poaWeightedAlternated / poaMaxWeightAlt) 

if poaShowInvered
    poaPoa                  := 100 - poaPoa
    poaWeightedAlternated   := 100 - poaWeightedAlternated

hline(0,   '0%',   #f57c00, linestyle=hline.style_dotted, display = display.none)
hline(50,  '50%',  #f57c00, linestyle=hline.style_dotted)
hline(100, '100%', #f57c00, linestyle=hline.style_dotted)

plot(poaShowPoa         ? poaPoa                 : na, color=color.new(#056656,  0), style=plot.style_area, title="% of alternation")
plot(poaShowPoaWeighted ? poaWeightedAlternated  : na, color=color.new(#0c3299, 30), style=plot.style_area, title="% of weighted alternation")
