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

Institutional Liquidity & Macro Dealing Range [BSL/SSL + CVD]

institutional liquidity & macro dealing range [bslssl + cvd].pine
Вы автор или правообладатель?

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

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

О программе

Индикатор TradingView для отображения институциональной ликвидности и макро-диапазонов сделок на графике цены. Основная функция — построение уровней Buy Stops (BSL) и Sell Stops (SSL) на основе свинг-пивотов с отслеживанием их снятия ценой, включая обнаружение снятия по фитилям. Также отображаются зоны справедливой стоимости (FVG) с отслеживанием инверсий, зоны спроса и предложения с потоком кумулятивного дельта-объёма (CVD), а также диапазоны премии и дисконта с аналитикой дельта-объёма.

В настройках доступна визуализация дневных и недельных максимумов/минимумов, Optional макро-диапазон, линия 50% равновесия и информационная таблица дельта-объёма. Индикатор поддерживает 6 пользовательских условий оповещений для ключевых событий: снятие BSL/SSL, инверсия iFVG, формирование зон спроса/предложения. Все элементы отрисовываются поверх графика как графические объекты Pine Script.

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

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

НастройкаОписание
swingLeft Количество баров слева, необходимых для подтверждения свинг-максимума или свинг-минимума при расчёте уровней ликвидности.
swingRight Количество баров справа, необходимых для подтверждения свинг-максимума или свинг-минимума при расчёте уровней ликвидности.
maxActiveLevels Максимальное количество одновременно отображаемых активных уровней BSL и SSL на графике.
bslLabelText Текст, отображаемый в метке рядом с линией Buy Stops (BSL) на графике.
sslLabelText Текст, отображаемый в метке рядом с линией Sell Stops (SSL) на графике.
sweepMode Действие при снятии уровня ликвидности: затушевка с маркировкой, автоматическое удаление линии или сохранение видимой.
sweepLabelStyle Стиль маркера при снятии уровня: обновление текста на линии, размещение маркера на свече или оба варианта.
detectWickSweeps Включает обнаружение снятия по фитилям, когда цена пробивает уровень BSL/SSL по фитилям, но закрывается обратно внутри.
showPdhPdl Отображение дневного максимума (PDH) и дневного минимума (PDL) как основных уровней ликвидности.
showPwhPwl Отображение недельного максимума (PWH) и недельного минимума (PWL) как дополнительных уровней ликвидности.
showFvg Отображение активных зон справедливой стоимости (FVG) на графике.
showCeMidpoint Отображение линии 50% серединного уровня (CE) внутри блоков FVG.
showFvgLabels Отображение текстовых меток (+FVG, -FVG, +iFVG, -iFVG) на блоках справедливой стоимости.
fvgLabelPos Положение текстовых меток FVG относительно блока: у правого края (впереди цены) или у левого края (в месте формирования).
fvgLabelVAlign Вертикальное положение текстовых меток FVG внутри блока: сверху, снизу или по центру.
showIfvg Отслеживание и отображение инвертированных FVG (iFVG) при пробое активной зоны FVG ценой.
maxFvgCount Максимальное количество одновременно отображаемых активных зон справедливой стоимости (FVG).
colBisi Цвет заливки блока бычьей справедливой стоимости (FVG), также обозначаемой как BISI.
colSibi Цвет заливки блока медвежьей справедливой стоимости (FVG), также обозначаемой как SIBI.
colBullIfvg Цвет заливки блока бычьего инвертированного FVG (iFVG), действующего как поддержка.
colBearIfvg Цвет заливки блока медвежьего инвертированного FVG (iFVG), действующего как сопротивление.
showSdZones Отображение зон институционального спроса и предложения (Order Block) с детекцией импульсного пробоя.
showSdWave Отображение сглаженной волны потока кумулятивного дельта-объёма (CVD) внутри активных зон спроса и предложения.
sdAtrLen Период ATR, используемый для расчёта импульсного пробоя при формировании зон спроса и предложения.
sdMomMult Множитель, определяющий минимальный размер тела пробойной свечи относительно ATR для подтверждения институционального импульса.
maxActiveSd Максимальное количество одновременно отображаемых активных зон спроса и предложения на графике.
showSdSignals Отображение треугольных маркеров пробоя при формировании зон спроса (вверх) и предложения (вниз).
colDemand Цвет заливки зон спроса (Demand Order Block).
colDemandBorder Цвет границы зон спроса.
colDemandWave Цвет заливки волны потока кумулятивного дельта-объёма (CVD) внутри активных зон спроса.
colSupply Цвет заливки зон предложения (Supply Order Block).
colSupplyBorder Цвет границы зон предложения.
colSupplyWave Цвет заливки волны потока кумулятивного дельта-объёма (CVD) внутри активных зон предложения.
colBsl Цвет линий Buy Stops (BSL) на графике.
colSsl Цвет линий Sell Stops (SSL) на графике.
colSweepMarker Цвет маркера, указывающего точку снятия уровня ликвидности.
lineStyleStr Стиль отображения активных линий уровней: сплошной, пунктирный или точечный.
lblSizeStr Размер шрифта текстовых меток на графике.
lineWidth Толщина линий уровней на графике.
showSR Отображение визуального диапазона премии и дисконта с границами на основе дельта-объёма.
srPeriod Период количества баров для расчёта диапазона премии/дисконта и дельта-объёма.
srExtendRight Количество баров вправо, на которое продлевается визуальный диапазон премии/дисконта.
atrMultiplier Множитель ATR для определения вертикальной толщины верхней зоны премии и нижней зоны дисконта в диапазоне премии/дисконта.
showEqLine Отображение линии 50% равновесия (EQ) в диапазоне премии/дисконта.
showMacro Отображение макро-диапазона сделок с расширенными границами высоких и низких значений.
macroPeriod Период количества баров для расчёта макро-диапазона сделок (макро максимумы/минимумы).
showDeltaTable Отображение таблицы дельта-объёма с данными диапазона и макро-дельты в углу графика.
tablePos Позиция таблицы дашборда дельта-объёма на графике: верхний правый, нижний правый, верхний левый или нижний левый угол.
upColor Цвет, обозначающий зону дисконта (покупатели) в диапазоне премии/дисконта.
downColor Цвет, обозначающий зону премии (продавцы) в диапазоне премии/дисконта.
colEqLine Цвет линии 50% равновесия (EQ) в диапазоне премии/дисконта.

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

