True Average Period Traded Range
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © priceprophet

//@version=5
indicator("True Average Period Traded Range",shorttitle="Orion:TAPTR",precision=4)

masterTrend = 21

APTRvalue = timeframe.period == "12M" ? 10 :
     timeframe.period == "M" ? 12 :
     timeframe.period == "W" ? 12 :
     timeframe.period == "D" ? 21 :
     timeframe.period == "240" ? 9 :
     timeframe.period == "60" ? 33 :
     timeframe.period == "45" ? 9 :
     timeframe.period == "30" ? 14 :
     timeframe.period == "15" ? 28 :
     timeframe.period == "10" ? 42 :
     timeframe.period == "5" ? 84 :
     timeframe.period == "1" ? 420 : 21

// Bar Type
bt = 0
h0 = math.round(high[0],2)
h1 = math.round(high[1],2)
l0 = math.round(low[0],2)
l1 = math.round(low[1],2)

bt := h0 > h1 and l0 > l1 ? 1 :  // HHHL - Bull
     h0 < h1 and l0 < l1 ? 2 : // LHLL - Bear
     h0 > h1 and l0 < l1 ? 3 : // HHLL - Engulfing
     h0 < h1 and l0 > l1 ? 4 : // LHHL - Adjustment
     h0 == h1 and l0 > l1 ? 5 : // EHHL
     h0 == h1 and l0 < l1 ? 6 : // EHLL
     h0 > h1 and l0 == l1 ? 7 : // HHEL
     h0 < h1 and l0 == l1 ? 8 : bt // LHEL

currentRange = high - low
currentPercent = (currentRange/close[0]) 

true_APTR = ta.sma(currentRange, APTRvalue)

consolidation_APTR = true_APTR * .618

percentOfPrice = (true_APTR/close) 
consolidation_percentOfPrice = percentOfPrice * .618


meanPercentOfPrice = (percentOfPrice + consolidation_percentOfPrice) / 2
APTRMean = math.avg(true_APTR,consolidation_APTR)

masterTrendMA = ta.sma(close,math.round(masterTrend))
masterTrend_TrendDelta = math.abs((close - masterTrendMA))/true_APTR

D1 = bt == 1 ? h0 - h1 : 0
D2 = bt == 2 ? l1 - l0 : 0
D3 = bt == 3 ? (h0 - h1) + (l1 - l0) : 0
D4 = bt == 4 ? (h1 - h0) + (l0 - l1) : 0

D = D1 + D2 + D3 + D4 // open space - not overlapping
AvgD = ta.sma(D,APTRvalue) // average open space
DPoP = (AvgD/close)

column_color = masterTrend_TrendDelta > 4.236 ? color.red : 
     masterTrend_TrendDelta > 2.618 ? color.orange : 
     masterTrend_TrendDelta > 1.618 ? color.yellow :
     masterTrend_TrendDelta > .618 ? color.green: color.blue


plot(currentRange,style=plot.style_columns,color=column_color,title='Current Range')
plot(currentPercent,color=column_color,title='Current Range Percent of Price')

plot(true_APTR,color=color.white,title='APTR')
plot(percentOfPrice,color=color.white,title='APTR Percent of Price')

plot(consolidation_APTR,color=color.orange,title='Consolidation APTR')
plot(consolidation_percentOfPrice,color=color.orange,title='Consolidation Percent of Price')

plot(APTRMean,color=color.blue,title='APTR Mean')
plot(meanPercentOfPrice,color=color.blue,title='Mean Percent of Price')

plot(AvgD,color=color.green,title="Free ATR")
plot(DPoP,color=color.green,title="Free ATR Percent of Price")







