Order Block v1
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © only_fibonacci

//@version=5
indicator("Order Block", overlay = true)

// Pivot precision
precision = input.int(defval = 5, title = "Precision")
last_how_ob = input.int(defval = 2, title = "How Many Last OB?", minval = 2)
color_of_ob_bullish = input.color(defval = color.rgb(46,204,113,80), title = "Color of OB Bull", group = "BULL")
color_of_ob_bearish = input.color(defval = color.rgb(231, 76, 60,80), title = "Color of OB Bear", group = "BEAR")
show_bull_ob = input.bool(defval = false, title = "SHOW BULL", group = "BULL")
show_bear_ob = input.bool(defval = false, title = "SHOW BEAR", group = "BEAR")


isBody = input.bool(defval =true, title = "Is Body?", group = "TOOL")
extendRight = input.bool(false,title = "Extend Right", group = "TOOL")


h = isBody ? math.max(open,close) : high
l = isBody ? math.min(open,close) : low 


// Conditions for top and bottom
top    = ta.pivothigh(precision,precision)
bottom = ta.pivotlow(precision,precision)


// arrays
tops = array.new_float()
bottoms = array.new_float()

// get Funcstions
getTop(i)=>
    _index = ta.valuewhen(top,bar_index,i) - precision
    _top = high[bar_index - _index]
    array.push(tops,_top)

getBottom(i)=>
    _index = ta.valuewhen(bottom,bar_index,i) - precision
    _bottom = low[bar_index - _index]
    array.push(bottoms,_bottom)



getTop(2)
getTop(1)
getTop(0)

getBottom(2)
getBottom(1)
getBottom(0)




is_bull_ob = array.get(tops,0) > array.get(tops,1) and  array.get(tops,1) > array.get(tops,2) and ta.crossover(high,array.last(tops))
is_bear_ob = array.get(bottoms,0) < array.get(bottoms,1) and  array.get(bottoms,1) < array.get(bottoms,2) and ta.crossunder(low,array.last(bottoms))





index_bull_ob = ta.valuewhen(is_bull_ob,bar_index,0)
index_bear_ob = ta.valuewhen(is_bear_ob,bar_index,0)

redBar = open[1] > close[1] and high[1] < high
greenBar = open[1] < close[1] and low[1] > low

redBarIndex = ta.valuewhen(redBar,bar_index,0)
greenBarIndex = ta.valuewhen(greenBar,bar_index,0)



a_allBoxes = box.all
if array.size(a_allBoxes) > last_how_ob
	for i = 0 to array.size(a_allBoxes) - last_how_ob - 1
		box.delete(array.get(a_allBoxes, i))


if is_bull_ob and show_bull_ob
    box.new(redBarIndex -1,h[bar_index - redBarIndex +1 ],last_bar_index,l[bar_index - redBarIndex +1], bgcolor = color_of_ob_bullish, border_color = color_of_ob_bullish, extend = extendRight ? extend.right : extend.none)


if is_bear_ob and show_bear_ob
    box.new(greenBarIndex -1,h[bar_index - greenBarIndex +1 ],last_bar_index,l[bar_index - greenBarIndex +1],  bgcolor = color_of_ob_bearish, border_color = color_of_ob_bearish, extend = extendRight ? extend.right : extend.none)