indicator("Institutional Liquidity & Macro Dealing Range [BSL/SSL + CVD]", shorttitle="Liq & Flow Matrix", overlay=true, 
     max_lines_count=500, max_labels_count=500, max_boxes_count=500, max_polylines_count=100, max_bars_back=500)

string grp_liq          = "🎯 01. Swing Liquidity Engine (BSL & SSL)"
int    swingLeft        = input.int(5, "Swing Pivot Lookback (Left)", minval=2, maxval=50, group=grp_liq,
     tooltip="Number of bars to the left required to confirm a swing high/low.")
int    swingRight       = input.int(5, "Swing Pivot Lookback (Right)", minval=1, maxval=30, group=grp_liq,
     tooltip="Number of bars to the right required to confirm a swing high/low.")
int    maxActiveLevels  = input.int(5, "Max Active Levels Each (BSL & SSL)", minval=1, maxval=20, group=grp_liq,
     tooltip="Keeps the chart clean by limiting how many active liquidity lines are displayed at once.")

string bslLabelText     = input.string("Buy Stops", "BSL Label Text", group=grp_liq,
     tooltip="Custom text to display above Buy-Side Liquidity (e.g. 'Buy Stops', 'BSL', 'Buyside Liquidity').")
string sslLabelText     = input.string("Sell Stops", "SSL Label Text", group=grp_liq,
     tooltip="Custom text to display below Sell-Side Liquidity (e.g. 'Sell Stops', 'SSL', 'Sellside Liquidity').")

string grp_sweep        = "⚡ 02. Liquidity Sweep Detection"
string sweepMode        = input.string("Fade & Mark Swept", "Action When Swept", 
     options=["Fade & Mark Swept", "Delete / Remove Line", "Keep Solid"], group=grp_sweep,
     tooltip="• Fade & Mark Swept: Turns the line into a dashed/faded line and marks the sweep point.\n• Delete / Remove: Automatically removes the line as soon as price sweeps it, keeping chart 100% clean.\n• Keep Solid: Keeps line visible.")
