← К каталогу
Исходный код · ID 4184

SUVO-Smart Money Concept

indicator suvo-smart money concept for tradingview.pine
Вы автор или правообладатель?

Сообщите нам, если считаете, что материал размещён без разрешения.

Краткий обзор

О программе

"SUVO-Smart Money Concept" — это мультифункциональный индикатор-оверлей для TradingView, написанный на Pine Script v5. Он объединяет несколько аналитических модулей для комплексного анализа рынка в одном инструменте. Индикатор отображается поверх ценового графика и предоставляет визуальные сигналы и уровни для анализа.

Индикатор включает анализ тренда через несколько скользящих средних, зоны реверса на основе регрессионных расчётов, линии ликвидности, паттерны разрыва свечей, супертрейн-логику с сигналами покупки и продажи, анализ волатильности, обнаружение блоков ордеров, анализ рыночной структуры, зоны справедливой стоимости, ключевые уровни по нескольким таймфреймам, сессионные уровни и зоны ликвидности. Поддерживается отображение данных на разных таймфреймах для ряда функций.

Пользователь может настраивать видимость, цвета, таймфреймы и параметры расчёта каждого модуля через обширный набор входных параметров. Индикатор поддерживает систему оповещений TradingView для ключевых событий на графике, таких как обнаружение зон справедливой стоимости и их заполнение.

Настройки программы

НастройкаОписание
showAllEmas HTF TREND DAILY BIAS — Переключатель для отображения или скрытия всех EMA-линий на графике
enableBarColor2 HTF TREND COLOUR — Переключатель для окраски свечей на основе зоны между EMA
bgColorZone Middle Zone Color — Цвет заливки средней зоны между EMA
bgColorZone2 Middle Zone Color — Цвет заливки второй средней зоны между EMA
enableLookback SCALPING SIGNAL — Переключатель для активации расчёта регрессии с учётом окна истории
enableColors REVERSAL BAND — Переключатель для отображения цветовых границ реверс-зоны
h1 Lookback Window — Количество баров, используемых для оценки регрессии
alpha Relative Weighting — Относительное взвешивание временных периодов
x_0 Start Regression at Bar — Индекс бара, с которого начинается регрессия
atr_length ATR Length — Период расчёта среднего истинного диапазона
nearFactor Near ATR Factor — Множитель для расчёта ближней границы
farFactor Far ATR Factor — Множитель для расчёта дальней границы
enable_period Liquidity Trendline — Переключатель для отображения линий ликвидности на основе периода
bull SHOW SNIPER BUY SIGNAL — Переключатель для отображения сигналов покупки
bear SHOW SNIPER SELL SIGNAL — Переключатель для отображения сигналов продажи
showExtremeAndZone SMART TRAIL — Переключатель для отображения трейлинга и зоны супертрейна
showBuySignal Buy Signal+ — Переключатель для отображения сигналов покупки
showSellSignal Sell Signal+ — Переключатель для отображения сигналов продажи
buyColor1 Buy Signal Color — Цвет маркеров сигналов покупки
sellColor1 Sell Signal Color — Цвет маркеров сигналов продажи
labelTextColor Signal Text Color — Цвет текста меток сигналов
enableBarColor SMART TRAIL Bar Color — Переключатель для окраски свечей по супертрейну
cooldownPeriod Candle Cooldown Period — Минимальное количество свечей между повторными сигналами
enable_len VOLITALITY SIGNAL (SUVO) — Переключатель для активации сигнала волатильности
enable_mode Mode 1 — Переключатель режима расчёта волатильности
enable_distance MODE 2 — Переключатель множителя расстояния волатильности
show_retest Retest Signals — Переключатель для отображения сигналов ретеста
enable_bar_color VLITALITY Bar Color — Переключатель для окраски свечей по волатильности
up4 Upward Volatility Color — Цвет для восходящего сигнала волатильности
dn Downward Volatility Color — Цвет для нисходящего сигнала волатильности
show_order_blocks Order Blocks — Переключатель для отображения блоков ордеров
ibull_ob_css Bullish OB Color — Цвет для бычьих блоков ордеров
ibear_ob_css Bearish OB Color — Цвет для медвежьих блоков ордеров
ob_type__ OB Type Filter — Фильтр типа блоков ордеров для отображения
i_tf_ob Timeframe — Таймфрейм для расчёта блоков ордеров
mittigation_filt Mitigation Method — Метод фильтрации заполненных блоков ордеров
overlapping_filt Hide Overlap — Скрытие перекрывающихся блоков ордеров
max_obs Max OBs — Максимальное количество отображаемых блоков ордеров
length_extend_ob Length — Длина продления блоков ордеров
ob_extend Extend — Продление блоков ордеров до текущего бара
text_size_ob Text Size — Размер текста для меток блоков ордеров
ob_text_color_1 OB Text Color — Цвет текста для блоков ордеров
volume_text Volume — Отображение объёма в блоках ордеров
percent_text Percentage — Отображение процента в блоках ордеров
show_line_ob Mid Line — Отображение средней линии блока ордеров
line_style_ob Line Style — Стиль линии средней линии блока ордеров
show_order_blocks_mtf MTF Order Blocks — Переключатель для отображения блоков ордеров на другом таймфрейме
ibull_ob_css_2 MTF Bullish OB Color — Цвет для бычьих блоков ордеров на другом таймфрейме
ibear_ob_css_2 MTF Bearish OB Color — Цвет для медвежьих блоков ордеров на другом таймфрейме
ob_type__mtf MTF OB Type Filter — Фильтр типа блоков ордеров на другом таймфрейме
i_tf_ob_mtf Timeframe — Таймфрейм для расчёта блоков ордеров на другом таймфрейме
mittigation_filt_mtf Mitigation Method — Метод фильтрации заполненных блоков ордеров на другом таймфрейме
overlapping_filt_mtf Hide Overlap — Скрытие перекрывающихся блоков ордеров на другом таймфрейме
max_obs_mtf Max OBs — Максимальное количество блоков ордеров на другом таймфрейме
length_extend_ob_mtf Length — Длина продления блоков ордеров на другом таймфрейме
ob_extend_mtf Extend — Продление блоков ордеров до текущего бара на другом таймфрейме
text_size_ob2 Text Size — Размер текста для меток блоков ордеров на другом таймфрейме
ob_text_color_2 MTF OB Text Color — Цвет текста для блоков ордеров на другом таймфрейме
volume_text_2 Volume — Отображение объёма в блоках ордеров на другом таймфрейме
percent_text_2 Percentage — Отображение процента в блоках ордеров на другом таймфрейме
show_line_ob2 Mid Line — Отображение средней линии блока ордеров на другом таймфрейме
line_style_ob2 Line Style — Стиль линии средней линии блока ордеров на другом таймфрейме
showms Market Structure — Переключатель для отображения рыночной структуры
bosColor1 Bullish BOS Color — Цвет для бычьих BOS/MSS линий
bosColor2 Bearish BOS Color — Цвет для медвежьих BOS/MSS линий
ms_type MS Type Filter — Фильтр типа рыночной структуры для отображения
show_equal_highlow Equal Highs & Lows — Переключатель для отображения равных максимумов и минимумов
eq_bear_color Bearish EQ Color — Цвет для медвежьих уровней равных высоких/низких
eq_bull_color Bullish EQ Color — Цвет для бычьих уровней равных высоких/низких
eq_threshold EQ Threshold — Пороговое значение для определения равных высоких и низких
showSwing Swing Points — Переключатель для отображения точек разворота
swingSize_swing Swing Point Period — Период обнаружения точек разворота
label_sizes_s Label Size — Размер меток точек разворота
swingColor Swing Color — Цвет меток точек разворота
show_fvg Fair Value Gaps (FVG) — Переключатель для отображения зон справедливой стоимости
i_tf Timeframe — Таймфрейм для расчёта зон справедливой стоимости
max_width_fvg Max Width — Максимальная ширина зон справедливой стоимости
remove_small Filter FVG — Фильтрация малых зон справедливой стоимости
mittigation_filt_fvg Mitigation Method — Метод фильтрации заполненных зон справедливой стоимости
fvg_color_fill Fill — Заливка блоков зон справедливой стоимости
fvg_shade_fill Shade — Затенение заполненных зон справедливой стоимости
max_fvg Max FVG — Максимальное количество отображаемых зон справедливой стоимости
length_extend Length — Длина продления зон справедливой стоимости
fvg_extend Extend — Продление зон справедливой стоимости до текущего бара
i_mtfbearishfvgcolor MTF Bearish FVG Color — Цвет для медвежьих зон справедливой стоимости на другом таймфрейме
i_mtfbullishfvgcolor MTF Bullish FVG Color — Цвет для бычьих зон справедливой стоимости на другом таймфрейме
mid_style Style — Стиль средней линии зоны справедливой стоимости
i_midPointColor Mid Point Color — Цвет средней линии зоны справедливой стоимости
fvg_extend_B Extend (Current) — Продление текущей зоны справедливой стоимости
Show_4H_Levels 4H — Переключатель для отображения ключевых уровней 4-часового таймфрейма
Color_4H_Levels 4H Level Color — Цвет уровней 4-часового таймфрейма
Style_4H_Levels 4H Level Style — Стиль линий уровней 4-часового таймфрейма
Text_4H_Levels 4H Shorten — Сокращение текстовых меток уровней 4-часового таймфрейма
Show_Daily_Levels Daily — Переключатель для отображения ключевых уровней дневного таймфрейма
Color_Daily_Levels Daily Level Color — Цвет уровней дневного таймфрейма
Style_Daily_Levels Daily Level Style — Стиль линий уровней дневного таймфрейма
Text_Daily_Levels Daily Shorten — Сокращение текстовых меток уровней дневного таймфрейма
Show_Monday_Levels Monday — Переключатель для отображения ключевых уровней понедельника
Color_Monday_Levels Monday Level Color — Цвет уровней понедельника
Style_Monday_Levels Monday Level Style — Стиль линий уровней понедельника
Получить полный код

Поиск по коду файла

indicator('SUVO-Smart Money Concept', overlay = true, max_bars_back = 5000, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500)

showAllEmas = input.bool(false, title="HTF TREND DAILY BIAS", group="HTF TREND BIAS")

enableBarColor2 = input.bool(false, title="HTF TREND COLOUR", group="HTF TREND Color Settings")

emaLength = 200
emaLength1 = 100
emaLength2 = 150

usedEma = ta.ema(close, emaLength)
usedEma1 = ta.ema(close, emaLength1)
usedEma2 = ta.ema(close, emaLength2)

