Trading Range Finder
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jamiedubauskas

//@version=4
study(title = "Trading Range Finder", shorttitle = "RANGE FINDER", overlay = false, max_lines_count = 500)

// ADX components
adxlen = input(14, title="ADX Smoothing")
dilen = input(14, title="DI Length")
dirmov(len) =>
	up = change(high)
	down = -change(low)
	plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
	minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
	truerange = rma(tr, len)
	plus = fixnan(100 * rma(plusDM, len) / truerange)
	minus = fixnan(100 * rma(minusDM, len) / truerange)
	[plus, minus]
adx(dilen, adxlen) =>
	[plus, minus] = dirmov(dilen)
	sum = plus + minus
	adx = 100 * rma(abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
sig = adx(dilen, adxlen)

// range ADX threshold
sidewaysThreshold = input(title = "ADX Sideways Threshold (20 for equities, 25 for crypto)", type = input.integer, minval = 0, defval = 20)

// plotting the ADX indicator and threshold line
plot(sig, color=color.red, title="ADX")
hline(sidewaysThreshold, title = "Sideways Threshold", color = color.new(color.white, 50), linestyle = hline.style_dashed, linewidth = 2)

// boolean expression to see if the ADX is below the sideways threshold
bool isSideways = sig < sidewaysThreshold

bgcolor(isSideways ? color.new(color.gray, 70) : na)

// adding the option to color the bars when in a trading range
useBarColor = input(title = "Color candles?", type = input.bool, defval = false)
bColor = isSideways ? color.new(#Fffb07, 0) : na
barcolor(useBarColor ? bColor : na)