string sweepLabelStyle  = input.string("Clean (Update Line Text)", "Sweep Marker Style",
     options=["Clean (Update Line Text)", "Marker on Sweep Candle", "Both"], group=grp_sweep,
     tooltip="• Clean (Update Line Text): Updates the existing line label to 'Sell Stops (✕ Purged)' with zero overlapping.\n• Marker on Sweep Candle: Places a clean '✕' symbol at the sweeping candle's wick.\n• Both: Updates the line text and places a candle marker.")
bool   detectWickSweeps = input.bool(true, "Detect Wick Sweeps (Liquidity Purge & Reclaim)", group=grp_sweep,
     tooltip="Highlights when price wicks beyond BSL/SSL but closes back inside (classic ICT turtle soup / liquidity purge).")

string grp_htf          = "🏛️ 03. High-Timeframe Major Liquidity"
bool   showPdhPdl       = input.bool(true, "Show Previous Day High & Low (PDH / PDL)", group=grp_htf)
bool   showPwhPwl       = input.bool(false, "Show Previous Week High & Low (PWH / PWL)", group=grp_htf)

string grp_fvg          = "📦 04. Fair Value Gaps & Inversion (FVG / iFVG)"
bool   showFvg          = input.bool(true, "Show Active FVG Zones", group=grp_fvg)
bool   showCeMidpoint   = input.bool(true, "Show 50% Consequent Encroachment (CE) Line", group=grp_fvg,
     tooltip="Draws the exact 50% midpoint line inside the imbalance box.")
bool   showFvgLabels    = input.bool(true, "Show FVG & iFVG Text Labels", group=grp_fvg,
     tooltip="Displays '+FVG' / '-FVG' on fresh gaps and '+iFVG' / '-iFVG' when inverted.")
string fvgLabelPos      = input.string("Right Edge (Ahead of Price)", "FVG Label Alignment",
     options=["Right Edge (Ahead of Price)", "Left Edge (Origin)"], group=grp_fvg,
     tooltip="• Right Edge (Ahead of Price): Positions labels on the right projected edge of the box so candles NEVER cover or overlap the text.\n• Left Edge (Origin): Places labels at the candle where the gap originally formed.")
string fvgLabelVAlign   = input.string("Top", "FVG Label Vertical Position",
     options=["Top", "Bottom", "Center"], group=grp_fvg,
     tooltip="Positions text at the Top or Bottom of the box so it never collides with the 50% CE midpoint line.")
bool   showIfvg         = input.bool(true, "Track Inversion FVGs (iFVG)", group=grp_fvg,
     tooltip="When price closes through an active FVG, it inverts into an iFVG (broken Bullish FVG becomes Bearish resistance; broken Bearish FVG becomes Bullish support).")