emaColor = close > usedEma ? #00ff08 : #ff0000
emaColor1 = close > usedEma1 ? #00ff08 : #ff0000
emaColor2 = close > usedEma2 ? #00ff08 : #ff0000

plot(showAllEmas ? usedEma : na, title="200 EMA", style=plot.style_stepline, linewidth=1, color=emaColor)
plot(showAllEmas ? usedEma1 : na, title="100 EMA", style=plot.style_stepline, linewidth=1, color=emaColor1)
plot(showAllEmas ? usedEma2 : na, title="150 EMA", style=plot.style_stepline, linewidth=1, color=emaColor2)

bgColorZone = input.color(color.rgb(255, 5, 5, 79), title="Middle Zone Color", group="EMAs")
bgColorZone2 = input.color(color.rgb(51, 255, 0, 60), title="Middle Zone Color", group="EMAs")
fill(plot1=plot(showAllEmas ? usedEma : na, title="200 EMA Line for Fill", display=display.none),
     plot2=plot(showAllEmas ? usedEma1 : na, title="100 EMA Line for Fill", display=display.none),
     color=bgColorZone)
fill(plot1=plot(showAllEmas ? usedEma1 : na, title="100 EMA Line for Fill", display=display.none),
     plot2=plot(showAllEmas ? usedEma2 : na, title="150 EMA Line for Fill", display=display.none),
     color=bgColorZone2)

