Patterns
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// ©mehtism

//@version=5
indicator('Swing Highs/Lows & Candle Patterns', overlay=true)


len = input.int(9, minval=1, title="Length")
src = input(close, title="Source")
offset = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out = ta.sma(src, len)
plot(out, color=color.blue, title="MA", offset=offset)

ma(source, length, type) =>
    switch type
        "SMA" => ta.sma(source, length)
        "EMA" => ta.ema(source, length)
        "SMMA (RMA)" => ta.rma(source, length)
        "WMA" => ta.wma(source, length)
        "VWMA" => ta.vwma(source, length)

typeMA = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing")
smoothingLength = input.int(title = "Length", defval = 5, minval = 1, maxval = 100, group="Smoothing")

smoothingLine = ma(out, smoothingLength, typeMA)
plot(smoothingLine, title="Smoothing Line", color=#f37f20, offset=offset)







nkj = input(5, title='Length')
Barcolor = input(false, title='Barcolor')

ys1 = (high + low + close * 2) / 4
rk3 = ta.ema(ys1, nkj)
rk4 = ta.stdev(ys1, nkj)
rk5 = (ys1 - rk3) * 100 / rk4
rk6 = ta.ema(rk5, nkj)
up = ta.ema(rk6, nkj)
down = ta.ema(up, nkj)
Oo = up < down ? up : down
Hh = Oo
Ll = up < down ? down : up
Cc = Ll

iff_1 = up > down ? #008000 : #FF0000
b_color = Oo[1] < Oo and Cc < Cc[1] ? #FFFF00 : iff_1
barcolor(Barcolor ? b_color : na)



Buy = ta.crossover(up, down)
Sell = ta.crossunder(up, down)

plotshape(Buy, title='Buy', color=color.new(#008000, 0), style=shape.triangleup, location=location.bottom, text='Buy', size=size.tiny)
plotshape(Sell, title='Sell', color=color.new(#FF0000, 0), style=shape.triangledown, location=location.top, text='Sell', size=size.tiny)

alertcondition(Buy or Sell, title='Buy/Sell Signal', message='Buy/Sell')

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


prd = input.int(defval=5, title='Pivot Period', minval=1, maxval=50)
source = input.string(defval='Close', title='Source for Pivot Points', options=['Close', 'High/Low'])
searchdiv = input.string(defval='Regular', title='Divergence Type', options=['Regular', 'Hidden', 'Regular/Hidden'])
showindis = input.string(defval='Full', title='Show Indicator Names', options=['Full', 'First Letter', 'Don\'t Show'])
showlimit = input.int(1, title='Minimum Number of Divergence', minval=1, maxval=11)
maxpp = input.int(defval=10, title='Maximum Pivot Points to Check', minval=1, maxval=20)
maxbars = input.int(defval=100, title='Maximum Bars to Check', minval=30, maxval=200)
shownum = input(defval=true, title='Show Divergence Number')
showlast = input(defval=false, title='Show Only Last Divergence')
dontconfirm = input(defval=false, title='Don\'t Wait for Confirmation')
showlines = input(defval=true, title='Show Divergence Lines')
showpivot = input(defval=false, title='Show Pivot Points')
calcmacd = input(defval=true, title='MACD')
calcmacda = input(defval=true, title='MACD Histogram')
calcrsi = input(defval=true, title='RSI')
calcstoc = input(defval=true, title='Stochastic')
calccci = input(defval=true, title='CCI')
calcmom = input(defval=true, title='Momentum')
calcobv = input(defval=true, title='OBV')
calcvwmacd = input(true, title='VWmacd')
calccmf = input(true, title='Chaikin Money Flow')
calcmfi = input(true, title='Money Flow Index')
calcext = input(false, title='Check External Indicator')
externalindi = input(defval=close, title='External Indicator')
pos_reg_div_col = input(defval=color.yellow, title='Positive Regular Divergence')
neg_reg_div_col = input(defval=color.navy, title='Negative Regular Divergence')
pos_hid_div_col = input(defval=color.lime, title='Positive Hidden Divergence')
neg_hid_div_col = input(defval=color.red, title='Negative Hidden Divergence')
pos_div_text_col = input(defval=color.black, title='Positive Divergence Text Color')
neg_div_text_col = input(defval=color.white, title='Negative Divergence Text Color')
reg_div_l_style_ = input.string(defval='Solid', title='Regular Divergence Line Style', options=['Solid', 'Dashed', 'Dotted'])
hid_div_l_style_ = input.string(defval='Dashed', title='Hdden Divergence Line Style', options=['Solid', 'Dashed', 'Dotted'])
reg_div_l_width = input.int(defval=2, title='Regular Divergence Line Width', minval=1, maxval=5)
hid_div_l_width = input.int(defval=1, title='Hidden Divergence Line Width', minval=1, maxval=5)
showmas = input.bool(defval=false, title='Show MAs 50 & 200', inline='ma12')
cma1col = input.color(defval=color.lime, title='', inline='ma12')
cma2col = input.color(defval=color.red, title='', inline='ma12')

plot(showmas ? ta.sma(close, 50) : na, color=showmas ? cma1col : na)
plot(showmas ? ta.sma(close, 200) : na, color=showmas ? cma2col : na)

// set line styles
var reg_div_l_style = reg_div_l_style_ == 'Solid' ? line.style_solid : reg_div_l_style_ == 'Dashed' ? line.style_dashed : line.style_dotted
var hid_div_l_style = hid_div_l_style_ == 'Solid' ? line.style_solid : hid_div_l_style_ == 'Dashed' ? line.style_dashed : line.style_dotted


// get indicators
rsi = ta.rsi(close, 14)  // RSI
[macd, signal, deltamacd] = ta.macd(close, 12, 26, 9)  // MACD
moment = ta.mom(close, 10)  // Momentum
cci = ta.cci(close, 10)  // CCI
Obv = ta.obv  // OBV
stk = ta.sma(ta.stoch(close, high, low, 14), 3)  // Stoch
maFast = ta.vwma(close, 12)  // volume weighted macd
maSlow = ta.vwma(close, 26)
vwmacd = maFast - maSlow
Cmfm = (close - low - (high - close)) / (high - low)  // Chaikin money flow
Cmfv = Cmfm * volume
cmf = ta.sma(Cmfv, 21) / ta.sma(volume, 21)
Mfi = ta.mfi(close, 14)  // Moneyt Flow Index

// keep indicators names and colors in arrays
var indicators_name = array.new_string(11)
var div_colors = array.new_color(4)
if barstate.isfirst
    // names
    array.set(indicators_name, 0, showindis == 'Full' ? 'MACD' : 'M')
    array.set(indicators_name, 1, showindis == 'Full' ? 'Hist' : 'H')
    array.set(indicators_name, 2, showindis == 'Full' ? 'RSI' : 'E')
    array.set(indicators_name, 3, showindis == 'Full' ? 'Stoch' : 'S')
    array.set(indicators_name, 4, showindis == 'Full' ? 'CCI' : 'C')
    array.set(indicators_name, 5, showindis == 'Full' ? 'MOM' : 'M')
    array.set(indicators_name, 6, showindis == 'Full' ? 'OBV' : 'O')
    array.set(indicators_name, 7, showindis == 'Full' ? 'VWMACD' : 'V')
    array.set(indicators_name, 8, showindis == 'Full' ? 'CMF' : 'C')
    array.set(indicators_name, 9, showindis == 'Full' ? 'MFI' : 'M')
    array.set(indicators_name, 10, showindis == 'Full' ? 'Extrn' : 'X')
    //colors
    array.set(div_colors, 0, pos_reg_div_col)
    array.set(div_colors, 1, neg_reg_div_col)
    array.set(div_colors, 2, pos_hid_div_col)
    array.set(div_colors, 3, neg_hid_div_col)

// Check if we get new Pivot High Or Pivot Low
float ph = ta.pivothigh(source == 'Close' ? close : high, prd, prd)
float pl = ta.pivotlow(source == 'Close' ? close : low, prd, prd)
plotshape(ph and showpivot, text='H', style=shape.labeldown, color=color.new(color.white, 100), textcolor=color.new(color.red, 0), location=location.abovebar, offset=-prd)
plotshape(pl and showpivot, text='L', style=shape.labelup, color=color.new(color.white, 100), textcolor=color.new(color.lime, 0), location=location.belowbar, offset=-prd)

// keep values and positions of Pivot Highs/Lows in the arrays
var int maxarraysize = 20
var ph_positions = array.new_int(maxarraysize, 0)
var pl_positions = array.new_int(maxarraysize, 0)
var ph_vals = array.new_float(maxarraysize, 0.)
var pl_vals = array.new_float(maxarraysize, 0.)

// add PHs to the array
if ph
    array.unshift(ph_positions, bar_index)
    array.unshift(ph_vals, ph)
    if array.size(ph_positions) > maxarraysize
        array.pop(ph_positions)
        array.pop(ph_vals)

// add PLs to the array
if pl
    array.unshift(pl_positions, bar_index)
    array.unshift(pl_vals, pl)
    if array.size(pl_positions) > maxarraysize
        array.pop(pl_positions)
        array.pop(pl_vals)

// functions to check Regular Divergences and Hidden Divergences

// function to check positive regular or negative hidden divergence
// cond == 1 => positive_regular, cond == 2=> negative_hidden
positive_regular_positive_hidden_divergence(src, cond) =>
    divlen = 0
    prsc = source == 'Close' ? close : low
    // if indicators higher than last value and close price is higher than las close 
    if dontconfirm or src > src[1] or close > close[1]
        startpoint = dontconfirm ? 0 : 1  // don't check last candle
        // we search last 15 PPs
        for x = 0 to maxpp - 1 by 1
            len = bar_index - array.get(pl_positions, x) + prd
            // if we reach non valued array element or arrived 101. or previous bars then we don't search more
            if array.get(pl_positions, x) == 0 or len > maxbars
                break
            if len > 5 and (cond == 1 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(pl_vals, x)) or cond == 2 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(pl_vals, x)))
                slope1 = (src[startpoint] - src[len]) / (len - startpoint)
                virtual_line1 = src[startpoint] - slope1
                slope2 = (close[startpoint] - close[len]) / (len - startpoint)
                virtual_line2 = close[startpoint] - slope2
                arrived = true
                for y = 1 + startpoint to len - 1 by 1
                    if src[y] < virtual_line1 or nz(close[y]) < virtual_line2
                        arrived := false
                        break
                    virtual_line1 -= slope1
                    virtual_line2 -= slope2
                    virtual_line2

                if arrived
                    divlen := len
                    break
    divlen

// function to check negative regular or positive hidden divergence
// cond == 1 => negative_regular, cond == 2=> positive_hidden
negative_regular_negative_hidden_divergence(src, cond) =>
    divlen = 0
    prsc = source == 'Close' ? close : high
    // if indicators higher than last value and close price is higher than las close 
    if dontconfirm or src < src[1] or close < close[1]
        startpoint = dontconfirm ? 0 : 1  // don't check last candle
        // we search last 15 PPs
        for x = 0 to maxpp - 1 by 1
            len = bar_index - array.get(ph_positions, x) + prd
            // if we reach non valued array element or arrived 101. or previous bars then we don't search more
            if array.get(ph_positions, x) == 0 or len > maxbars
                break
            if len > 5 and (cond == 1 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(ph_vals, x)) or cond == 2 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(ph_vals, x)))
                slope1 = (src[startpoint] - src[len]) / (len - startpoint)
                virtual_line1 = src[startpoint] - slope1
                slope2 = (close[startpoint] - nz(close[len])) / (len - startpoint)
                virtual_line2 = close[startpoint] - slope2
                arrived = true
                for y = 1 + startpoint to len - 1 by 1
                    if src[y] > virtual_line1 or nz(close[y]) > virtual_line2
                        arrived := false
                        break
                    virtual_line1 -= slope1
                    virtual_line2 -= slope2
                    virtual_line2

                if arrived
                    divlen := len
                    break
    divlen

// calculate 4 types of divergence if enabled in the options and return divergences in an array
calculate_divs(cond, indicator_1) =>
    divs = array.new_int(4, 0)
    array.set(divs, 0, cond and (searchdiv == 'Regular' or searchdiv == 'Regular/Hidden') ? positive_regular_positive_hidden_divergence(indicator_1, 1) : 0)
    array.set(divs, 1, cond and (searchdiv == 'Regular' or searchdiv == 'Regular/Hidden') ? negative_regular_negative_hidden_divergence(indicator_1, 1) : 0)
    array.set(divs, 2, cond and (searchdiv == 'Hidden' or searchdiv == 'Regular/Hidden') ? positive_regular_positive_hidden_divergence(indicator_1, 2) : 0)
    array.set(divs, 3, cond and (searchdiv == 'Hidden' or searchdiv == 'Regular/Hidden') ? negative_regular_negative_hidden_divergence(indicator_1, 2) : 0)
    divs

// array to keep all divergences
var all_divergences = array.new_int(44)  // 11 indicators * 4 divergence = 44 elements
// set related array elements
array_set_divs(div_pointer, index) =>
    for x = 0 to 3 by 1
        array.set(all_divergences, index * 4 + x, array.get(div_pointer, x))

// set divergences array 
array_set_divs(calculate_divs(calcmacd, macd), 0)
array_set_divs(calculate_divs(calcmacda, deltamacd), 1)
array_set_divs(calculate_divs(calcrsi, rsi), 2)
array_set_divs(calculate_divs(calcstoc, stk), 3)
array_set_divs(calculate_divs(calccci, cci), 4)
array_set_divs(calculate_divs(calcmom, moment), 5)
array_set_divs(calculate_divs(calcobv, Obv), 6)
array_set_divs(calculate_divs(calcvwmacd, vwmacd), 7)
array_set_divs(calculate_divs(calccmf, cmf), 8)
array_set_divs(calculate_divs(calcmfi, Mfi), 9)
array_set_divs(calculate_divs(calcext, externalindi), 10)

// check minimum number of divergence, if less than showlimit then delete all divergence
total_div = 0
for x = 0 to array.size(all_divergences) - 1 by 1
    total_div += math.round(math.sign(array.get(all_divergences, x)))
    total_div

if total_div < showlimit
    array.fill(all_divergences, 0)

// keep line in an array
var pos_div_lines = array.new_line(0)
var neg_div_lines = array.new_line(0)
var pos_div_labels = array.new_label(0)
var neg_div_labels = array.new_label(0)

// remove old lines and labels if showlast option is enabled
delete_old_pos_div_lines() =>
    if array.size(pos_div_lines) > 0
        for j = 0 to array.size(pos_div_lines) - 1 by 1
            line.delete(array.get(pos_div_lines, j))
        array.clear(pos_div_lines)

delete_old_neg_div_lines() =>
    if array.size(neg_div_lines) > 0
        for j = 0 to array.size(neg_div_lines) - 1 by 1
            line.delete(array.get(neg_div_lines, j))
        array.clear(neg_div_lines)

delete_old_pos_div_labels() =>
    if array.size(pos_div_labels) > 0
        for j = 0 to array.size(pos_div_labels) - 1 by 1
            label.delete(array.get(pos_div_labels, j))
        array.clear(pos_div_labels)

delete_old_neg_div_labels() =>
    if array.size(neg_div_labels) > 0
        for j = 0 to array.size(neg_div_labels) - 1 by 1
            label.delete(array.get(neg_div_labels, j))
        array.clear(neg_div_labels)

// delete last creted lines and labels until we met new PH/PV 
delete_last_pos_div_lines_label(n) =>
    if n > 0 and array.size(pos_div_lines) >= n
        asz = array.size(pos_div_lines)
        for j = 1 to n by 1
            line.delete(array.get(pos_div_lines, asz - j))
            array.pop(pos_div_lines)
        if array.size(pos_div_labels) > 0
            label.delete(array.get(pos_div_labels, array.size(pos_div_labels) - 1))
            array.pop(pos_div_labels)

delete_last_neg_div_lines_label(n) =>
    if n > 0 and array.size(neg_div_lines) >= n
        asz = array.size(neg_div_lines)
        for j = 1 to n by 1
            line.delete(array.get(neg_div_lines, asz - j))
            array.pop(neg_div_lines)
        if array.size(neg_div_labels) > 0
            label.delete(array.get(neg_div_labels, array.size(neg_div_labels) - 1))
            array.pop(neg_div_labels)

// variables for Alerts
pos_reg_div_detected = false
neg_reg_div_detected = false
pos_hid_div_detected = false
neg_hid_div_detected = false

// to remove lines/labels until we met new // PH/PL
var last_pos_div_lines = 0
var last_neg_div_lines = 0
var remove_last_pos_divs = false
var remove_last_neg_divs = false
if pl
    remove_last_pos_divs := false
    last_pos_div_lines := 0
    last_pos_div_lines
if ph
    remove_last_neg_divs := false
    last_neg_div_lines := 0
    last_neg_div_lines

// draw divergences lines and labels
divergence_text_top = ''
divergence_text_bottom = ''
distances = array.new_int(0)
dnumdiv_top = 0
dnumdiv_bottom = 0
top_label_col = color.white
bottom_label_col = color.white
old_pos_divs_can_be_removed = true
old_neg_divs_can_be_removed = true
startpoint = dontconfirm ? 0 : 1  // used for don't confirm option

for x = 0 to 10 by 1
    div_type = -1
    for y = 0 to 3 by 1
        if array.get(all_divergences, x * 4 + y) > 0  // any divergence?
            div_type := y
            if y % 2 == 1
                dnumdiv_top += 1
                top_label_col := array.get(div_colors, y)
                top_label_col
            if y % 2 == 0
                dnumdiv_bottom += 1
                bottom_label_col := array.get(div_colors, y)
                bottom_label_col
            if not array.includes(distances, array.get(all_divergences, x * 4 + y))  // line not exist ?
                array.push(distances, array.get(all_divergences, x * 4 + y))
                new_line = showlines ? line.new(x1=bar_index - array.get(all_divergences, x * 4 + y), y1=source == 'Close' ? close[array.get(all_divergences, x * 4 + y)] : y % 2 == 0 ? low[array.get(all_divergences, x * 4 + y)] : high[array.get(all_divergences, x * 4 + y)], x2=bar_index - startpoint, y2=source == 'Close' ? close[startpoint] : y % 2 == 0 ? low[startpoint] : high[startpoint], color=array.get(div_colors, y), style=y < 2 ? reg_div_l_style : hid_div_l_style, width=y < 2 ? reg_div_l_width : hid_div_l_width) : na
                if y % 2 == 0
                    if old_pos_divs_can_be_removed
                        old_pos_divs_can_be_removed := false
                        if not showlast and remove_last_pos_divs
                            delete_last_pos_div_lines_label(last_pos_div_lines)
                            last_pos_div_lines := 0
                            last_pos_div_lines
                        if showlast
                            delete_old_pos_div_lines()
                    array.push(pos_div_lines, new_line)
                    last_pos_div_lines += 1
                    remove_last_pos_divs := true
                    remove_last_pos_divs

                if y % 2 == 1
                    if old_neg_divs_can_be_removed
                        old_neg_divs_can_be_removed := false
                        if not showlast and remove_last_neg_divs
                            delete_last_neg_div_lines_label(last_neg_div_lines)
                            last_neg_div_lines := 0
                            last_neg_div_lines
                        if showlast
                            delete_old_neg_div_lines()
                    array.push(neg_div_lines, new_line)
                    last_neg_div_lines += 1
                    remove_last_neg_divs := true
                    remove_last_neg_divs

            // set variables for alerts
            if y == 0
                pos_reg_div_detected := true
                pos_reg_div_detected
            if y == 1
                neg_reg_div_detected := true
                neg_reg_div_detected
            if y == 2
                pos_hid_div_detected := true
                pos_hid_div_detected
            if y == 3
                neg_hid_div_detected := true
                neg_hid_div_detected
    // get text for labels
    if div_type >= 0
        divergence_text_top += (div_type % 2 == 1 ? showindis != 'Don\'t Show' ? array.get(indicators_name, x) + '\n' : '' : '')
        divergence_text_bottom += (div_type % 2 == 0 ? showindis != 'Don\'t Show' ? array.get(indicators_name, x) + '\n' : '' : '')
        divergence_text_bottom


// draw labels
if showindis != 'Don\'t Show' or shownum
    if shownum and dnumdiv_top > 0
        divergence_text_top += str.tostring(dnumdiv_top)
        divergence_text_top
    if shownum and dnumdiv_bottom > 0
        divergence_text_bottom += str.tostring(dnumdiv_bottom)
        divergence_text_bottom
    if divergence_text_top != ''
        if showlast
            delete_old_neg_div_labels()
        array.push(neg_div_labels, label.new(x=bar_index, y=math.max(high, high[1]), text=divergence_text_top, color=top_label_col, textcolor=neg_div_text_col, style=label.style_label_down))

    if divergence_text_bottom != ''
        if showlast
            delete_old_pos_div_labels()
        array.push(pos_div_labels, label.new(x=bar_index, y=math.min(low, low[1]), text=divergence_text_bottom, color=bottom_label_col, textcolor=pos_div_text_col, style=label.style_label_up))


alertcondition(pos_reg_div_detected or neg_reg_div_detected or pos_hid_div_detected or neg_hid_div_detected, title='all Detected', message='Divergence Detected')






//************************************************************************************************************
// Parameter
//************************************************************************************************************

indiSet = input(false, '═════════ MRC Parameter ════════')
source1 = input(hlc3, title='Price Source')
type = input.string('SuperSmoother', title='Filter Type', options=['SuperSmoother', 'Ehlers EMA', 'Gaussian', 'Butterworth', 'BandStop', 'SMA', 'EMA', 'RMA'])
length = input.int(200, title='Lookback Period', minval=1)
innermult = input.float(1.0, title='Inner Channel Size Multiplier', minval=0.1)
outermult = input.float(2.415, title='Outer Channel Size Multiplier', minval=0.1)

ChartSet = input(false, '═════════ Chart Setting ════════')
drawchannel = input(true, title='Draw Channel')
displayzone = input(true, title='Draw Zone (With Channel)')
zonetransp = input.int(60, title='Zone Transparency', minval=0, maxval=100)
displayline = input(true, title='Display Line Extension')

MTFSet = input(false, '═════════ MTF Setting ════════')
enable_mtf = input(true, title='Enable Multiple TimeFrame Analysis')
mtf_disp_typ = input.string('On Hover', title='MTF Display Type', options=['Always Display', 'On Hover'])
mtf_typ = input.string('Auto', title='Multiple TimeFrame Type', options=['Auto', 'Custom'])
mtf_lvl1 = input.timeframe('D', title='Custom MTF Level 1')
mtf_lvl2 = input.timeframe('W', title='Custom MTF Level 2')

//************************************************************************************************************
// Functions Start {
//************************************************************************************************************
var pi = 2 * math.asin(1)
var mult = pi * innermult
var mult2 = pi * outermult
var gradsize = 0.5
var gradtransp = zonetransp

//-----------------------
// Ehler SwissArmyKnife Function
//-----------------------
SAK_smoothing(_type, _src, _length) =>
    c0 = 1.0
    c1 = 0.0
    b0 = 1.0
    b1 = 0.0
    b2 = 0.0
    a1 = 0.0
    a2 = 0.0
    alpha = 0.0
    beta = 0.0
    gamma = 0.0
    cycle = 2 * pi / _length

    if _type == 'Ehlers EMA'
        alpha := (math.cos(cycle) + math.sin(cycle) - 1) / math.cos(cycle)
        b0 := alpha
        a1 := 1 - alpha
        a1
    if _type == 'Gaussian'
        beta := 2.415 * (1 - math.cos(cycle))
        alpha := -beta + math.sqrt(beta * beta + 2 * beta)
        c0 := alpha * alpha
        a1 := 2 * (1 - alpha)
        a2 := -(1 - alpha) * (1 - alpha)
        a2
    if _type == 'Butterworth'
        beta := 2.415 * (1 - math.cos(cycle))
        alpha := -beta + math.sqrt(beta * beta + 2 * beta)
        c0 := alpha * alpha / 4
        b1 := 2
        b2 := 1
        a1 := 2 * (1 - alpha)
        a2 := -(1 - alpha) * (1 - alpha)
        a2
    if _type == 'BandStop'
        beta := math.cos(cycle)
        gamma := 1 / math.cos(cycle * 2 * 0.1)  // delta default to 0.1. Acceptable delta -- 0.05<d<0.5
        alpha := gamma - math.sqrt(gamma * gamma - 1)
        c0 := (1 + alpha) / 2
        b1 := -2 * beta
        b2 := 1
        a1 := beta * (1 + alpha)
        a2 := -alpha
        a2
    if _type == 'SMA'
        c1 := 1 / _length
        b0 := 1 / _length
        a1 := 1
        a1
    if _type == 'EMA'
        alpha := 2 / (_length + 1)
        b0 := alpha
        a1 := 1 - alpha
        a1
    if _type == 'RMA'
        alpha := 1 / _length
        b0 := alpha
        a1 := 1 - alpha
        a1

    _Input = _src
    _Output = 0.0
    _Output := c0 * (b0 * _Input + b1 * nz(_Input[1]) + b2 * nz(_Input[2])) + a1 * nz(_Output[1]) + a2 * nz(_Output[2]) - c1 * nz(_Input[_length])
    _Output

//-----------------------
// SuperSmoother Function
//-----------------------
supersmoother(_src, _length) =>
    s_a1 = math.exp(-math.sqrt(2) * pi / _length)
    s_b1 = 2 * s_a1 * math.cos(math.sqrt(2) * pi / _length)
    s_c3 = -math.pow(s_a1, 2)
    s_c2 = s_b1
    s_c1 = 1 - s_c2 - s_c3
    ss = 0.0
    ss := s_c1 * _src + s_c2 * nz(ss[1], _src[1]) + s_c3 * nz(ss[2], _src[2])
    ss

//-----------------------
// Auto TimeFrame Function
//-----------------------
// ————— Converts current chart resolution into a float minutes value.
f_resInMinutes() =>
    _resInMinutes = timeframe.multiplier * (timeframe.isseconds ? 1. / 60 : timeframe.isminutes ? 1. : timeframe.isdaily ? 60. * 24 : timeframe.isweekly ? 60. * 24 * 7 : timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
    _resInMinutes

get_tf(_lvl) =>
    y = f_resInMinutes()
    z = timeframe.period
    if mtf_typ == 'Auto'
        if y < 1
            z := _lvl == 1 ? '1' : _lvl == 2 ? '5' : z
            z
        else if y <= 3
            z := _lvl == 1 ? '5' : _lvl == 2 ? '15' : z
            z
        else if y <= 10
            z := _lvl == 1 ? '15' : _lvl == 2 ? '60' : z
            z
        else if y <= 30
            z := _lvl == 1 ? '60' : _lvl == 2 ? '240' : z
            z
        else if y <= 120
            z := _lvl == 1 ? '240' : _lvl == 2 ? 'D' : z
            z
        else if y <= 240
            z := _lvl == 1 ? 'D' : _lvl == 2 ? 'W' : z
            z
        else if y <= 1440
            z := _lvl == 1 ? 'W' : _lvl == 2 ? 'M' : z
            z
        else if y <= 10080
            z := _lvl == 1 ? 'M' : z
            z
        else
            z := z
            z
    else
        z := _lvl == 1 ? mtf_lvl1 : _lvl == 2 ? mtf_lvl2 : z
        z

    z

//-----------------------
// Mean Reversion Channel Function
//-----------------------
get_mrc() =>
    v_condition = 0
    v_meanline = source1
    v_meanrange = supersmoother(ta.tr, length)

    //-- Get Line value
    if type == 'SuperSmoother'
        v_meanline := supersmoother(source1, length)
        v_meanline

    if type != 'SuperSmoother'
        v_meanline := SAK_smoothing(type, source1, length)
        v_meanline

    v_upband1 = v_meanline + v_meanrange * mult
    v_loband1 = v_meanline - v_meanrange * mult
    v_upband2 = v_meanline + v_meanrange * mult2
    v_loband2 = v_meanline - v_meanrange * mult2

    //-- Check Condition
    if close > v_meanline
        v_upband2_1 = v_upband2 + v_meanrange * gradsize * 4
        v_upband2_9 = v_upband2 + v_meanrange * gradsize * -4
        if high >= v_upband2_9 and high < v_upband2
            v_condition := 1
            v_condition
        else if high >= v_upband2 and high < v_upband2_1
            v_condition := 2
            v_condition
        else if high >= v_upband2_1
            v_condition := 3
            v_condition
        else if close <= v_meanline + v_meanrange
            v_condition := 4
            v_condition
        else
            v_condition := 5
            v_condition

    if close < v_meanline
        v_loband2_1 = v_loband2 - v_meanrange * gradsize * 4
        v_loband2_9 = v_loband2 - v_meanrange * gradsize * -4
        if low <= v_loband2_9 and low > v_loband2
            v_condition := -1
            v_condition
        else if low <= v_loband2 and low > v_loband2_1
            v_condition := -2
            v_condition
        else if low <= v_loband2_1
            v_condition := -3
            v_condition
        else if close >= v_meanline + v_meanrange
            v_condition := -4
            v_condition
        else
            v_condition := -5
            v_condition

    [v_meanline, v_meanrange, v_upband1, v_loband1, v_upband2, v_loband2, v_condition]

//-----------------------
// MTF Analysis
//-----------------------

get_stat(_cond) =>
    ret = 'Price at Mean Line\n'
    if _cond == 1
        ret := 'Overbought (Weak)\n'
        ret
    else if _cond == 2
        ret := 'Overbought\n'
        ret
    else if _cond == 3
        ret := 'Overbought (Strong)\n'
        ret
    else if _cond == 4
        ret := 'Price Near Mean\n'
        ret
    else if _cond == 5
        ret := 'Price Above Mean\n'
        ret
    else if _cond == -1
        ret := 'Oversold (Weak)\n'
        ret
    else if _cond == -2
        ret := 'Oversold\n'
        ret
    else if _cond == -3
        ret := 'Oversold (Strong)\n'
        ret
    else if _cond == -4
        ret := 'Price Near Mean\n'
        ret
    else if _cond == -5
        ret := 'Price Below Mean\n'
        ret
    ret

//-----------------------
// Chart Drawing Function
//-----------------------
format_price(x) =>
    y = str.tostring(x, '0.00000')
    if x > 10
        y := str.tostring(x, '0.000')
        y
    if x > 1000
        y := str.tostring(x, '0.00')
        y
    y

f_PriceLine(_ref, linecol) =>
    line.new(x1=bar_index, x2=bar_index - 1, y1=_ref, y2=_ref, extend=extend.left, color=linecol)

f_MTFLabel(_txt, _yloc) =>
    label.new(x=time + math.round(ta.change(time) * 20), y=_yloc, xloc=xloc.bar_time, text=mtf_disp_typ == 'Always Display' ? _txt : 'Check MTF', tooltip=mtf_disp_typ == 'Always Display' ? '' : _txt, color=color.black, textcolor=color.white, size=size.normal, style=mtf_disp_typ == 'On Hover' and displayline ? label.style_label_lower_left : label.style_label_left, textalign=text.align_left)

//} Function End

//************************************************************************************************************
// Calculate Channel
//************************************************************************************************************
var tf_0 = timeframe.period
var tf_1 = get_tf(1)
var tf_2 = get_tf(2)

[meanline, meanrange, upband1, loband1, upband2, loband2, condition] = get_mrc()
[mtf1_meanline, mtf1_meanrange, mtf1_upband1, mtf1_loband1, mtf1_upband2, mtf1_loband2, mtf1_condition] = request.security(syminfo.tickerid, tf_1, get_mrc())
[mtf2_meanline, mtf2_meanrange, mtf2_upband1, mtf2_loband1, mtf2_upband2, mtf2_loband2, mtf2_condition] = request.security(syminfo.tickerid, tf_2, get_mrc())

//************************************************************************************************************
// Drawing Start {
//************************************************************************************************************
float p_meanline = drawchannel ? meanline : na
float p_upband1 = drawchannel ? upband1 : na
float p_loband1 = drawchannel ? loband1 : na
float p_upband2 = drawchannel ? upband2 : na
float p_loband2 = drawchannel ? loband2 : na

z = plot(p_meanline, color=color.new(#FFCD00, 0), style=plot.style_line, title=' Mean', linewidth=2)
x1 = plot(p_upband1, color=color.new(color.green, 50), style=plot.style_circles, title=' R1', linewidth=1)
x2 = plot(p_loband1, color=color.new(color.green, 50), style=plot.style_circles, title=' S1', linewidth=1)
y1 = plot(p_upband2, color=color.new(color.red, 50), style=plot.style_line, title=' R2', linewidth=1)
y2 = plot(p_loband2, color=color.new(color.red, 50), style=plot.style_line, title=' S2', linewidth=1)

//-----------------------
// Draw zone
//-----------------------
//---
var color1 = #FF0000
var color2 = #FF4200
var color3 = #FF5D00
var color4 = #FF7400
var color5 = #FF9700
var color6 = #FFAE00
var color7 = #FFC500
var color8 = #FFCD00
//---
float upband2_1 = drawchannel and displayzone ? upband2 + meanrange * gradsize * 4 : na
float loband2_1 = drawchannel and displayzone ? loband2 - meanrange * gradsize * 4 : na
float upband2_2 = drawchannel and displayzone ? upband2 + meanrange * gradsize * 3 : na
float loband2_2 = drawchannel and displayzone ? loband2 - meanrange * gradsize * 3 : na
float upband2_3 = drawchannel and displayzone ? upband2 + meanrange * gradsize * 2 : na
float loband2_3 = drawchannel and displayzone ? loband2 - meanrange * gradsize * 2 : na
float upband2_4 = drawchannel and displayzone ? upband2 + meanrange * gradsize * 1 : na
float loband2_4 = drawchannel and displayzone ? loband2 - meanrange * gradsize * 1 : na
float upband2_5 = drawchannel and displayzone ? upband2 + meanrange * gradsize * 0 : na
float loband2_5 = drawchannel and displayzone ? loband2 - meanrange * gradsize * 0 : na
float upband2_6 = drawchannel and displayzone ? upband2 + meanrange * gradsize * -1 : na
float loband2_6 = drawchannel and displayzone ? loband2 - meanrange * gradsize * -1 : na
float upband2_7 = drawchannel and displayzone ? upband2 + meanrange * gradsize * -2 : na
float loband2_7 = drawchannel and displayzone ? loband2 - meanrange * gradsize * -2 : na
float upband2_8 = drawchannel and displayzone ? upband2 + meanrange * gradsize * -3 : na
float loband2_8 = drawchannel and displayzone ? loband2 - meanrange * gradsize * -3 : na
float upband2_9 = drawchannel and displayzone ? upband2 + meanrange * gradsize * -4 : na
float loband2_9 = drawchannel and displayzone ? loband2 - meanrange * gradsize * -4 : na

//---
plot_upband2_1 = plot(upband2_1, color=na, display=display.none, transp=100)
plot_loband2_1 = plot(loband2_1, color=na, display=display.none, transp=100)
plot_upband2_2 = plot(upband2_2, color=na, display=display.none, transp=100)
plot_loband2_2 = plot(loband2_2, color=na, display=display.none, transp=100)
plot_upband2_3 = plot(upband2_3, color=na, display=display.none, transp=100)
plot_loband2_3 = plot(loband2_3, color=na, display=display.none, transp=100)
plot_upband2_4 = plot(upband2_4, color=na, display=display.none, transp=100)
plot_loband2_4 = plot(loband2_4, color=na, display=display.none, transp=100)
plot_upband2_5 = plot(upband2_5, color=na, display=display.none, transp=100)
plot_loband2_5 = plot(loband2_5, color=na, display=display.none, transp=100)
plot_upband2_6 = plot(upband2_6, color=na, display=display.none, transp=100)
plot_loband2_6 = plot(loband2_6, color=na, display=display.none, transp=100)
plot_upband2_7 = plot(upband2_7, color=na, display=display.none, transp=100)
plot_loband2_7 = plot(loband2_7, color=na, display=display.none, transp=100)
plot_upband2_8 = plot(upband2_8, color=na, display=display.none, transp=100)
plot_loband2_8 = plot(loband2_8, color=na, display=display.none, transp=100)
plot_upband2_9 = plot(upband2_9, color=na, display=display.none, transp=100)
plot_loband2_9 = plot(loband2_9, color=na, display=display.none, transp=100)

//---
fill(plot_upband2_1, plot_upband2_2, color=color1, transp=gradtransp)
fill(plot_loband2_1, plot_loband2_2, color=color1, transp=gradtransp)
fill(plot_upband2_2, plot_upband2_3, color=color2, transp=gradtransp)
fill(plot_loband2_2, plot_loband2_3, color=color2, transp=gradtransp)
fill(plot_upband2_3, plot_upband2_4, color=color3, transp=gradtransp)
fill(plot_loband2_3, plot_loband2_4, color=color3, transp=gradtransp)
fill(plot_upband2_4, plot_upband2_5, color=color4, transp=gradtransp)
fill(plot_loband2_4, plot_loband2_5, color=color4, transp=gradtransp)
fill(plot_upband2_5, plot_upband2_6, color=color5, transp=gradtransp)
fill(plot_loband2_5, plot_loband2_6, color=color5, transp=gradtransp)
fill(plot_upband2_6, plot_upband2_7, color=color6, transp=gradtransp)
fill(plot_loband2_6, plot_loband2_7, color=color6, transp=gradtransp)
fill(plot_upband2_7, plot_upband2_8, color=color7, transp=gradtransp)
fill(plot_loband2_7, plot_loband2_8, color=color7, transp=gradtransp)
fill(plot_upband2_8, plot_upband2_9, color=color8, transp=gradtransp)
fill(plot_loband2_8, plot_loband2_9, color=color8, transp=gradtransp)

//-----------------------
// Plot Extension
//-----------------------
if displayline and enable_mtf and mtf_disp_typ == 'Always Display'
    displayline := false
    displayline

var line mean = na
line.delete(mean)
mean := displayline ? f_PriceLine(meanline, #FFCD00) : na
var line res1 = na
line.delete(res1)
res1 := displayline ? f_PriceLine(upband1, color.green) : na
var line sup1 = na
line.delete(sup1)
sup1 := displayline ? f_PriceLine(loband1, color.green) : na
var line res2 = na
line.delete(res2)
res2 := displayline ? f_PriceLine(upband2, color.red) : na
var line sup2 = na
line.delete(sup2)
sup2 := displayline ? f_PriceLine(loband2, color.red) : na

//--------------
// Prep MTF Label
//--------------
var brl = '\n--------------------------------------'
dist_0 = 'Distance from Mean: ' + str.tostring((close - meanline) / close * 100, '#.##') + ' %'
dist_1 = 'Distance from Mean: ' + str.tostring((close - mtf1_meanline) / close * 100, '#.##') + ' %'
dist_2 = 'Distance from Mean: ' + str.tostring((close - mtf2_meanline) / close * 100, '#.##') + ' %'

var title = 'Mean Reversion Channel\nMultiple TimeFrame Analysis' + brl
tf0 = '\n\nTimeframe: ' + tf_0 + ' (Current)\n\nStatus: ' + get_stat(condition) + dist_0 + brl

tf1 = not timeframe.ismonthly ? '\n\nTimeframe: ' + tf_1 + '\n\nStatus: ' + get_stat(mtf1_condition) + dist_1 + brl : ''

tf2 = not timeframe.isweekly and not timeframe.ismonthly ? '\n\nTimeframe: ' + tf_2 + '\n\nStatus: ' + get_stat(mtf2_condition) + dist_2 + brl : ''

mtf_lbl = title + tf0 + tf1 + tf2
var label label_mtf = na
label.delete(label_mtf)
label_mtf := enable_mtf ? f_MTFLabel(mtf_lbl, meanline) : na

//} Drawing End