int    maxFvgCount      = input.int(3, "Max Active FVGs", minval=1, maxval=10, group=grp_fvg)
color  colBisi          = input.color(color.new(#80cbc4, 80), "Bullish FVG (BISI) Box", group=grp_fvg)
color  colSibi          = input.color(color.new(#ffcc80, 80), "Bearish FVG (SIBI) Box", group=grp_fvg)
color  colBullIfvg      = input.color(color.new(#089981, 75), "Bullish iFVG Box (Support)", group=grp_fvg)
color  colBearIfvg      = input.color(color.new(#f23645, 75), "Bearish iFVG Box (Resistance)", group=grp_fvg)

string grp_sd           = "🌊 05. Supply & Demand Order Blocks (CVD Flow Engine)"
bool   showSdZones      = input.bool(true, "Show S&D Order Block Zones", group=grp_sd,
     tooltip="Detects institutional Supply & Demand base order blocks with momentum breakouts.")
bool   showSdWave       = input.bool(true, "Show CVD Flow Wave (Inside Zone)", group=grp_sd,
     tooltip="Draws a smoothed cumulative volume delta flow ribbon inside active order block zones.")
int    sdAtrLen         = input.int(14, "Momentum ATR Length", minval=1, group=grp_sd)
float  sdMomMult        = input.float(0.7, "Momentum Multiplier", minval=0.1, step=0.1, group=grp_sd,
     tooltip="Breakout candle body must be >= this multiple of ATR. Default 0.7 captures clean institutional momentum for both buyers and sellers.")
int    maxActiveSd      = input.int(5, "Max Active S&D Zones Each", minval=1, maxval=20, group=grp_sd,
     tooltip="Controls how many active Demand and Supply zones can remain on chart simultaneously.")
bool   showSdSignals    = input.bool(false, "Show S&D Breakout Signals (△ / ▽)", group=grp_sd,
     tooltip="Displays clean triangle breakout signals under demand creation and above supply creation.")
color  colDemand        = input.color(color.new(#089981, 88), "Demand Zone Fill", group=grp_sd)
color  colDemandBorder  = input.color(color.new(#089981, 30), "Demand Border", group=grp_sd)
color  colDemandWave    = input.color(color.new(#22c5af, 60), "Demand CVD Wave Fill", group=grp_sd)
color  colSupply        = input.color(color.new(#f23645, 88), "Supply Zone Fill", group=grp_sd)
color  colSupplyBorder  = input.color(color.new(#f23645, 30), "Supply Border", group=grp_sd)
color  colSupplyWave    = input.color(color.new(#ef8844, 60), "Supply CVD Wave Fill", group=grp_sd)

string grp_style        = "🎨 06. Visual Styling & Colors"
color  colBsl           = input.color(#787b86, "BSL (Buy Stops) Line Color", group=grp_style)
color  colSsl           = input.color(#787b86, "SSL (Sell Stops) Line Color", group=grp_style)
color  colSweepMarker   = input.color(#f57c00, "Sweep Marker Color", group=grp_style)
string lineStyleStr     = input.string("Solid", "Active Line Style", options=["Solid", "Dashed", "Dotted"], group=grp_style)
string lblSizeStr       = input.string("Small", "Label Font Size", options=["Tiny", "Small", "Normal"], group=grp_style)
int    lineWidth        = input.int(1, "Line Width", minval=1, maxval=3, group=grp_style)

string grp_pd             = "⚖️ 07. Premium & Discount Dealing Range (Delta Volume Engine)"
bool   showSR             = input.bool(true, "Show Premium & Discount Range", group=grp_pd,
     tooltip="Visualizes the dealing range with Premium / Discount volume boundaries and Delta Volume analytics inspired by BigBeluga.")
int    srPeriod           = input.int(50, "P&D Lookback Period", minval=10, step=10, group=grp_pd,
     tooltip="Lookback period for calculating Support & Resistance dealing range and positive/negative volume delta.")
int    srExtendRight      = input.int(35, "Extend Range to Right (Bars)", minval=5, maxval=100, group=grp_pd)
float  atrMultiplier      = input.float(0.8, "ATR Zone Height Multiplier", minval=0.1, maxval=3.0, step=0.1, group=grp_pd,
     tooltip="Controls the vertical thickness of the upper Premium and lower Discount boxes.")
bool   showEqLine         = input.bool(true, "Show 50% Equilibrium (EQ) Line", group=grp_pd)
bool   showMacro          = input.bool(false, "Show Macro Dealing Range", group=grp_pd,
     tooltip="Draws wider macro High/Low boundary boxes over the macro lookback period.")
int    macroPeriod        = input.int(200, "Macro Lookback Period", minval=20, step=10, group=grp_pd,
     tooltip="Lookback period for Macro Highs/Lows and Macro Volume Delta.")
bool   showDeltaTable     = input.bool(true, "Show Delta Volume Dashboard Table", group=grp_pd,
     tooltip="Displays a clean dashboard in the top-right corner with Dealing Range and Macro Delta Volume %.")
string tablePos           = input.string("Top Right", "Dashboard Position", 
     options=["Top Right", "Bottom Right", "Top Left", "Bottom Left"], group=grp_pd)
color  upColor            = input.color(#79c1f1, "Discount (Buyer) Color", group=grp_pd)
color  downColor          = input.color(#f19579, "Premium (Seller) Color", group=grp_pd)
color  colEqLine          = input.color(#787b86, "Equilibrium (EQ) Line Color", group=grp_pd)

f_lineStyle(string s) =>
    switch s
        "Dashed" => line.style_dashed
        "Dotted" => line.style_dotted
        =>          line.style_solid

f_lblSize(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Normal" => size.normal
        =>          size.small

f_tablePos(string s) =>
    switch s
        "Top Left"      => position.top_left
        "Bottom Left"   => position.bottom_left
        "Bottom Right"  => position.bottom_right
        =>                 position.top_right

f_boxHAlign(string s) =>
    s == "Left Edge (Origin)" ? text.align_left : text.align_right

f_boxVAlign(string s) =>
    switch s
        "Bottom" => text.align_bottom
        "Center" => text.align_center
        =>          text.align_top

type LiqLevel
    line  ln
    label lb
    float price
    int   startBar
    bool  isBsl
    bool  swept
    int   sweepBar

var LiqLevel[] activeBsl = array.new<LiqLevel>()
var LiqLevel[] activeSsl = array.new<LiqLevel>()

float ph = ta.pivothigh(high, swingLeft, swingRight)
float pl = ta.pivotlow(low, swingLeft, swingRight)

int pivotBarHigh = bar_index - swingRight
int pivotBarLow  = bar_index - swingRight

if not na(ph)
    int x1 = pivotBarHigh
    int x2 = bar_index + 10
    float p = high[swingRight]

    line  ln = line.new(x1, p, x2, p, color = colBsl, width = lineWidth, style = f_lineStyle(lineStyleStr))
    label lb = label.new(x1, p, bslLabelText, color = color.new(color.white, 100), 
                         textcolor = colBsl, style = label.style_label_down, size = f_lblSize(lblSizeStr))

    LiqLevel item = LiqLevel.new(ln, lb, p, x1, true, false, 0)
    array.push(activeBsl, item)

    if array.size(activeBsl) > maxActiveLevels * 2
        LiqLevel oldest = array.shift(activeBsl)
        line.delete(oldest.ln)
        label.delete(oldest.lb)

if not na(pl)
    int x1 = pivotBarLow
    int x2 = bar_index + 10
    float p = low[swingRight]

    line  ln = line.new(x1, p, x2, p, color = colSsl, width = lineWidth, style = f_lineStyle(lineStyleStr))
    label lb = label.new(x1, p, sslLabelText, color = color.new(color.white, 100), 
                         textcolor = colSsl, style = label.style_label_up, size = f_lblSize(lblSizeStr))

    LiqLevel item = LiqLevel.new(ln, lb, p, x1, false, false, 0)
    array.push(activeSsl, item)

    if array.size(activeSsl) > maxActiveLevels * 2
        LiqLevel oldest = array.shift(activeSsl)
        line.delete(oldest.ln)
        label.delete(oldest.lb)

float atrVal = ta.atr(14)
bool  anyBslSwept = false
bool  anySslSwept = false

if array.size(activeBsl) > 0
    for i = array.size(activeBsl) - 1 to 0
        LiqLevel lvl = array.get(activeBsl, i)

        if not lvl.swept

            line.set_x2(lvl.ln, bar_index + 5)

            if high >= lvl.price
                lvl.swept := true
                lvl.sweepBar := bar_index
                anyBslSwept := true

                bool isWickSweep = detectWickSweeps and (close < lvl.price)

                if sweepMode == "Delete / Remove Line"
                    line.delete(lvl.ln)
                    label.delete(lvl.lb)
                    array.remove(activeBsl, i)
                else if sweepMode == "Fade & Mark Swept"
                    line.set_x2(lvl.ln, bar_index)
                    line.set_style(lvl.ln, line.style_dashed)
                    line.set_color(lvl.ln, color.new(colBsl, 65))

                    if sweepLabelStyle == "Clean (Update Line Text)" or sweepLabelStyle == "Both"
                        string updatedTxt = isWickSweep ? bslLabelText + " (✕ Purged)" : bslLabelText + " (✕ Swept)"
                        label.set_text(lvl.lb, updatedTxt)
                        label.set_textcolor(lvl.lb, isWickSweep ? colSweepMarker : color.new(colBsl, 50))
                    else
                        label.set_textcolor(lvl.lb, color.new(colBsl, 50))

                    if (sweepLabelStyle == "Marker on Sweep Candle" or sweepLabelStyle == "Both") and isWickSweep
                        if (bar_index > lvl.startBar + 2)
                            label.new(bar_index, high + atrVal * 0.35, "✕ Purged", color = color.new(color.white, 100), 
                                      textcolor = colSweepMarker, style = label.style_label_down, size = size.tiny)
        else

            if (bar_index - lvl.sweepBar) > 200
                line.delete(lvl.ln)
                label.delete(lvl.lb)
                array.remove(activeBsl, i)

if array.size(activeSsl) > 0
    for i = array.size(activeSsl) - 1 to 0
        LiqLevel lvl = array.get(activeSsl, i)

        if not lvl.swept

            line.set_x2(lvl.ln, bar_index + 5)

            if low <= lvl.price
                lvl.swept := true
                lvl.sweepBar := bar_index
                anySslSwept := true

                bool isWickSweep = detectWickSweeps and (close > lvl.price)

                if sweepMode == "Delete / Remove Line"
                    line.delete(lvl.ln)
                    label.delete(lvl.lb)
                    array.remove(activeSsl, i)
                else if sweepMode == "Fade & Mark Swept"
                    line.set_x2(lvl.ln, bar_index)
                    line.set_style(lvl.ln, line.style_dashed)
                    line.set_color(lvl.ln, color.new(colSsl, 65))

                    if sweepLabelStyle == "Clean (Update Line Text)" or sweepLabelStyle == "Both"
                        string updatedTxt = isWickSweep ? sslLabelText + " (✕ Purged)" : sslLabelText + " (✕ Swept)"
                        label.set_text(lvl.lb, updatedTxt)
                        label.set_textcolor(lvl.lb, isWickSweep ? colSweepMarker : color.new(colSsl, 50))
                    else
                        label.set_textcolor(lvl.lb, color.new(colSsl, 50))

                    if (sweepLabelStyle == "Marker on Sweep Candle" or sweepLabelStyle == "Both") and isWickSweep
                        if (bar_index > lvl.startBar + 2)
                            label.new(bar_index, low - atrVal * 0.35, "✕ Purged", color = color.new(color.white, 100), 
                                      textcolor = colSweepMarker, style = label.style_label_up, size = size.tiny)
        else
            if (bar_index - lvl.sweepBar) > 200
                line.delete(lvl.ln)
                label.delete(lvl.lb)
                array.remove(activeSsl, i)

[pdh, pdl] = request.security(syminfo.tickerid, "D", [high[1], low[1]], lookahead = barmerge.lookahead_on)
[pwh, pwl] = request.security(syminfo.tickerid, "W", [high[1], low[1]], lookahead = barmerge.lookahead_on)

var line ln_pdh = na, var label lb_pdh = na
var line ln_pdl = na, var label lb_pdl = na

bool isNewDay = ta.change(time("D")) != 0
var int dayStartBar = 0
if isNewDay
    dayStartBar := bar_index

if showPdhPdl and not na(pdh)
    int startX = dayStartBar
    int endX   = bar_index + 15

    if na(ln_pdh)
        ln_pdh := line.new(startX, pdh, endX, pdh, color = #42a5f5, width = 1, style = line.style_dashed)
        lb_pdh := label.new(endX, pdh, "PDH (Major BSL)", color = color.new(color.white, 100), 
                            textcolor = #42a5f5, style = label.style_label_left, size = size.tiny)
        ln_pdl := line.new(startX, pdl, endX, pdl, color = #ef5350, width = 1, style = line.style_dashed)
        lb_pdl := label.new(endX, pdl, "PDL (Major SSL)", color = color.new(color.white, 100), 
                            textcolor = #ef5350, style = label.style_label_left, size = size.tiny)
    else
        line.set_xy1(ln_pdh, startX, pdh), line.set_xy2(ln_pdh, endX, pdh)
        label.set_xy(lb_pdh, endX, pdh)
        line.set_xy1(ln_pdl, startX, pdl), line.set_xy2(ln_pdl, endX, pdl)
        label.set_xy(lb_pdl, endX, pdl)

type FvgBox
    box   bx
    line  ln_ce
    float top
    float btm
    float ce
    bool  isBull
    bool  isInverted
    bool  mitigated

var FvgBox[] activeFvgs = array.new<FvgBox>()

bool anyBullIfvg = false
bool anyBearIfvg = false

bool isBullFvg = (low > high[2]) and (close[1] > high[2])
bool isBearFvg = (high < low[2]) and (close[1] < low[2])

if showFvg and isBullFvg
    float top = low
    float btm = high[2]
    float ce  = (top + btm) / 2.0
    int   x1  = bar_index - 1
    int   x2  = bar_index + 10
    string fvgTxt = showFvgLabels ? "+FVG" : ""

    box bx = box.new(x1, top, x2, btm, border_width = 0, bgcolor = colBisi,
                     text = fvgTxt, text_size = size.tiny, text_color = color.new(#00897b, 10),
                     text_halign = f_boxHAlign(fvgLabelPos), text_valign = f_boxVAlign(fvgLabelVAlign))
    line ln = showCeMidpoint ? line.new(x1, ce, x2, ce, color = color.new(#00897b, 40), style = line.style_dashed) : na

    FvgBox f = FvgBox.new(bx, ln, top, btm, ce, true, false, false)
    array.push(activeFvgs, f)

    if array.size(activeFvgs) > maxFvgCount * 2
        FvgBox old = array.shift(activeFvgs)
        box.delete(old.bx)
        if not na(old.ln_ce)
            line.delete(old.ln_ce)

if showFvg and isBearFvg
    float top = low[2]
    float btm = high
    float ce  = (top + btm) / 2.0
    int   x1  = bar_index - 1
    int   x2  = bar_index + 10
    string fvgTxt = showFvgLabels ? "-FVG" : ""

    box bx = box.new(x1, top, x2, btm, border_width = 0, bgcolor = colSibi,
                     text = fvgTxt, text_size = size.tiny, text_color = color.new(#e65100, 10),
                     text_halign = f_boxHAlign(fvgLabelPos), text_valign = f_boxVAlign(fvgLabelVAlign))
    line ln = showCeMidpoint ? line.new(x1, ce, x2, ce, color = color.new(#e65100, 40), style = line.style_dashed) : na

    FvgBox f = FvgBox.new(bx, ln, top, btm, ce, false, false, false)
    array.push(activeFvgs, f)

    if array.size(activeFvgs) > maxFvgCount * 2
        FvgBox old = array.shift(activeFvgs)
        box.delete(old.bx)
        if not na(old.ln_ce)
            line.delete(old.ln_ce)

if showFvg and array.size(activeFvgs) > 0
    for i = array.size(activeFvgs) - 1 to 0
        FvgBox f = array.get(activeFvgs, i)

        if not f.mitigated
            box.set_right(f.bx, bar_index + 8)
            if not na(f.ln_ce)
                line.set_x2(f.ln_ce, bar_index + 8)

            if not f.isInverted

                if f.isBull and close < f.btm
                    if showIfvg
                        f.isInverted := true
                        anyBearIfvg := true
                        box.set_bgcolor(f.bx, colBearIfvg)
                        box.set_border_width(f.bx, 1)
                        box.set_border_color(f.bx, color.new(colBearIfvg, 20))
                        if showFvgLabels
                            box.set_text(f.bx, "-iFVG")
                            box.set_text_color(f.bx, color.new(#ef5350, 10))
                            box.set_text_halign(f.bx, f_boxHAlign(fvgLabelPos))
                            box.set_text_valign(f.bx, f_boxVAlign(fvgLabelVAlign))
                        if not na(f.ln_ce)
                            line.set_color(f.ln_ce, color.new(#ef5350, 40))
                    else
                        f.mitigated := true
                        box.set_right(f.bx, bar_index)
                        if not na(f.ln_ce)
                            line.set_x2(f.ln_ce, bar_index)

                else if not f.isBull and close > f.top
                    if showIfvg
                        f.isInverted := true
                        anyBullIfvg := true
                        box.set_bgcolor(f.bx, colBullIfvg)
                        box.set_border_width(f.bx, 1)
                        box.set_border_color(f.bx, color.new(colBullIfvg, 20))
                        if showFvgLabels
                

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