barColor = enableBarColor2 and (usedEma > usedEma1 and close > usedEma1 and close < usedEma) ? color.new(#ff0000, 0) : 
           enableBarColor2 and (usedEma1 > usedEma and close > usedEma and close < usedEma1) ? color.new(#00ff00, 0) : na
barcolor(barColor)

emaCrossUp = ta.crossover(usedEma, usedEma1) // 200 EMA crosses above 100 EMA
emaCrossDown = ta.crossunder(usedEma, usedEma1) // 200 EMA crosses below 100 EMA

barColorOnCross = enableBarColor2 and (emaCrossUp or emaCrossDown) ? color.new(#ffa500, 0) : na // Orange when crossing
barcolor(barColorOnCross)

upTrend = close > usedEma and close > usedEma1 and close > usedEma2  // Uptrend condition (all EMAs below price)
downTrend = close < usedEma and close < usedEma1 and close < usedEma2 // Downtrend condition (all EMAs above price)

candleColor = enableBarColor2 and upTrend ? #00ff08 : (enableBarColor2 and downTrend ? #ff0000 : na)  // Green for uptrend, red for downtrend
barcolor(candleColor)

enableLookback = input.bool(false, title = 'SCALPING SIGNAL', group = 'HLW Guys I am SUVO Creator Of this  Indicator Hope You Like it and  Use it and Enjoy with Your Profits')
enableColors = input.bool(false, title = 'REVERSAL BAND') // New input for enabling/disabling all colors
h1 = input.int(14, 'Lookback Window', tooltip = 'The number of bars used for the estimation. Recommended range: 3-50', inline = 'lookback')
alpha = input.float(0.25, 'Relative Weighting', step = 0.25, tooltip = 'Relative weighting of time frames. Recommended range: 0.25-25', inline = 'lookback')
x_0 = input.int(12, 'Start Regression at Bar', tooltip = 'Bar index on which to start regression. Recommended range: 5-25')

atr_length = input.int(7, 'ATR Length', minval = 1, tooltip = 'The number of bars associated with the Average True Range (ATR).')
nearFactor = input.float(1.9, 'Near ATR Factor', minval = 0.5, step = 0.1, tooltip = 'Recommended range: 0.5-2.0')
farFactor = input.float(5, 'Far ATR Factor', minval = 1.0, step = 0.25, tooltip = 'Recommended range: 6.0-8.0')

import jdehorty/KernelFunctions/2 as kernels

getBounds(_atr, _nearFactor, _farFactor, _yhat) =>
    _upper_far = _yhat + _farFactor * _atr
    _upper_near = _yhat + _nearFactor * _atr
    _lower_near = _yhat - _nearFactor * _atr
    _lower_far = _yhat - _farFactor * _atr
    _upper_avg = (_upper_far + _upper_near) / 2
    _lower_avg = (_lower_far + _lower_near) / 2
    [_upper_near, _upper_far, _upper_avg, _lower_near, _lower_far, _lower_avg]

kernel_atr(length, _high, _low, _close) =>
    trueRange = na(_high[1]) ? _high - _low : math.max(math.max(_high - _low, math.abs(_high - _close[1])), math.abs(_low - _close[1]))
    ta.rma(trueRange, length)

yhat_close = enableLookback ? kernels.rationalQuadratic(close, h1, alpha, x_0) : close
yhat_high = enableLookback ? kernels.rationalQuadratic(high, h1, alpha, x_0) : high
yhat_low = enableLookback ? kernels.rationalQuadratic(low, h1, alpha, x_0) : low
yhat = yhat_close
ktr = kernel_atr(atr_length, yhat_high, yhat_low, yhat_close)
[upper_near, upper_far, upper_avg, lower_near, lower_far, lower_avg] = getBounds(ktr, nearFactor, farFactor, yhat_close)

red_far = enableColors ? input.color(#ff040440, title = 'Upper Boundary Color: Far') : na
red_near = enableColors ? input.color(#ff00001a, title = 'Upper Boundary Color: Near') : na
yhat_green = enableColors ? input.color(#00ff0866, title = 'Bullish Estimator Color') : na
yhat_red = enableColors ? input.color(#ff020266, title = 'Bearish Estimator Color') : na
green_near = enableColors ? input.color(color.rgb(0, 255, 8, 90), title = 'Lower Boundary Color: Near') : na
green_far = enableColors ? input.color(#00ff0840, title = 'Lower Boundary Color: Far') : na

p_upper_far = plot(upper_far, color = red_far, title = 'Upper External Heat Zone', linewidth = 1)
p_upper_avg = plot(upper_avg, color = red_near, title = '', linewidth = 1)
p_upper_near = plot(upper_near, color = red_near, title = 'Upper External Heat Zone', linewidth = 1)

p_lower_near = plot(lower_near, color = green_near, title = 'Lower Internal Heat Zone', linewidth = 1)
p_lower_avg = plot(lower_avg, color = green_near, title = '', linewidth = 1)
p_lower_far = plot(lower_far, color = green_far, title = 'Lower Internal Heat Zone', linewidth = 1)

fill(p_upper_far, p_upper_avg, color = red_far, title = 'Upper Boundary: Farmost Region')
fill(p_upper_near, p_upper_avg, color = red_near, title = 'Upper Boundary: Nearmost Region')
fill(p_lower_near, p_lower_avg, color = green_near, title = 'Lower Boundary: Nearmost Region')
fill(p_lower_far, p_lower_avg, color = green_far, title = 'Lower Boundary: Farmost Region')

buyCondition = ta.crossover(close, lower_near)
sellCondition = ta.crossunder(close, upper_near)

validBuyCondition = buyCondition and close < lower_near * 1.05
validSellCondition = sellCondition and close > upper_near * 0.95

plotshape(series = validBuyCondition, location = location.belowbar, size = size.small, color = color.rgb(7, 11, 253), style = shape.labelup, text = '▲', textcolor = #f8fff9)
plotshape(series = validSellCondition, location = location.abovebar, size = size.small, color = #ff0909, style = shape.labeldown, text = '▼', textcolor = #ffffff)

enable_period = input.bool(false, "Liquidity Trendline", tooltip = "Enable or disable period-based calculation", group = "SETTINGS")

len2   = 5        // Period
cup   = color.rgb(0, 255, 21)  // Uptrend color
cdn   = #ff2b00  // Downtrend color
space = 2.0      // Padding
shs   = true     // Show breakouts

ph1 = enable_period ? ta.pivothigh(high, len2, len2) : na
pl1 = enable_period ? ta.pivotlow (low , len2, len2) : na

type store
    float src
    int   n

type bar
    float o = open
    float h = high
    float l = low
    float c = close
    int   n = bar_index
    float v = volume

type draw
    line[] upln
    line[] dnln

var store[] upbin = array.new<store>()
var store[] dnbin = array.new<store>()

var draw d = draw.new(array.new<line>(), array.new<line>())

bar b = bar.new()
atr1   = ta.atr(200)

method slope(line ln) =>
    x = ln.get_x2() - ln.get_x1()
    y = ln.get_y2() - ln.get_y1()
    y / x

vol() =>
    math.min(atr1 * 0.1, close * (0.1 / 100))

var bool broken  = false
color    active  = na
bool plup = false
bool pldn = false

if ph1 
    bool   remove = false
    var bool valid = false

    upbin.unshift(store.new(b.h[len2], b.n[len2]))
    if upbin.size() > 1
        current = upbin.get(0)
        before  = upbin.get(1)
        if current.src < before.src
            if broken
                valid := true

            else
                valid := false
                if upbin.size() > 3
                    pastold = upbin.get(3)
                    pastcur = upbin.get(2)
                    now     = upbin.get(1)
                    late    = upbin.get(0)
                    if now.src < pastcur.src and now.src < pastold.src and late.src < pastcur.src and late.src < pastold.src
                        valid := true

                    else
                        valid := false

                else 
                    valid := false

            if valid

                d.upln.unshift(line.new(x1 = before.n, x2 = current.n, y1 = before.src                , y2 = current.src                , color = cdn))
                d.upln.unshift(line.new(x1 = before.n, x2 = current.n, y1 = before.src - vol() * space, y2 = current.src - vol() * space, color = cdn))

                ln = d.upln.get(1)
                for i = 0 to (b.n - before.n)
                    slope = ln.slope()
                    ln.set_x2(b.n[i])
                    ln.set_y2(ln.get_y2() - slope)
                    if low[i] > ln.get_y2()
                        remove := true
                        break

                if remove
                    d.upln.get(0).delete()
                    d.upln.get(1).delete()
                    d.upln       .clear()
                    upbin        .clear()
                    broken := true

                else
                    d.upln.get(0).delete()
                    d.upln.get(1).delete()   
                    d.upln       .clear ()

                    d.upln.unshift(line.new(x1 = before.n, x2 = current.n, y1 = before.src                , y2 = current.src                , color = cdn))
                    d.upln.unshift(line.new(x1 = before.n, x2 = current.n, y1 = before.src - vol() * space, y2 = current.src - vol() * space, color = cdn))

                    linefill.new(d.upln.get(0), d.upln.get(1), color = color.new(cdn, 75))
                    upbin.clear()
                    broken := false

if d.upln.size() > 1

    btm = d.upln.get(0)
    top = d.upln.get(1)

    if b.l > top.get_y2()
        d.upln.clear()
        broken := true
        upbin.clear()
        plup   := true

    if d.upln.size() > 1

        slup = top.slope()
        sldn = btm.slope()

        top.set_x2(b.n)
        top.set_y2(top.get_y2() + slup)

        btm.set_x2(b.n)
        btm.set_y2(btm.get_y2() + sldn)

if pl1
    bool    remove = false
    var bool valid = false

    dnbin.unshift(store.new(b.l[len2], b.n[len2]))
    if dnbin.size() > 1
        current = dnbin.get(0)
        before  = dnbin.get(1)
        if current.src > before.src
            if broken
                valid := true

            else
                valid := false
                if dnbin.size() > 3
                    pastold = dnbin.get(3)
                    pastcur = dnbin.get(2)
                    now     = dnbin.get(1)
                    late    = dnbin.get(0)

                    if now.src > pastcur.src and now.src > pastold.src and late.src > pastcur.src and late.src > pastold.src
                        valid := true

                    else
                        valid := false

                else 
                    valid := false

            if valid
                d.dnln.unshift(line.new(x1 = before.n, x2 = current.n, y1 = before.src                , y2 = current.src                , color = cup))
                d.dnln.unshift(line.new(x1 = before.n, x2 = current.n, y1 = before.src + vol() * space, y2 = current.src + vol() * space, color = cup))

                ln = d.dnln.get(1)

                for i = 0 to (b.n - before.n)
                    slope = ln.slope()
                    ln.set_x2(b.n[i])
                    ln.set_y2(ln.get_y2() - slope)
                    if high[i] < ln.get_y2()
                        remove := true
                        break

                if remove
                    d.dnln.get(0).delete()
                    d.dnln.get(1).delete()
                    d.dnln       .clear ()
                    dnbin        .clear ()
                    broken := true

                else
                    d.dnln.get(0).delete()
                    d.dnln.get(1).delete()   
                    d.dnln       .clear ()

                    d.dnln.unshift(line.new(x1 = before.n, x2 = current.n, y1 = before.src, y2 = current.src, color = cup))
                    d.dnln.unshift(line.new(x1 = before.n, x2 = current.n, y1 = before.src + vol() * space, y2 = current.src + vol() * space, color = cup))

                    linefill.new(d.dnln.get(0), d.dnln.get(1), color = color.new(cup, 75))
                    dnbin.clear()
                    broken := false

if d.dnln.size() > 1

    btm = d.dnln.get(0)
    top = d.dnln.get(1)

    if b.h < btm.get_y2()
        d.dnln.clear()
        broken := true
        dnbin.clear()
        pldn   := true

    if d.dnln.size() > 1

        slup = top.slope()
        sldn = btm.slope()

        top.set_x2(b.n)
        top.set_y2(top.get_y2() + slup)

        btm.set_x2(b.n)
        btm.set_y2(btm.get_y2() + sldn)

plotshape(pldn and shs ? b.h[1] : na, "Breaking Down", shape.triangledown, location = location.abovebar, color = cdn  , offset = -1, size = size.tiny)
plotshape(plup and shs ? b.l[1] : na, "Breaking Up"  , shape.triangleup  , location = location.belowbar, color = cup, offset = -1, size = size.tiny)

len1 = 5 // Sensitivity (Hard-coded)
bull = input.bool(false, 'SHOW SNIPER BUY SIGNAL ')
bear = input.bool(false, 'SHOW SNIPER SELL SIGNAL')

iVal = 'None'
percent = 30
auto = true
mlt = 50
res = 'D' // Default timeframe
prem = false

dSwingLine = true
dOpposLine = true
dSFP_Line = true
dSFP_Label = true
colBl = color.rgb(0, 255, 4)
colBr = color.rgb(255, 0, 0)
colBl2 = color.rgb(17, 255, 0)
colBr2 = color.new(color.rgb(255, 0, 234), 0)

type piv
	float swing_prc // price
	int swing_bix // bar_index
	float oppos_prc // price
	int oppos_bix // bar_index
	bool active
	bool confirmed
	line swing_line
	line oppos_line
	line wicky_line
	label wicky_label

type swing
	int bix
	float prc

n1 = bar_index
INV = color(na)
FGc = chart.fg_color

var swing swingH = swing.new()
var swing swingL = swing.new()
var piv pivH = piv.new()
var piv pivL = piv.new()

validate = iVal != 'None'
valHigher = iVal == 'Volume outside swing > Threshold'
valLower = iVal == 'Volume outside swing < Threshold'

method n(float piv) =>
    bool out = not na(piv)
    out

tfS = timeframe.in_seconds(res)
tfC = timeframe.in_seconds(timeframe.period)
rs = auto ? tfC / mlt : tfS
if not validate
    res := timeframe.period
    res
else
    rs := prem ? rs : math.max(60, rs)
    res := timeframe.from_seconds(math.min(tfC, rs))
    res

ph = ta.pivothigh(len1, 1)
pl = ta.pivotlow(len1, 1)

[ltf_close, ltf_volume] = request.security_lower_tf(syminfo.tickerid, res, [close, volume])

ltf_size = ltf_close.size()

if validate
    if ltf_size > 0 and ltf_size[1] == 0
        line.new(n1, close, n1, close + syminfo.mintick, color = color.silver, style = line.style_dotted, extend = extend.both)

bearishSFP = false
if bear

    if ph.n()
        swingH.bix := n1 - 1
        swingH.prc := ph
        swingH.prc

    sw = swingH.prc
    bx = swingH.bix
    if high > sw and open < sw and close < sw
        valid = true
        if validate
            if ltf_close.size() > 0
                outsideVolume = 0.
                totalVolume = ltf_volume.sum()
                for j = 0 to ltf_close.size() - 1 by 1
                    if ltf_close.get(j) > sw
                        outsideVolume := outsideVolume + ltf_volume.get(j)
                        outsideVolume
                if valHigher ? 100 / totalVolume * outsideVolume < percent : 100 / totalVolume * outsideVolume > percent
                    valid := false
                    valid

        if valid

            opposL = sw
            opposB = n1

            for i = 1 to n1 - bx - 1 by 1
                if low[i] < opposL
                    opposL := low[i]
                    opposB := n1 - i
                    opposB

            if not pivH.confirmed
                pivH.swing_line.delete()
                pivH.oppos_line.delete()
                pivH.wicky_line.delete()
                pivH.wicky_label.delete()

            pivH := piv.new(sw, bx, opposL, opposB, true, false)

            if dSwingLine
                pivH.swing_line := line.new(bx, sw, n1, sw, color = colBr)
                pivH.swing_line
            if dOpposLine
                pivH.oppos_line := line.new(opposB, opposL, n1, opposL, color = colBr, style = line.style_dotted)
                pivH.oppos_line
            if dSFP_Line
                pivH.wicky_line := line.new(n1, high, n1, sw, color = colBr2, width = 3)
                pivH.wicky_line
            if dSFP_Label
                pivH.wicky_label := label.new(n1, high, style = label.style_label_down, text = '🆂🅴🅻', textcolor = colBr, color = INV, size = size.normal)
                pivH.wicky_label

    if pivH.active and not pivH.confirmed

        pivH.swing_line.set_x2(n1)
        pivH.oppos_line.set_x2(n1)

        if close < pivH.oppos_prc
            pivH.confirmed := true
            bearishSFP := true

            if pivH.wicky_label.get_x() == n1
                pivH.wicky_label.set_text('\n▼')
            else
                label.new(n1, high, style = label.style_label_down, text = '▼', textcolor = colBr, color = INV, size = size.normal)

    if n1 - pivH.swing_bix > 500 or close > pivH.swing_prc
        pivH.active := false
        if not pivH.confirmed
            pivH.swing_line.delete()
            pivH.oppos_line.delete()
            pivH.wicky_line.delete()
            pivH.wicky_label.delete()

bullishSFP = false
if bull

    if pl.n()
        swingL.bix := n1 - 1
        swingL.prc := pl
        swingL.prc

    sw = swingL.prc
    bx = swingL.bix
    if low < sw and open > sw and close > sw
        valid = true
        if validate
            if ltf_close.size() > 0
                outsideVolume = 0.
                totalVolume = ltf_volume.sum()
                for j = 0 to ltf_close.size() - 1 by 1
                    if ltf_close.get(j) < sw
                        outsideVolume := outsideVolume + ltf_volume.get(j)
                        outsideVolume
                if valHigher ? 100 / totalVolume * outsideVolume < percent : 100 / totalVolume * outsideVolume > percent
                    valid := false
                    valid
        if valid

            opposH = sw
            opposB = n1

            for i = 1 to n1 - bx - 1 by 1
                if high[i] > opposH
                    opposH := high[i]
                    opposB := n1 - i
                    opposB

            if not pivL.confirmed
                pivL.swing_line.delete()
                pivL.oppos_line.delete()
                pivL.wicky_line.delete()
                pivL.wicky_label.delete()

            pivL := piv.new(sw, bx, opposH, opposB, true, false)

            if dSwingLine
                pivL.swing_line := line.new(bx, sw, n1, sw, color = colBl)
                pivL.swing_line
            if dOpposLine
                pivL.oppos_line := line.new(opposB, opposH, n1, opposH, color = colBl, style = line.style_dotted)
                pivL.oppos_line
            if dSFP_Line
                pivL.wicky_line := line.new(n1, low, n1, sw, color = colBl2, width = 3)
                pivL.wicky_line
            if dSFP_Label
                pivL.wicky_label := label.new(n1, low, style = label.style_label_up, text = '🅱🆄🆈', textcolor = colBl, color = INV, size = size.normal)
                pivL.wicky_label

    if pivL.active and not pivL.confirmed

        pivL.swing_line.set_x2(n1)
        pivL.oppos_line.set_x2(n1)

        if close > pivL.oppos_prc
            pivL.confirmed := true
            bullishSFP := true

            if pivL.wicky_label.get_x() == n1
                pivL.wicky_label.set_text('▲\n')
            else
                label.new(n1, low, style = label.style_label_up, text = '▲', textcolor = colBl, color = INV, size = size.normal)

    if n1 - pivL.swing_bix > 500 or close < pivL.swing_prc
        pivL.active := false
        if not pivL.confirmed
            pivL.swing_line.delete()
            pivL.oppos_line.delete()
            pivL.wicky_line.delete()
            pivL.wicky_label.delete()

showExtremeAndZone = input.bool(false, 'SMART TRAIL', group = 'SMART TRAIL ')
showBuySignal = input.bool(false, 'Buy Signal+', group = 'Signals')
showSellSignal = input.bool(false, 'Sell Signal+', group = 'Signals')
buyColor1 = input.color(#0bf113, 'Buy Signal Color', group = 'Signals')
sellColor1 = input.color(#f30505, 'Sell Signal Color', group = 'Signals')
labelTextColor = input.color(color.white, 'Signal Text Color', group = 'Signals')
enableBarColor = input.bool(false, 'SMART TRAIL Bar Color', group = 'Bar Colors')

cooldownPeriod = input.int(20, 'Candle Cooldown Period ', group = 'Other')

inp1 = 3.00
inp2 = 34
inp3 = 1.00

atrs = ta.atr(100)
[supertrend, direction] = ta.supertrend(math.round(math.avg(7, inp1)), inp2 * 2)
hullup = ta.hma(high, math.round(math.avg(21, inp2))) + atrs * math.round(inp1 / 2.5)
hulldown = ta.hma(low, math.round(math.avg(21, inp2))) - atrs * math.round(inp1 / 2.5)
hline = ta.highest(close, inp2) + atrs
lline = ta.lowest(close, inp2) + atrs
supert = 0.00
supert := if close > supertrend
    math.avg(supertrend, supertrend, supertrend, hulldown, lline)
else if close < supertrend
    math.avg(supertrend, supertrend, supertrend, hullup, hline)
supert2 = 0.00
supert2 := if close > supert
    supert + atrs * inp3
else if close < supert
    supert - atrs * inp3

tool = direction > 0 or direction < 0
toolx = true // Keep this for plotting logic

tool12 = plot(toolx and showExtremeAndZone ? supert : na, ' ', color = close > supert ? color.rgb(41, 98, 255, 1) : color.rgb(255, 0, 0), style = plot.style_linebr)
tool2 = plot(toolx and showExtremeAndZone ? supert2 : na, ' ', color = color.new(color.gray, 100), display = display.none, editable = false, style = plot.style_linebr)
fill(tool12, tool2, color = close > supert ? #2962ff34 : color.rgb(255, 2, 2, 76), fillgaps = false)

mid = ta.ema(close, 21)
dist = (supert - mid) * inp3
tpl = ta.sma(mid - dist, 2)

var int lastSignalBar = na

buySignal1 = close < supert2 and close > supert and (na(lastSignalBar) or bar_index - lastSignalBar > cooldownPeriod)
sellSignal1 = close > supert2 and close < supert and (na(lastSignalBar) or bar_index - lastSignalBar > cooldownPeriod)

if buySignal1 or sellSignal1
    lastSignalBar := bar_index
    lastSignalBar

buySignalPlot = showBuySignal and buySignal1
sellSignalPlot = showSellSignal and sellSignal1

plotshape(buySignalPlot, style = shape.labelup, location = location.belowbar, color = buyColor1, size = size.small, title = 'Buy Signal', text = '▲+', textcolor = labelTextColor)
plotshape(sellSignalPlot, style = shape.labeldown, location = location.abovebar, color = sellColor1, size = size.small, title = 'Sell Signal', text = '▼+', textcolor = labelTextColor)

var color barColor1 = na
var color lastExtremeColor = na

currentExtremeColor = close > supert ? color.blue : color.red

if currentExtremeColor != lastExtremeColor
    barColor1 := currentExtremeColor == color.blue ? #00ff0d : color.rgb(255, 0, 0)
    barColor1

lastExtremeColor := currentExtremeColor

if enableBarColor
    barColor1 := barColor1
    barColor1
else
    barColor1 := na
    barColor1

barcolor(enableBarColor ? barColor1 : na)

alertb = close < supert2 and close > supert
alerts = close > supert2 and close < supert
tchup = direction < 0 and direction[3] > 0
tchdown = direction > 0 and direction[3] < 0

chosen = alertb or alerts // Simplified alert condition

alertcondition(chosen, 'Smooth Trail Alert', 'The price of {{ticker}} is in the area of SuperTrend')

bool enable_len = input.bool(false, 'VOLITALITY SIGNAL (SUVO)', group = 'Volatility SIGNAL ') // Toggle for Length input
int len = enable_len ? input.int(5, 'Length', minval = 5) : na

bool enable_mode = input.bool(true, 'Mode 1') // Toggle for Mode input
string mode = enable_mode ? input.string('MODE', 'Type', ['AVG', 'MEADIAN', 'MODE']) : 'AVG'

bool enable_distance = input.bool(true, 'MODE 2') // Toggle for Distance multiplier
float distance = enable_distance ? input.float(1, step = 0.1) : 0

bool show_retest = input.bool(false, 'Retest Signals')
bool enable_bar_color = input.bool(false, 'VLITALITY Bar Color') // Toggle bar coloring

color up4 = input.color(color.rgb(0, 255, 13), group = 'Color')
color dn = input.color(#ff0000, group = 'Color')

gaussian_filter(src, length, sigma) =>
    var array<float> weights = array.new_float(100)
    float total = 0.0
    float pi = math.pi
    for i = 0 to length - 1 by 1
        float weight = math.exp(-0.5 * math.pow((i - length / 2) / sigma, 2.0)) / math.sqrt(sigma * 2.0 * pi)
        weights.set(i, weight)
        total := total + weight
        total
    for i = 0 to length - 1 by 1
        weights.set(i, weights.get(i) / total)
    float sum = 0.0
    for i = 0 to length - 1 by 1
        sum := sum + src[i] * weights.get(i)
        sum
    sum

multi_trend4(src, period) =>
    array<float> g_value = array.new<float>()
    float volatility = ta.sma(high - low, 100)
    var float lower_band = 0.0
    var float up4per_band = 0.0
    var float trend4_line = 0.0
    var bool trend4 = false
    for step = 0 to 20 by 1
        float gaussian_filter = gaussian_filter(src, period + step, 10)
        g_value.push(gaussian_filter)
    float coeff = 0.05
    float score = 0.0
    for i = 0 to g_value.size() - 1 by 1
        float g_f = g_value.get(i)
        if g_f > g_value.first()
            score := score + coeff
            score
    color color = score > 0.5 ? color.from_gradient(score, 0.5, 1, na, dn) : color.from_gradient(score, 0, 0.5, up4, na)
    float value = switch mode
        'AVG' => g_value.avg()
        'MEADIAN' => g_value.median()
        'MODE' => g_value.mode()
    lower_band := value - volatility * distance
    up4per_band := value + volatility * distance
    if ta.crossover(close, up4per_band)
        trend4 := true
        trend4
    if ta.crossunder(close, lower_band)
        trend4 := false
        trend4
    trend4_line := trend4 ? lower_band : not trend4 ? up4per_band : na
    [score, value, color, trend4_line, trend4]

[score, avg, color, trend4_line, trend4] = multi_trend4(close, len)

p2 = plot(avg, color = color, linewidth = math.max(1, 0))
p1 = plot(ta.change(trend4) ? na : trend4_line, color = close > trend4_line ? up4 : dn, linewidth = math.max(1, 0), style = plot.style_linebr)
plot(trend4_line, color = close > trend4_line ? up4 : dn, linewidth = math.max(1, 0), style = plot.style_linebr)

barcolor(enable_bar_color ? trend4 ? up4 : dn : na)

if ta.crossunder(close, trend4_line)
    label.new(bar_index, trend4_line, score < 0.5 ? '▼+' : '▼', color = dn, textcolor = chart.fg_color, style = label.style_label_lower_right, size = score < 0.5 ? size.normal : size.small)

if ta.crossover(close, trend4_line)
    label.new(bar_index, trend4_line, score > 0.5 ? '▲+' : '▲', color = up4, textcolor = chart.bg_color, style = label.style_label_upper_right, size = score > 0.5 ? size.normal : size.small)

color trend4_color = trend4 ? color.new(up4, 80) : color.new(dn, 80)
fill(p1, p2, trend4_line, avg, trend4_color, na)

if show_retest
    if ta.crossunder(high, avg) and not trend4
        label.new(bar_index[1], high[1], '▼', color = color(na), style = label.style_label_down, textcolor = chart.fg_color, size = size.small)
    if ta.crossover(close, avg) and trend4
        label.new(bar_index[1], low[1], '▲', color = color(na), style = label.style_label_up, textcolor = chart.fg_color, size = size.small)

float score_up4 = (score - 1) * -1
float score_dn = 1 - score_up4
if barstate.islast
    table trend4_strength_up4 = table.new(position.bottom_center, 100, 100)
    table trend4_strength_dn = table.new(position.top_center, 100, 100)
    for i = 0 to score_up4 * 20 by 1
        trend4_strength_up4.cell(0 + i, 0, bgcolor = color.new(up4, 100 - i * 5), text = i == 0 ? '|' : '', text_color = color.gray)
        if i == score_up4 * 20
            trend4_strength_up4.cell(0 + i, 0, text = str.tostring(score_up4 * 100, format.percent) + ' ▲', text_color = chart.fg_color, height = 2)
    for i = 0 to score_dn * 20 by 1
        trend4_strength_dn.cell(0 + i, 0, bgcolor = color.new(dn, 100 - i * 5), text = i == 0 ? '|' : '', text_color = color.gray)
        if i == score_dn * 20
            trend4_strength_dn.cell(0 + i, 0, text = str.tostring(score_dn * 100, format.percent) + ' ▼', text_color = chart.fg_color, height = 2)

show_order_blocks = input.bool(true, 'Order Blocks', group = 'Order Blocks', inline = 'ob1')
ibull_ob_css = input.color(#01ff3833, '', inline = 'ob1', group = 'Order Blocks')
ibear_ob_css = input.color(#ff000033, '', inline = 'ob1', group = 'Order Blocks')
ob_type__ = input.string('All', '', options = ['All', 'Internal', 'External'], group = 'Order Blocks', inline = 'ob1')
i_tf_ob = input.timeframe('', 'Timeframe', group = 'Order Blocks', inline = 'ob2')
mittigation_filt = input.string('Average', 'Mitigation Method', options = ['Touch', 'Wicks', 'Close', 'Average'], group = 'Order Blocks', inline = 'ob3')
overlapping_filt = input(true, 'Hide Overlap', inline = 'ob3', group = 'Order Blocks')
max_obs = input.int(10, 'Max OBs', minval = 3, group = 'Order Blocks', inline = 'ob4')
length_extend_ob = input.int(defval = 20, title = 'Length', minval = 0, maxval = 500, group = 'Order Blocks', inline = 'ob4')
ob_extend = input.bool(false, 'Extend', group = 'Order Blocks', inline = 'ob4')

text_size_ob = input.string('Medium', options = ['Small', 'Medium', 'Large'], title = 'Text Size', inline = 'ob1_t', group = 'Order Blocks')
text_size_ob_ = text_size_ob == 'Medium' ? size.tiny : text_size_ob == 'Medium' ? size.small : text_size_ob == 'Large' ? size.normal : text_size_ob == 'Medium2' ? size.normal : text_size_ob == 'Large2' ? size.large : size.huge
ob_text_color_1 = input.color(color.rgb(255, 255, 255), '', inline = 'ob1_t', group = 'Order Blocks')
volume_text = input.bool(true, 'Volume', group = 'Order Blocks', inline = 'ob1_t')
percent_text = input.bool(true, 'Percentage', group = 'Order Blocks', inline = 'ob1_t')

show_line_ob = input.string('Off', title = 'Mid Line', options = ['On', 'Off'], group = 'Order Blocks', inline = 'ob1_l')
show_line_ob_1 = show_line_ob == 'On' ? true : false
line_style_ob = input.string('Solid', title = 'Line Style', options = ['Solid', 'Dashed', 'Dotted'], group = 'Order Blocks', inline = 'ob1_l')
line_style_ob_1 = line_style_ob == 'Solid' ? line.style_solid : line_style_ob == 'Dashed' ? line.style_dashed : line.style_dotted

show_order_blocks_mtf = input.bool(false, 'MTF Order Blocks', group = 'Order Blocks', inline = 'm_ob1')
ibull_ob_css_2 = input.color(#5d606b19, '', inline = 'm_ob1', group = 'Order Blocks')
ibear_ob_css_2 = input.color(#5d606b19, '', inline = 'm_ob1', group = 'Order Blocks')
ob_type__mtf = input.string('All', '', options = ['All', 'Internal', 'External'], group = 'Order Blocks', inline = 'm_ob1')
i_tf_ob_mtf = input.timeframe('240', 'Timeframe', group = 'Order Blocks', inline = 'mob2')
mittigation_filt_mtf = input.string('Wicks', 'Mitigation Method', options = ['Touch', 'Wicks', 'Close', 'Average'], group = 'Order Blocks', inline = 'mob3')
overlapping_filt_mtf = input(true, 'Hide Overlap', inline = 'mob3', group = 'Order Blocks')
max_obs_mtf = input.int(4, 'Max OBs', minval = 3, group = 'Order Blocks', inline = 'mob4')
length_extend_ob_mtf = input.int(defval = 20, title = 'Length', minval = 0, maxval = 500, group = 'Order Blocks', inline = 'mob4')
ob_extend_mtf = input.bool(false, 'Extend', group = 'Order Blocks', inline = 'mob4')

text_size_ob2 = input.string('Medium', options = ['Small', 'Medium', 'Large'], title = 'Text Size', inline = 'ob2_t', group = 'Order Blocks')
text_size_ob_2 = text_size_ob2 == 'Small' ? size.tiny : text_size_ob2 == 'Medium' ? size.small : text_size_ob2 == 'Large' ? size.normal : text_size_ob2 == 'Medium2' ? size.normal : text_size_ob2 == 'Large2' ? size.large : size.huge
ob_text_color_2 = input.color(#787b86, '', inline = 'ob2_t', group = 'Order Blocks')
volume_text_2 = input.bool(true, 'Volume', group = 'Order Blocks', inline = 'ob2_t')
percent_text_2 = input.bool(true, 'Percentage', group = 'Order Blocks', inline = 'ob2_t')

show_line_ob2 = input.string('On', title = 'Mid Line', options = ['On', 'Off'], group = 'Order Blocks', inline = 'ob2_l')
show_line_ob_2 = show_line_ob2 == 'On' ? true : false
line_style_ob2 = input.string('Solid', title = 'Line Style', options = ['Solid', 'Dashed', 'Dotted'], group = 'Order Blocks', inline = 'ob2_l')
line_style_ob_2 = line_style_ob2 == 'Solid' ? line.style_solid : line_style_ob2 == 'Dashed' ? line.style_dashed : line.style_dotted

v_buy = #00dbff4d
v_sell = #e91e634d

tf_s1 = i_tf_ob_mtf == '' ? timeframe.period : i_tf_ob_mtf
timeframe_st = not str.contains(tf_s1, 'S') and not str.contains(tf_s1, 'D') and not str.contains(tf_s1, 'W') and not str.contains(tf_s1, 'M') ? str.tonumber(tf_s1) >= 60 ? str.tostring(str.tonumber(tf_s1) / 60) + 'H' : tf_s1 + 'M' : tf_s1

timeframe1 = timeframe_st + ' : '
show_iob = ob_type__ == 'All' or ob_type__ == 'Internal' //input(true, 'Internal', inline = 'ob', group = 'Order Blocks')
show_ob = ob_type__ == 'All' or ob_type__ == 'External' //input(false, 'External', inline = 'ob', group = 'Order Blocks')
show_iob_mtf = ob_type__mtf == 'All' or ob_type__mtf == 'Internal' //input(true, 'Internal', inline = 'ob', group = 'Order Blocks')
show_ob_mtf = ob_type__mtf == 'All' or ob_type__mtf == 'External' //input(false, 'External', inline = 'ob', group = 'Order Blocks')
ob_showlast = 5 //input.int(10, 'LookBack', minval = 1, inline = 'ob', group = 'Order Blocks')
iob_showlast = 5 //input.int(5, 'LookBack', minval = 1, inline = 'iob', group = 'Order Blocks')
max_width_ob = 3 //input.float(3, 'Max OB Width', minval = 0.1,maxval = 3, inline = 'close', group = 'Order Blocks')
max_width_ob := max_width_ob == 3 ? 20 : max_width_ob

style = 'Colored'
v_lookback = 10
ob_loockback = 10
timediff = (time[1] - time[101]) / 100

color CLEAR = color.rgb(0, 0, 0, 100)

showms = input(true, title = 'Market Structure ', inline = '0', group = 'Market Structure')
bosColor1 = input.color(#09ff00, '', group = 'Market Structure', inline = '0')
bosColor2 = input.color(color.rgb(255, 0, 0), '', group = 'Market Structure', inline = '0')
ms_type = input.string('All', options = ['All', 'External', 'Internal'], title = '', group = 'Market Structure', inline = '0')
show_equal_highlow = input(false, 'Equal Highs & Lows', group = 'Market Structure', inline = 'equilibrium_zone')
eq_bear_color = input.color(color.rgb(12, 61, 238), '', group = 'Market Structure', inline = 'equilibrium_zone')
eq_bull_color = input.color(color.rgb(230, 10, 94), '', group = 'Market Structure', inline = 'equilibrium_zone')
eq_threshold = input.float(0.3, '', minval = 0, maxval = 0.5, step = 0.1, group = 'Market Structure', inline = 'equilibrium_zone')
showSwing = input.bool(false, 'Swing Points', group = 'Market Structure', inline = '3')
swingSize_swing = input.int(10, 'Swing Point Period', inline = '4', group = 'Market Structure')
label_sizes_s = input.string('Medium', options = ['Small', 'Medium', 'Large'], title = 'Label Size', inline = '4', group = 'Market Structure')
label_size_buysell_s = label_sizes_s == 'Small' ? size.tiny : label_sizes_s == 'Medium' ? size.small : label_sizes_s == 'Large' ? size.normal : label_sizes_s == 'Medium2' ? size.normal : label_sizes_s == 'Large2' ? size.large : size.huge
label_size_buysell = label_sizes_s == 'Small' ? size.tiny : label_sizes_s == 'Medium' ? size.small : label_sizes_s == 'Large' ? size.normal : label_sizes_s == 'Medium2' ? size.normal : label_sizes_s == 'Large2' ? size.large : size.huge
swingColor = input.color(#787b86, '', group = 'Market Structure', inline = '3')

swingSize = 3
length_eqh = 3

show_fvg = input(true, 'Fair Value Gaps (FVG)', group = 'Fair Value Gaps', inline = 'fvg_css')
i_tf = input.timeframe('', 'Timeframe', group = 'Fair Value Gaps', inline = 'tf')
max_width_fvg = input.float(1.5, 'Max Width', minval = 0, maxval = 5.0, step = 0.1, group = 'Fair Value Gaps', inline = 'width')
remove_small = input.bool(true, 'Filter FVG', group = 'Fair Value Gaps', inline = 'width')
mittigation_filt_fvg = input.string('Average', 'Mitigation Method', options = ['Touch', 'Wicks', 'Close', 'Average'], group = 'Fair Value Gaps', inline = 'mt')
fvg_color_fill = input.bool(true, 'Fill', group = 'Fair Value Gaps', inline = 'mt')
fvg_shade_fill = input.bool(false, 'Shade', group = 'Fair Value Gaps', inline = 'mt')
max_fvg = input.int(defval = 4, title = 'Max FVG', minval = 0, maxval = 50, group = 'Fair Value Gaps', inline = 'OS')
length_extend = input.int(defval = 20, title = 'Length', minval = 0, maxval = 100, group = 'Fair Value Gaps', inline = 'OS')
fvg_extend = input.bool(false, 'Extend', group = 'Fair Value Gaps', inline = 'OS')
i_mtfbearishfvgcolor = input.color(#2962ff, '', group = 'Fair Value Gaps', inline = 'fvg_css')
i_mtfbullishfvgcolor = input.color(#c2185b, '', group = 'Fair Value Gaps', inline = 'fvg_css')
mid_style = input.string('Solid', '  Style', ['Solid', 'Dashed', 'Dotted'], group = 'Fair Value Gaps', inline = 'mid')
i_midPointColor = input.color(#787b86, '', group = 'Fair Value Gaps', inline = 'mid')
fvg_extend_B = input.bool(true, 'Extend (Current)', group = 'Fair Value Gaps', inline = 'mid')

i_bullishfvgcolor = color.new(color.green, 100)
i_bearishfvgcolor = color.new(color.green, 90)
i_fillByMid = true
i_deleteonfill = true
i_textColor = color.white
i_mtf = 'HTF'
i_tfos = 10
i_mtfos = 50

var Show_4H_Levels = input.bool(defval = false, title = '4H', group = 'Key Levels', inline = '4H')
Color_4H_Levels = input.color(title = '', defval = color.orange, group = 'Key Levels', inline = '4H')
Style_4H_Levels = input.string('Dotted', '  Style', ['Solid', 'Dashed', 'Dotted'], group = 'Key Levels', inline = '4H')
Text_4H_Levels = input.bool(defval = false, title = 'Shorten', group = 'Key Levels', inline = '4H')

var Show_Daily_Levels = input.bool(defval = false, title = 'Daily', group = 'Key Levels', inline = 'Daily')
Color_Daily_Levels = input.color(title = '', defval = #08bcd4, group = 'Key Levels', inline = 'Daily')
Style_Daily_Levels = input.string('Dotted', '  Style', ['Solid', 'Dashed', 'Dotted'], group = 'Key Levels', inline = 'Daily')
Text_Daily_Levels = input.bool(defval = false, title = 'Shorten', group = 'Key Levels', inline = 'Daily')

var Show_Monday_Levels = input.bool(defval = false, title = 'Monday', group = 'Key Levels', inline = 'Monday')
Color_Monday_Levels = input.color(title = '', defval = color.white, group = 'Key Levels', inline = 'Monday')
Style_Monday_Levels = input.string('Dotted', '  Style', ['Solid', 'Dashed', 'Dotted'], group = 'Key Levels', inline = 'Monday')
Text_Monday_Levels = input.bool(defval = false, title = 'Shorten', group = 'Key Levels', inline = 'Monday')

var Show_Weekly_Levels = input.bool(defval = false, title = 'Weekly', group = 'Key Levels', inline = 'Weekly')
WeeklyColor = input.color(title = '', defval = #fffcbc, group = 'Key Levels', inline = 'Weekly')
Weekly_style = input.string('Dotted', '  Style', ['Solid', 'Dashed', 'Dotted'], group = 'Key Levels', inline = 'Weekly')
WeeklyTextType = input.bool(defval = false, title = 'Shorten', group = 'Key Levels', inline = 'Weekly')

var Show_Monthly_Levels = input.bool(defval = false, title = 'Monthly', group = 'Key Levels', inline = 'Monthly')
MonthlyColor = input.color(title = '', defval = #098c30, group = 'Key Levels', inline = 'Monthly')
Monthly_style = input.string('Dotted', '  Style', ['Solid', 'Dashed', 'Dotted'], group = 'Key Levels', inline = 'Monthly')
MonthlyTextType = input.bool(defval = false, title = 'Shorten', group = 'Key Levels', inline = 'Monthly')

var Show_Quaterly_Levels = input.bool(defval = false, title = 'Quarterly', group = 'Key Levels', inline = 'Quarterly')
quarterlyColor = input.color(title = '', defval = #bcffd0, group = 'Key Levels', inline = 'Quarterly')
Quaterly_style = input.string('Dotted', '  Style', ['Solid', 'Dashed', 'Dotted'], group = 'Key Levels', inline = 'Quarterly')
QuarterlyTextType = input.bool(defval = false, title = 'Shorten', group = 'Key Levels', inline = 'Quarterly')

var Show_Yearly_Levels = input.bool(defval = false, title = 'Yearly', group = 'Key Levels', inline = 'Yearly')
YearlyColor = input.color(title = '', defval = #ffbcdb, group = 'Key Levels', inline = 'Yearly')
Yearly_style = input.string('Dotted', '  Style', ['Solid', 'Dashed', 'Dotted'], group = 'Key Levels', inline = 'Yearly')
YearlyTextType = input.bool(defval = false, title = 'Shorten', group = 'Key Levels', inline = 'Yearly')

labelsize = input.string(defval = 'Medium', title = 'Text Size', options = ['Small', 'Medium', 'Large'], group = 'Key Levels', inline = 'H')

var pdhtext = Text_Daily_Levels ? 'PDH' : 'Prev Day High'
var pdltext = Text_Daily_Levels ? 'PDL' : 'Prev Day Low'
var dotext = Text_Daily_Levels ? 'DO' : 'Daily Open'
var pdmtext = Text_Daily_Levels ? 'PDM' : 'Prev Day Mid'
var pwhtext = WeeklyTextType ? 'PWH' : 'Prev Week High'
var pwltext = WeeklyTextType ? 'PWL' : 'Prev Week Low'
var wotext = WeeklyTextType ? 'WO' : 'Weekly Open'
var pwmtext = WeeklyTextType ? 'PWM' : 'Prev Week Mid'
var pmhtext = MonthlyTextType ? 'PMH' : 'Prev Month High'
var pmltext = MonthlyTextType ? 'PML' : 'Prev Month Low'
var motext = MonthlyTextType ? 'MO' : 'Monthly Open'
var pmmtext = MonthlyTextType ? 'PMM' : 'Prev Month Mid'
var pqhtext = QuarterlyTextType ? 'PQH' : 'Prev Quarter High'
var pqltext = QuarterlyTextType ? 'PQL' : 'Prev Quarter Low'
var qotext = QuarterlyTextType ? 'QO' : 'Quarterly Open'
var pqmtext = QuarterlyTextType ? 'PQM' : 'Prev Quarter Mid'
var cyhtext = YearlyTextType ? 'CYH' : 'Current Year High'
var cyltext = YearlyTextType ? 'CYL' : 'Current Year Low'
var yotext = YearlyTextType ? 'YO' : 'Yearly Open'
var cymtext = YearlyTextType ? 'CYM' : 'Current Year Mid'
var pihtext = Text_4H_Levels ? 'P-4H-H' : 'Prev 4H High'
var piltext = Text_4H_Levels ? 'P-4H-L' : 'Prev 4H Low'
var iotext = Text_4H_Levels ? '4H-O' : '4H Open'
var pimtext = Text_4H_Levels ? 'P-4H-M' : 'Prev 4H Mid'
var pmonhtext = Text_Monday_Levels ? 'MDAY-H' : 'Monday High'
var pmonltext = Text_Monday_Levels ? 'MDAY-L' : 'Monday Low'
var pmonmtext = Text_Monday_Levels ? 'MDAY-M' : 'Monday Mid'

displayStyle = 'Standard'
distanceright = 25
radistance = 250
linesize = 'Small'
linestyle = 'Solid'
var untested_monday = false

var is_londonrange_enabled = input.bool(defval = false, title = 'London', group = 'Session Levels', inline = 'london')
var london_OC = input.bool(defval = true, title = 'O/C', group = 'Session Levels', inline = 'london')
var london_HL = input.bool(defval = true, title = 'H/L', group = 'Session Levels', inline = 'london')
var is_usrange_enabled = input.bool(defval = false, title = 'New York', group = 'Session Levels', inline = 'US')
var us_OC = input.bool(defval = true, title = 'O/C', group = 'Session Levels', inline = 'US')
var us_HL = input.bool(defval = true, title = 'H/L', group = 'Session Levels', inline = 'US')
var is_tokyorange_enabled = input.bool(defval = false, title = 'Tokyo', group = 'Session Levels', inline = 'asia')
var asia_OC = input.bool(defval = true, title = 'O/C', group = 'Session Levels', inline = 'asia')
var asia_HL = input.bool(defval = true, title = 'H/L', group = 'Session Levels', inline = 'asia')
SessionTextType = false //input.bool(defval=false, title='ShortHand', group='Sessions', inline='FXColor')

Londont = '0800-1600'
USt = '1400-2100'
Asiat = '0000-0900'

LondonColor = input.color(title = '', defval = color.white, group = 'Session Levels', inline = 'london')
USColor = input.color(title = '', defval = color.white, group = 'Session Levels', inline = 'US')
AsiaColor = input.color(title = '', defval = color.white, group = 'Session Levels', inline = 'asia')

Short_text_London = input.bool(defval = false, title = 'Shorten', group = 'Session Levels', inline = 'london')
Short_text_NY = input.bool(defval = false, title = 'Shorten', group = 'Session Levels', inline = 'US')
Short_text_TKY = input.bool(defval = false, title = 'Shorten', group = 'Session Levels', inline = 'asia')

var London_high_text = Short_text_London ? 'Lon-H' : 'London High'
var London_low_text = Short_text_London ? 'Lon-L' : 'London Low'
var London_open_text = Short_text_London ? 'Lon-O' : 'London Open'

var NY_high_text = Short_text_NY ? 'NY-H' : 'New York High'
var NY_low_text = Short_text_NY ? 'NY-L' : 'New York Low'
var NY_open_text = Short_text_NY ? 'NY-O' : 'New York Open'

var Tokyo_high_text = Short_text_TKY ? 'TK-H' : 'Tokyo High'
var Tokyo_low_text = Short_text_TKY ? 'TK-L' : 'Tokyo Low'
var Tokyo_open_text = Short_text_TKY ? 'TK-O' : 'Tokyo Open'

var table wm = table.new(position.bottom_right, 1, 1)
if barstate.isfirst
    table.cell(wm, 0, 0, "Telegram @SimpleForexTools", text_color = color.new(color.gray, 70), text_size = size.large)

color transparent = #ffffff00
length = 50
is_newbar(res) =>
    t = time(res)
    not na(t) and (na(t[1]) or t > t[1])

Show_MS(x, y, txt, css, dashed, down, lbl_size) =>
    label.new(int(math.avg(x, bar_index)), y, txt, color = transparent, textcolor = css, style = down ? label.style_label_down : label.style_label_up, size = lbl_size)
    line.new(x, y, bar_index, y, color = css, style = dashed ? line.style_dashed : line.style_solid)

f_barssince(_cond, _count) =>
    _barssince = bar_index - ta.valuewhen(_cond, bar_index, _count)
    _barssince

calculate_swing_points(length) =>
    var prev = 0
    prev := high[length] > ta.highest(length) ? 0 : low[length] < ta.lowest(length) ? 1 : prev[1]
    t = prev == 0 and prev[1] != 0 ? high[length] : 0
    b = prev == 1 and prev[1] != 1 ? low[length] : 0
    [t, b]

var t_MS = 0
var int_t_MS = 0
var internal_y_up = 0.
var internal_x_up = 0
var internal_y_dn = 0.
var internal_x_dn = 0
var y_up = 0.
var x_up = 0
var y_dn = 0.
var x_dn = 0
var crossed_up = true
var crossed_down = true
var internal_up_broke = true
var internal_dn_broke = true
var up_trailing = high
var down_trailing = low
var up_trailing_x = 0
var down_trailing_x = 0
var high_text = ''
var low_text = ''
bullish_OB_Break = false
bearish_OB_Break = false

bosConfType = 'Candle High' //input.string('Candle Close', 'BOS Confirmation', ['Candle Close', 'Wicks'], tooltip='Choose whether candle close/wick above previous swing point counts as a BOS.')
MSS = true //input.bool(false, 'Show MSS', tooltip='Renames the first counter t_MS BOS to MSS' )

lineStyle(x) =>
    switch x
        'Solid' => line.style_solid
        'Dashed' => line.style_dashed
        'Dotted' => line.style_dotted
pivot_high_found = ta.pivothigh(high, swingSize_swing, swingSize_swing)
pivot_low_found = ta.pivotlow(low, swingSize_swing, swingSize_swing)

var float prevHigh_s = na
var float prevLow_s = na
var int prevHighIndex_s = na
var int prevLowIndex_s = na
bool higher_highs = false
bool lower_highs = false
bool higher_lows = false
bool lower_lows = false

var int prevSwing_s = 0

if not na(pivot_high_found)
    if pivot_high_found >= prevHigh_s
        higher_highs := true
        prevSwing_s := 2
        prevSwing_s
    else
        lower_highs := true
        prevSwing_s := 1
        prevSwing_s
    prevHigh_s := pivot_high_found
    prevHighIndex_s := bar_index - swingSize_swing
    prevHighIndex_s

if not na(pivot_low_found)
    if pivot_low_found >= prevLow_s
        higher_lows := true
        prevSwing_s := -1
        prevSwing_s
    else
        lower_lows := true
        prevSwing_s := -2
        prevSwing_s
    prevLow_s := pivot_low_found
    prevLowIndex_s := bar_index - swingSize_swing
    prevLowIndex_s

if higher_highs and showSwing
    label.new(bar_index - swingSize_swing, pivot_high_found, 'HH', color = CLEAR, style = label.style_label_down, textcolor = swingColor, size = label_size_buysell_s)
if lower_highs and showSwing
    label.new(bar_index - swingSize_swing, pivot_high_found, 'LH', color = CLEAR, style = label.style_label_down, textcolor = swingColor, size = label_size_buysell_s)
if higher_lows and showSwing
    label.new(bar_index - swingSize_swing, pivot_low_found, 'HL', color = CLEAR, style = label.style_label_up, textcolor = swingColor, size = label_size_buysell_s)
if lower_lows and showSwing
    label.new(bar_index - swingSize_swing, pivot_low_found, 'LL', color = CLEAR, style = label.style_label_up, textcolor = swingColor, size = label_size_buysell_s)

var htfH = open
var htfL = open

if close > htfH
    htfH := close
    htfH
if close < htfL
    htfL := close
    htfL

sClose = request.security(ticker.standard(syminfo.tickerid), i_tf, close[1], barmerge.gaps_off, barmerge.lookahead_on)
sHighP2 = request.security(ticker.standard(syminfo.tickerid), i_tf, high[2], barmerge.gaps_off, barmerge.lookahead_on)
sLowP2 = request.security(ticker.standard(syminfo.tickerid), i_tf, low[2], barmerge.gaps_off, barmerge.lookahead_on)
sOpen = request.security(ticker.standard(syminfo.tickerid), i_tf, open[1], barmerge.gaps_off, barmerge.lookahead_on)
sBar = request.security(ticker.standard(syminfo.tickerid), i_tf, bar_index, barmerge.gaps_off, barmerge.lookahead_on)

var bullishgapholder = array.new_box(0)
var bearishgapholder = array.new_box(0)

var bullishgapholder_fill = array.new_box(0)
var bearishgapholder_fill = array.new_box(0)

var bullish_high_holder = array.new_line(0)
var bearish_high_holder = array.new_line(0)
var bullish_low_holder = array.new_line(0)
var bearish_low_holder = array.new_line(0)
var bullishmidholder = array.new_line(0)
var bearishmidholder = array.new_line(0)
var bullishlabelholder = array.new_label(0)
var bearishlabelholder = array.new_label(0)
var transparentcolor = color.new(color.white, 100)

var fvg_apper = false
var fvg_break = false

fvg_apper := false
fvg_break := false

create_fvg_func(_upperlimit, _lowerlimit, _midlimit, _bar, _boxholder, _boxholder_fill, _midholder, _highholder, _lowholder, _labelholder, _boxcolor, _mtfboxcolor, _htf) =>
    timeholder = str.tostring(i_tf)
    offset = i_mtfos
    boxbgcolor = _mtfboxcolor
    bg_color = color.new(_mtfboxcolor, 90)
    if _htf == false
        timeholder := str.tostring(timeframe.period)
        offset := i_tfos
        boxbgcolor := _boxcolor
        boxbgcolor
    array.push(_boxholder, box.new(_bar, _upperlimit, _bar + timediff * length_extend, _lowerlimit, border_color = fvg_color_fill ? bg_color : na, bgcolor = fvg_color_fill ? bg_color : na, extend = fvg_extend ? extend.right : extend.none, xloc = xloc.bar_time, text = '', text_color = #787b86, text_halign = text.align_right, text_size = size.small))
    array.push(_boxholder_fill, box.new(_bar, _upperlimit, _bar + timediff * length_extend, _lowerlimit, border_color = fvg_color_fill ? bg_color : na, bgcolor = fvg_color_fill ? bg_color : na, extend = fvg_extend ? extend.right : extend.none, xloc = xloc.bar_time))
    array.push(_midholder, line.new(_bar, (_lowerlimit + _upperlimit) / 2.0, _bar + timediff * length_extend, _midlimit, color = i_midPointColor, extend = fvg_extend ? extend.right : extend.none, style = lineStyle(mid_style), width = 1, xloc = xloc.bar_time))
    array.push(_lowholder, line.new(_bar, _lowerlimit, _bar + timediff * length_extend, _lowerlimit, color = i_fillByMid ? boxbgcolor : na, extend = fvg_extend ? extend.right : extend.none, width = 1, xloc = xloc.bar_time))
    array.push(_highholder, line.new(_bar, _upperlimit, _bar + timediff * length_extend, _upperlimit, color = i_fillByMid ? boxbgcolor : na, extend = fvg_extend ? extend.right : extend.none, width = 1, xloc = xloc.bar_time))

check_fvg_func(_close, _high, _highp2, _low, _lowp2, _open, _bar, _htf) =>
    gap = 0
    thold_ = (ta.highest(_high, 300) - ta.lowest(_low, 300)) * math.max(max_width_fvg, 0.1) / 100.
    if _open > _close // red

        if _lowp2 > _high
            if not remove_small or math.abs(_lowp2 - _high) > thold_
                upperlimit = _high //_close - (_close - _lowp2 )
                lowerlimit = _lowp2 //_close - (_close-_high)
                midlimit = lowerlimit + (upperlimit - lowerlimit) / 2.
                gap := 1
                create_fvg_func(upperlimit, lowerlimit, midlimit, _bar, bullishgapholder, bullishgapholder_fill, bullishmidholder, bullish_high_holder, bullish_low_holder, bullishlabelholder, i_bullishfvgcolor, i_mtfbullishfvgcolor, _htf)

    else 
        if _low > _highp2
            if not remove_small or math.abs(_low - _highp2) > thold_
                upperlimit = _low //_close - (_close-_low)
                lowerlimit = _highp2 //_close- (_close - _highp2),
                midlimit = lowerlimit + (upperlimit - lowerlimit) / 2.
                gap := -1
                create_fvg_func(upperlimit, lowerlimit, midlimit, _bar, bearishgapholder, bearishgapholder_fill, bearishmidholder, bearish_high_holder, bearish_low_holder, bearishlabelholder, i_bearishfvgcolor, i_mtfbearishfvgcolor, _htf)

    gap

delete_fvg_func(_currentgap, _currentgap_fill, _i, _boxholder, _boxholder_fill, _midholder, _highholder, _lowholder, _labelholder) =>

    array.remove(_boxholder, _i)
    array.remove(_boxholder_fill, _i)

    currentmid = array.get(_midholder, _i)
    currenthigh = array.get(_highholder, _i)
    currentlow = array.get(_lowholder, _i)
    array.remove(_midholder, _i)
    array.remove(_highholder, _i)
    array.remove(_lowholder, _i)

    if i_deleteonfill
        line.delete(currentmid)
        line.delete(currenthigh)
        line.delete(currentlow)
    else
        line.set_extend(currentmid, extend.none)
        line.set_x2(currentmid, time)
        line.set_extend(currenthigh, extend.none)
        line.set_x2(currenthigh, time)
        line.set_extend(currentlow, extend.none)
        line.set_x2(currentlow, time)

    if i_deleteonfill
        box.delete(_currentgap)
        box.delete(_currentgap_fill)

    else
        box.set_extend(_currentgap, extend.none)
        box.set_right(_currentgap, time)

validate_fvg_func(_high, _low) =>

    fvg_removed = 0
    if array.size(bullishgapholder) > 0

        for i = array.size(bullishgapholder) - 1 to 0 by 1
            if fvg_extend_B
                currentgap_fill = array.get(bullishgapholder_fill, i)
                currentgap = array.get(bullishgapholder, i)
                cmid = array.get(bullishmidholder, i)
                chigh = array.get(bullish_high_holder, i)
                clow = array.get(bullish_low_holder, i)
                line.set_x2(cmid, timenow + timediff * length_extend)
                line.set_x2(chigh, timenow + timediff * length_extend)
                line.set_x2(clow, timenow + timediff * length_extend)
                box.set_right(currentgap_fill, timenow + timediff * length_extend)
                box.set_right(currentgap, timenow + timediff * length_extend)

            if mittigation_filt_fvg == 'Touch'
                currentgap_fill = array.get(bullishgapholder_fill, i)
                currentgap = array.get(bullishgapholder, i)
                currentmid = array.get(bullishmidholder, i)
                currenthigh = array.get(bullish_high_holder, i)
                currentlow = array.get(bullish_low_holder, i)
                currenttop = box.get_top(currentgap)

                if high > currenttop
                    fvg_removed := 1
                    delete_fvg_func(currentgap, currentgap_fill, i, bullishgapholder, bullishgapholder_fill, bullishmidholder, bullish_high_holder, bullish_low_holder, bullishlabelholder)

            if mittigation_filt_fvg == 'Wicks'
                currentgap_fill = array.get(bullishgapholder_fill, i)
                currentgap = array.get(bullishgapholder, i)
                currentmid = array.get(bullishmidholder, i)
                currenthigh = array.get(bullish_high_holder, i)
                currentlow = array.get(bullish_low_holder, i)
                currenttop = box.get_bottom(currentgap)
                currentbottom = box.get_top(currentgap_fill)

                if high > currentbottom and fvg_shade_fill
                    currentgap_f = array.get(bullishgapholder_fill, i)
                    cur_bottom = box.get_bottom(currentgap_f)
                    _bottom = box.get_bottom(currentgap)
                    if _bottom == cur_bottom
                        box.set_bottom(currentgap_f, high)
                    else
                        box.set_bottom(currentgap_f, math.max(cur_bottom, high))
                    box.set_bgcolor(currentgap_f, #787b865e)

                if high > currenttop
                    fvg_removed := 1
                    delete_fvg_func(currentgap, currentgap_fill, i, bullishgapholder, bullishgapholder_fill, bullishmidholder, bullish_high_holder, bullish_low_holder, bullishlabelholder)

            if mittigation_filt_fvg == 'Close'
                currentgap_fill = array.get(bullishgapholder_fill, i)
                currentgap = array.get(bullishgapholder, i)
                currentmid = array.get(bullishmidholder, i)
                currenthigh = array.get(bullish_high_holder, i)
                currentlow = array.get(bullish_low_holder, i)
                currenttop = box.get_bottom(currentgap)
                currentbottom = box.get_top(currentgap_fill)

                if high > currentbottom and fvg_shade_fill
                    currentgap_f = array.get(bullishgapholder_fill, i)
                    cur_bottom = box.get_bottom(currentgap_f)
                    _bottom = box.get_bottom(currentgap)
                    if _bottom == cur_bottom
                        box.set_bottom(currentgap_f, high)
                    else
                        box.set_bottom(currentgap_f, math.max(cur_bottom, high))
                    box.set_bgcolor(currentgap_f, #787b865e)
                if close > currenttop
                    fvg_removed := 1
                    delete_fvg_func(currentgap, currentgap_fill, i, bullishgapholder, bullishgapholder_fill, bullishmidholder, bullish_high_holder, bullish_low_holder, bullishlabelholder)

            if mittigation_filt_fvg == 'Average'
                currentgap_fill = array.get(bullishgapholder_fill, i)
                currentgap = array.get(bullishgapholder, i)
                currentmid = array.get(bullishmidholder, i)
                currenthigh = array.get(bullish_high_holder, i)
                currentlow = array.get(bullish_low_holder, i)
                currenttop = line.get_y1(currentmid)
                currentbottom = box.get_top(currentgap_fill)

                if high > currentbottom and fvg_shade_fill
                    currentgap_f = array.get(bullishgapholder_fill, i)
                    cur_bottom = box.get_bottom(currentgap_f)
                    _bottom = box.get_bottom(currentgap)
                    if _bottom == cur_bottom
                        box.set_bottom(currentgap_f, high)
                    else
                        box.set_bottom(currentgap_f, math.max(cur_bottom, high))
                    box.set_bgcolor(currentgap_f, #787b865e)

                if high > currenttop
                    fvg_removed := 1
                    delete_fvg_func(currentgap, currentgap_fill, i, bullishgapholder, bullishgapholder_fill, bullishmidholder, bullish_high_holder, bullish_low_holder, bullishlabelholder)

    if array.size(bearishgapholder) > 0

        for i = array.size(bearishgapholder) - 1 to 0 by 1
            if fvg_extend_B
                currentgap_fill = array.get(bearishgapholder_fill, i)
                currentgap = array.get(bearishgapholder, i)
                cmid = array.get(bearishmidholder, i)
                chigh = array.get(bearish_high_holder, i)
                clow = array.get(bearish_low_holder, i)
                line.set_x2(cmid, timenow + timediff * length_extend)
                line.set_x2(chigh, timenow + timediff * length_extend)
                line.set_x2(clow, timenow + timediff * length_extend)
                box.set_right(currentgap_fill, timenow + timediff * length_extend)
                box.set_right(currentgap, timenow + timediff * length_extend)

            if mittigation_filt_fvg == 'Touch'
                currentgap_fill = array.get(bearishgapholder_fill, i)
                currentgap = array.get(bearishgapholder, i)
                currenttop = box.get_top(currentgap)
                currentmid = array.get(bearishmidholder, i)
                currenthigh = array.get(bearish_high_holder, i)
                currentlow = array.get(bearish_low_holder, i)

                if low < currenttop
                    fvg_removed := -1
                    delete_fvg_func(currentgap, currentgap_fill, i, bearishgapholder, bearishgapholder_fill, bearishmidholder, bearish_high_holder, bearish_low_holder, bearishlabelholder)
            if mittigation_filt_fvg == 'Wicks'
                currentgap_fill = array.get(bearishgapholder_fill, i)
                currentgap = array.get(bearishgapholder, i)
                currenttop = box.get_bottom(currentgap)
                currentmid = array.get(bearishmidholder, i)
                currenthigh = array.get(bearish_high_holder, i)
                currentlow = array.get(bearish_low_holder, i)
                currentbottom = box.get_top(currentgap_fill)

                if low < currentbottom and fvg_shade_fill
                    currentgap_f = array.get(bearishgapholder_fill, i)
                    cur_bottom = box.get_bottom(currentgap_f)
                    _bottom = box.get_bottom(currentgap)
                    if _bottom == cur_bottom
                        box.set_bottom(currentgap_f, low)
                    else
                        box.set_bottom(currentgap_f, math.min(cur_bottom, low))
                    box.set_bgcolor(currentgap_f, #787b865e)

                if low < currenttop
                    fvg_removed := -1
                    delete_fvg_func(currentgap, currentgap_fill, i, bearishgapholder, bearishgapholder_fill, bearishmidholder, bearish_high_holder, bearish_low_holder, bearishlabelholder)
            if mittigation_filt_fvg == 'Close'
                currentgap_fill = array.get(bearishgapholder_fill, i)
                currentgap = array.get(bearishgapholder, i)
                currenttop = box.get_bottom(currentgap)
                currentmid = array.get(bearishmidholder, i)
                currenthigh = array.get(bearish_high_holder, i)
                currentlow = array.get(bearish_low_holder, i)
                currentbottom = box.get_top(currentgap_fill)

                if low < currentbottom and fvg_shade_fill
                    currentgap_f = array.get(bearishgapholder_fill, i)
                    cur_bottom = box.get_bottom(currentgap_f)
                    _bottom = box.get_bottom(currentgap)
                    if _bottom == cur_bottom
                        box.set_bottom(currentgap_f, low)
                    else
                        box.set_bottom(currentgap_f, math.min(cur_bottom, low))
                    box.set_bgcolor(currentgap_f, #787b865e)

                if close < currenttop
                    fvg_removed := -1
                    delete_fvg_func(currentgap, currentgap_fill, i, bearishgapholder, bearishgapholder_fill, bearishmidholder, bearish_high_holder, bearish_low_holder, bearishlabelholder)
            if mittigation_filt_fvg == 'Average'
                currentgap_fill = array.get(bearishgapholder_fill, i)
                currentgap = array.get(bearishgapholder, i)
                currentmid = array.get(bearishmidholder, i)
                currenttop = line.get_y1(currentmid)
                currenthigh = array.get(bearish_high_holder, i)
                currentlow = array.get(bearish_low_holder, i)
                currentbottom = box.get_top(currentgap_fill)

                if low < currentbottom and fvg_shade_fill
                    currentgap_f = array.get(bearishgapholder_fill, i)
                    cur_bottom = box.get_bottom(currentgap_f)
                    _bottom = box.get_bottom(currentgap)
                    if _bottom == cur_bottom
                        box.set_bottom(currentgap_f, low)
                    else
                        box.set_bottom(currentgap_f, math.min(cur_bottom, low))
                    box.set_bgcolor(currentgap_f, #787b865e)

                if low < currenttop
                    fvg_removed := -1
                    delete_fvg_func(currentgap, currentgap_fill, i, bearishgapholder, bearishgapholder_fill, bearishmidholder, bearish_high_holder, bearish_low_holder, bearishlabelholder)

    fvg_removed

if is_newbar(i_tf)
    htfH := high
    htfL := low
    htfL

fvg_gap = 0

if is_newbar(i_tf) and (i_mtf == 'Current + HTF' or i_mtf == 'HTF') and show_fvg and barstate.isconfirmed
    fvg_gap := check_fvg_func(sClose, htfH, sHighP2, htfL, sLowP2, sOpen, time[2], true)
    fvg_gap

alertcondition(fvg_gap == 1, 'Bullish FVG', 'Bullish FVG Found Suvo-SMC')
alertcondition(fvg_gap == -1, 'Bearish FVG', 'Bearish FVG Found Suvo-SMC')

fvg_removed = validate_fvg_func(high, low)

alertcondition(fvg_removed == 1, 'Bullish FVG Break', 'Bullish FVG Broken Suvo-SMC')
alertcondition(fvg_removed == -1, 'Bearish FVG Break', 'Bearish FVG Broken Suvo-SMC')

if array.size(bullishgapholder) > max_fvg
    d_box = array.shift(bullishgapholder)
    box.delete(d_box)

if array.size(bullishgapholder_fill) > max_fvg
    d_box = array.shift(bullishgapholder_fill)
    box.delete(d_box)

if array.size(bullishmidholder) > max_fvg
    d_line = array.shift(bullishmidholder)
    line.delete(d_line)

if array.size(bullish_high_holder) > max_fvg
    d_line = array.shift(bullish_high_holder)
    line.delete(d_line)

if array.size(bullish_low_holder) > max_fvg
    d_line = array.shift(bullish_low_holder)
    line.delete(d_line)

if array.size(bearishgapholder) > max_fvg
    d_box_ = array.shift(bearishgapholder)
    box.delete(d_box_)

if array.size(bearishgapholder_fill) > max_fvg
    d_box_ = array.shift(bearishgapholder_fill)
    box.delete(d_box_)

if array.size(bearishmidholder) > max_fvg
    d_line_ = array.shift(bearishmidholder)
    line.delete(d_line_)

if array.size(bearish_high_holder) > max_fvg
    d_line_ = array.shift(bearish_high_holder)
    line.delete(d_line_)

if array.size(bearish_low_holder) > max_fvg
    d_line_ = array.shift(bearish_low_holder)
    line.delete(d_line_)

n = bar_index

if barstate.isfirst
    var table errorBox = table.new(position.bottom_right, 1, 1, bgcolor = color.new(#363a45, 100))
    table.cell(errorBox, 0, 0, '© SUVO PRICE ACTION CONCEPT \'', text_color = color.rgb(189, 230, 196), text_halign = text.align_center, text_size = size.normal)

var monday_time = time
var monday_high = high
var monday_low = low
cdailyh_open = request.security(syminfo.tickerid, 'D', high, lookah

Показано первые 50% кода (символов: 104408)

Открыть по тарифу

Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.

Разовая покупка файла

На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.

Чтобы оформить заказ, введите email и перейдите к оплате.

Стоимость полного кода
10 440,80₽ ≈ $127.61