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

Order Blocks FVG & BOS

indicator order blocks fvg & bos for tradingview.pine
Вы автор или правообладатель?

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

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

О программе

Индикатор «Order Blocks FVG & BOS» предназначен для анализа и отображения на графиках TradingView ключевых концепций Smart Money: ордер-блоков, справедливых ценовых разрывов (FVG) и прорывов структуры (BOS). Индикатор работает поверх графика и рисует зоны ордер-блоков, FVG-зоны и линии BOS с соответствующими метками и цветовой кодировкой.

В основе работы лежит расчёт объёмной дельты — индикатор отображает общий объём, бычий и медвежий объём внутри каждого ордер-блока в виде цветовых заливок и процентных меток. Также рассчитывается точка контроля (POC) в диапазоне BOS и её объёмная статистика.

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

Функциональность оповещений включает условия для бычьих и медвежьих ордер-блоков, ретестов, а также конфлюэнс-сигналов (совпадение ордер-блока, FVG и BOS). Условия alertcondition() доступны для интеграции с системой оповещений TradingView.

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

НастройкаОписание
obEnabled Включает или отключает обнаружение и отрисовку ордер-блоков на графике.
obPivotLength Количество баров с каждой стороны для подтверждения пивота, используемого движком ордер-блоков. Большее значение создаёт меньше, но более крупных блоков и добавляет задержку подтверждения.
bullObColor Цвет, используемый для отображения бычьих ордер-блоков.
bearObColor Цвет, используемый для отображения медвежьих ордер-блоков.
invMethod Метод инвалидации ордер-блока: Wick инвалидирует при проколе блока ценой, Close — после закрытия свечи за его пределами.
showNearestX Максимальное количество активных ордер-блоков, отображаемых в каждом направлении, ранжированных по расстоянию от текущей цены.
dominantPctMin Минимальный процент доминирующей стороны объёма для отображения и отправки оповещений по ордер-блокам.
showHistoricZones Управляет отображением инвалидированных или завершённых исторических зон. Не управляет активными зонами.
visibleExtendedZones Количество баров для расширения активных зон вправо.
showRetestLbl Отображает треугольник на квалифицированной свече ретеста ордер-блока.
retestBullColor Цвет треугольных маркеров ретеста бычьих ордер-блоков.
retestBearColor Цвет треугольных маркеров ретеста медвежьих ордер-блоков.
hideInvalid При включении инвалидированные ордер-блоки скрываются. При отключении они могут отображаться при активном показе исторических зон.
obVolumetricInfo Отображает общий объём и проценты бычьего/медвежьего дельта внутри ордер-блоков.
obMidline Рисует геометрическую среднюю линию каждого ордер-блока.
vdEnable Включает разделение объёма на бычью и медвежью части и объёмный текст внутри отображаемых ордер-блоков.
vdBullColor Цвет разделения бычьей части объёмной дельты.
vdBearColor Цвет разделения медвежьей части объёмной дельты.
displayStyle Стиль отображения разделения объёма: вертикальный (разделение слева/справа) или горизонтальный (разделение сверху/снизу).
vdTfIn Младший таймфрейм, используемый для оценки дельты объёма.
showTotalVol Отображает общий объём (бычий + медвежий) из активного источника дельты.
showDeltaPct Отображает процентное соотношение бычьего и медвежьего объёма. Если выбранный таймфрейм ниже графика, используются данные младшего таймфрейма.
vdTextColor Цвет текста для меток объёма, дельты и процентов.
showPoc Рисует уровень точки контроля (POC) внутри каждого отображаемого ордер-блока.
pocColor Цвет линии точки контроля (POC) внутри ордер-блоков.
pocWidth Толщина линии точки контроля (POC).
showFvg Включает обнаружение и отображение справедливых ценовых разрывов (FVG).
fvgBullColor Цвет, используемый для отображения бычьих справедливых ценовых разрывов (FVG).
fvgBearColor Цвет, используемый для отображения медвежьих справедливых ценовых разрывов (FVG).
fvgDetectionMethod Метод обнаружения FVG: Same требует согласованного направления трёх свечей, Any принимает любой трёхсвечной разрыв.
fvgInvalidationMethod Метод инвалидации FVG: Close инвалидирует после закрытия свечи через разрыв, Wick — при проколе цены.
fvgSensitivity Минимальный размер разрыва определяется как ATR, делённый на это значение. Большее значение допускает более мелкие разрывы.
fvgVolumetricInfo Добавляет исходный объём к меткам FVG.
fvgCombineZones Подавляет новый однонаправленный FVG, если он перекрывается с существующей активной FVG-зоной.
fvgMidline Рисует пунктирную линию через центр каждой FVG-зоны.
fvgLabels Отображает центрированную метку внутри каждой активной FVG-зоны.
fvgLabelColor Цвет текста меток FVG и инверсионных FVG.
fvgMaxStored Максимальное количество записей FVG, сохраняемых для отображения и проверки конфлюэнса.
showBos Отображает пунктирную линию прорывов структуры (BOS) и центрированную метку BOS.
bosBullColor Цвет, используемый для линий и меток бычьих прорывов структуры (BOS).
bosBearColor Цвет, используемый для линий и меток медвежьих прорывов структуры (BOS).
showConfluence Рисует метки LONG или SHORT только при совпадении нового объёмного ордер-блока, однонаправленной активной FVG и подтверждённого BOS. При отключении метки и соответствующие оповещения удаляются.
confluenceWindow Максимальный возраст в барах активной однонаправленной FVG-зоны для квалификации конфлюэнс-сигнала.
confluenceBullColor Цвет, используемый для меток бычьих конфлюэнс-сигналов (OB + FVG + BOS).
confluenceBearColor Цвет, используемый для меток медвежьих конфлюэнс-сигналов (OB + FVG + BOS).
showInversionFvg Отображает FVG противоположного направления после заполнения исходного разрыва.
ifvgBullColor Цвет, используемый для отображения бычьих инверсионных FVG.
ifvgBearColor Цвет, используемый для отображения медвежьих инверсионных FVG.
ifvgInvalidationMethod Метод инвалидации инверсионного FVG: по закрытию свечи (Close) или по проколу (Wick).
ifvgVolumetricInfo Добавляет исходный объём к меткам инверсионных FVG.
ifvgMidline Рисует пунктирную среднюю линию через инверсионные FVG.
breakerEnabled Включает отображение инвалидированных ордер-блоков в цветах брейкер-блоков.
breakerBullColor Цвет, используемый для отображения бычьих брейкер-блоков (инвалидированных ордер-блоков).
breakerBearColor Цвет, используемый для отображения медвежьих брейкер-блоков (инвалидированных ордер-блоков).
breakerInvalidationMethod Предпочтительный метод инвалидации для отображения брейкер-блоков: по проколу (Wick) или по закрытию свечи (Close).
breakerVolumetricInfo Отображает объёмную информацию на брейкер-блоках.
breakerMidline Рисует среднюю линию через отображаемые брейкер-блоки.
tfChart Разрешает вывод ордер-блоков и структуры на таймфрейме графика.
tfChartSource Необязательный селектор источника таймфрейма графика.
tf1h Разрешает вывод, когда таймфрейм графика совпадает с выбранным часовым источником.
tf1hSource Старший таймфрейм, используемый селектором одного часа.
tf1w Разрешает вывод, когда таймфрейм графика совпадает с выбранным недельным источником.
tf1wSource Старший таймфрейм, используемый селектором одной недели.
msSwingLength Количество баров с каждой стороны, используемое для подтверждения пивотов рыночной структуры.
msBullColor Цвет, используемый для отображения бычьих элементов рыночной структуры.
msBearColor Цвет, используемый для отображения медвежьих элементов рыночной структуры.
msBos Включает линию и центрированную метку BOS для рыночной структуры.
msBosCandleColoring Окрашивает подтверждённую свечу BOS в цвет бычьей или медвежьей рыночной структуры.
showEqh Рисует пунктирную линию и центрированную метку EQH, когда новый подтверждённый пивот высокий находится в пределах 0.10 ATR от предыдущего.
showEql Рисует пунктирную линию и центрированную метку EQL, когда новый подтверждённый пивот низкий находится в пределах 0.10 ATR от предыдущего.
alBullOB Включает оповещение при обнаружении бычьего ордер-блока.
alBearOB Включает оповещение при обнаружении медвежьего ордер-блока.
alBullRetest Включает оповещение при ретесте бычьего ордер-блока.
alBearRetest Включает оповещение при ретесте медвежьего ордер-блока.

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

indicator("Order Blocks FVG & BOS", overlay = true,
     max_boxes_count = 500, max_labels_count = 500, max_lines_count = 500, max_bars_back = 5000)

const int MAX_STORED_OBS = 50

lineStyleFromString(string value) =>
    switch value
        "Dotted" => line.style_dotted
        "Dashed" => line.style_dashed
        => line.style_solid

labelSizeFromString(string value) =>
    switch value
        "Tiny" => size.tiny
        "Small" => size.small
        "Normal" => size.normal
        "Large" => size.large
        => size.auto

grpOB = "ORDER BLOCKS"
obEnabled = input.bool(true, "Enabled", group = grpOB, inline = "obEnable", tooltip = "Turns Volume Delta order-block detection and drawings on or off.")
obPivotLength = input.int(5, "Order Block Pivot", minval = 1, maxval = 50, group = grpOB, inline = "sw", tooltip = "Number of bars required on each side to confirm the pivot used by the order-block engine. Higher values create fewer, larger-structure blocks and add confirmation delay.")
bullObColor = input.color(color.new(color.teal, 55), "", group = grpOB, inline = "sw", tooltip = "Color used for order blocks.")
bearObColor = input.color(color.new(color.red, 55), "", group = grpOB, inline = "sw", tooltip = "Color used for order blocks.")
invMethod = input.string("Wick", "Invalidation", options = ["Wick", "Close"], group = grpOB, display = display.none, tooltip = "Wick invalidates when price pierces the block; Close waits for a candle close beyond it.")
showNearestX = input.int(3, "Show Nearest", minval = 1, maxval = 20, group = grpOB, display = display.none, tooltip = "Maximum active blocks shown per direction, ranked by distance from current price.")
dominantPctMin = input.float(0.0, "Minimum Dominant Volume %", minval = 0.0, maxval = 100.0, step = 1.0, group = grpOB,
 tooltip = "Only display/order alerts for blocks whose dominant side is at least this percentage. Set to 60 to match the video example.")
showHistoricZones = input.bool(true, "Show Historic Zones", group = grpOB, tooltip = "Controls whether invalidated or completed historical zones may be drawn. It does not control active zones.")
visibleExtendedZones = input.int(10, "Visible Extended Zones", minval = 0, group = grpOB,
 tooltip = "Number of bars to extend active zones to the right.")
showRetestLbl = input.bool(true, "Retest Labels", group = grpOB, tooltip = "Displays a triangle on a qualifying closed-candle retest of a displayed order block.")
retestMarkerSize = labelSizeFromString(input.string("Small", "Retest Marker Size", options = ["Tiny", "Small", "Normal", "Large", "Auto"], group = grpOB, tooltip = "Controls the size of bullish and bearish retest triangle markers."))
retestBullColor = input.color(color.new(color.teal, 0), "Bullish Retest Color", group = grpOB, inline = "retColor", tooltip = "Color used for order-block retest triangle markers.")
retestBearColor = input.color(color.new(color.red, 0), "Bearish Retest Color", group = grpOB, inline = "retColor", tooltip = "Color used for order-block retest triangle markers.")
hideInvalid = input.bool(true, "Hide Invalidated Zones", group = grpOB, inline = "tog", tooltip = "When enabled, invalidated blocks are hidden. When disabled, they can be shown if Show Historic Zones is also enabled.")

grpOBX = "ORDER BLOCK OPTIONS"
obVolumetricInfo = input.bool(true, "Volumetric Info", group = grpOBX, inline = "obx", tooltip = "Shows total volume and bullish/bearish delta percentages inside order blocks.")
obMidline = input.bool(false, "Midline", group = grpOBX, inline = "obx", tooltip = "Draws the geometric midpoint of each order block.")

grpVD = "VOLUME DELTA"
vdEnable = input.bool(true, "Enable", group = grpVD, inline = "vd", tooltip = "Enables volume-delta split fills and volume text inside displayed order blocks.")
vdBullColor = input.color(color.new(color.teal, 65), "", group = grpVD, inline = "vd", tooltip = "Color used for volume-delta split fills.")
vdBearColor = input.color(color.new(color.red, 65), "", group = grpVD, inline = "vd", tooltip = "Color used for volume-delta split fills.")
displayStyle = input.string("Vertical", "Display Style", options = ["Vertical", "Horizontal"], group = grpVD, 
 tooltip = "Horizontal: split shown top/bottom.\nVertical: split shown left/right across the zone.", display = display.none)
vdTfIn = input.timeframe("", "Volume Delta Timeframe", group = grpVD, 
 tooltip = "Lower timeframe used to estimate delta")
showTotalVol = input.bool(true, "Display Total Volume", group = grpVD, 
 tooltip = "Displays total volume (Bull+Bear) from the active delta source.", inline = "vd2") and vdEnable
showDeltaPct = input.bool(true, "Show Delta %", group = grpVD, inline = "vd2", 
 tooltip = "Shows bullish vs bearish volume split.\nIf selected TF is lower than chart TF, uses LTF data; otherwise uses chart TF.") and vdEnable
vdTextColor = input.color(color.white, "", group = grpVD, inline = "vd2", tooltip = "Text color used for volume, delta, and percentage labels.")
showPoc = input.bool(true, "Show POC", group = grpVD, inline = "poc",
 tooltip = "Draws the most-touched price level inside each displayed block.")
pocColor = input.color(color.new(color.yellow, 0), "", group = grpVD, inline = "poc", tooltip = "Color used for the point-of-control line.")
pocWidth = input.int(1, "POC Width", minval = 1, maxval = 4, group = grpVD, display = display.none, tooltip = "Line width used for the point-of-control line.")
pocStyle = lineStyleFromString(input.string("Dashed", "POC Line Type", options = ["Solid", "Dashed", "Dotted"], group = grpVD, tooltip = "Line style used for the point-of-control level inside each displayed order block."))

grpPA = "PRICE ACTION CONFLUENCE"
showFvg = input.bool(true, "Enabled", group = grpPA, inline = "fvg", tooltip = "Enables fair-value-gap detection and display.")
fvgBullColor = input.color(color.new(color.lime, 82), "", group = grpPA, inline = "fvg", tooltip = "Color used for fair-value gaps.")
fvgBearColor = input.color(color.new(color.orange, 82), "", group = grpPA, inline = "fvg", tooltip = "Color used for fair-value gaps.")
fvgDetectionMethod = input.string("Same", "Detection Method", options = ["Same", "Any"], group = grpPA, tooltip = "Same requires the three candles to agree directionally; Any accepts any three-candle gap.")
fvgInvalidationMethod = input.string("Close", "Invalidation Method", options = ["Close", "Wick"], group = grpPA, tooltip = "Close invalidates after a candle closes through the gap; Wick invalidates on a price pierce.")
fvgSensitivity = input.int(5, "Sensitivity", minval = 1, maxval = 50, group = grpPA, tooltip = "Minimum gap size is ATR divided by this value. Higher values allow smaller gaps.")
fvgVolumetricInfo = input.bool(false, "Volumetric Info", group = grpPA, inline = "fvgx", tooltip = "Adds the source volume to FVG labels.")
fvgCombineZones = input.bool(true, "Combine Zones", group = grpPA, inline = "fvgx", tooltip = "Suppresses a new same-direction FVG when it overlaps an existing active FVG.")
fvgMidline = input.bool(true, "Midline", group = grpPA, inline = "fvgx", tooltip = "Draws a dotted line through the center of each FVG.")
fvgLabels = input.bool(true, "Labels", group = grpPA, inline = "fvgl", tooltip = "Places a centered FVG label inside each active gap.")
fvgLabelColor = input.color(color.white, "", group = grpPA, inline = "fvgl", tooltip = "Text color used for FVG and IFVG labels.")
fvgMaxStored = input.int(20, "Stored FVGs", minval = 1, maxval = 100, group = grpPA, display = display.none, tooltip = "Maximum number of FVG records retained for display and confluence checks.")
showBos = input.bool(true, "Show Break of Structure", group = grpPA, inline = "bos", tooltip = "Shows the dotted swing-to-break BOS line and centered BOS label.")
bosBullColor = input.color(color.new(color.lime, 0), "", group = grpPA, inline = "bos", tooltip = "Color used for BOS lines and labels.")
bosBearColor = input.color(color.new(color.red, 0), "", group = grpPA, inline = "bos", tooltip = "Color used for BOS lines and labels.")
showConfluence = input.bool(true, "Show OB + FVG + BOS Signals", group = grpPA,
 tooltip = "Draws a LONG or SHORT label only when a new Volume Delta order block, a same-direction active FVG, and the confirmed BOS align. Unchecking it removes those labels and disables their alerts.")
confluenceWindow = input.int(20, "Confluence FVG Window", minval = 1, maxval = 100, group = grpPA, display = display.none, tooltip = "Maximum age in bars for an active same-direction FVG to qualify for an OB + FVG + BOS signal.")
confluenceBullColor = input.color(color.new(color.lime, 0), "Bullish Signal Color", group = grpPA, inline = "confStyle", tooltip = "Color used for OB + FVG + BOS signal labels.")
confluenceBearColor = input.color(color.new(color.red, 0), "Bearish Signal Color", group = grpPA, inline = "confStyle", tooltip = "Color used for OB + FVG + BOS signal labels.")
confluenceLabelSize = labelSizeFromString(input.string("Small", "Signal Label Size", options = ["Tiny", "Small", "Normal", "Large", "Auto"], group = grpPA, tooltip = "Controls the size of LONG and SHORT OB + FVG + BOS labels."))
bosLabelSize = labelSizeFromString(input.string("Tiny", "BOS Label Size", options = ["Tiny", "Small", "Normal", "Large", "Auto"], group = grpPA, tooltip = "Controls the size of the centered BOS label on each structure line."))

grpIFVG = "INVERSION FAIR VALUE GAPS"
showInversionFvg = input.bool(false, "Enabled", group = grpIFVG, inline = "ifvg", tooltip = "Displays an opposite-direction FVG after an original gap is filled.")
ifvgBullColor = input.color(color.new(color.teal, 82), "", group = grpIFVG, inline = "ifvg", tooltip = "Color used for inversion fair-value gaps.")
ifvgBearColor = input.color(color.new(color.red, 82), "", group = grpIFVG, inline = "ifvg", tooltip = "Color used for inversion fair-value gaps.")
ifvgInvalidationMethod = input.string("Wick", "Invalidation Method", options = ["Close", "Wick"], group = grpIFVG, tooltip = "Close or wick condition used to invalidate an inversion FVG.")
ifvgVolumetricInfo = input.bool(false, "Volumetric Info", group = grpIFVG, inline = "ifvgx", tooltip = "Adds source volume to inversion FVG labels.")
ifvgMidline = input.bool(false, "Midline", group = grpIFVG, inline = "ifvgx", tooltip = "Draws a dotted midpoint line through inversion FVGs.")

grpBreaker = "BREAKER BLOCKS"
breakerEnabled = input.bool(false, "Enabled", group = grpBreaker, inline = "br", tooltip = "Displays invalidated order blocks using breaker-block colors.")
breakerBullColor = input.color(color.new(color.blue, 78), "", group = grpBreaker, inline = "br", tooltip = "Color used for breaker blocks.")
breakerBearColor = input.color(color.new(color.olive, 78), "", group = grpBreaker, inline = "br", tooltip = "Color used for breaker blocks.")
breakerInvalidationMethod = input.string("Wick", "Invalidation Method", options = ["Wick", "Close"], group = grpBreaker, tooltip = "Invalidation preference for breaker presentation.")
breakerVolumetricInfo = input.bool(false, "Volumetric Info", group = grpBreaker, inline = "brx", tooltip = "Shows volume information on displayed breaker blocks.")
breakerMidline = input.bool(false, "Midline", group = grpBreaker, inline = "brx", tooltip = "Draws a midpoint line through displayed breaker blocks.")

grpTf = "TIMEFRAME OUTPUT FILTERS"
tfChart = input.bool(true, "Chart", group = grpTf, inline = "tfChart", tooltip = "Allows chart-timeframe order-block and structure output.")
tfChartSource = input.timeframe("", "", group = grpTf, inline = "tfChart", tooltip = "Optional chart timeframe source selector.")
tf1h = input.bool(false, "1 hour", group = grpTf, inline = "tf1h", tooltip = "Allows output when the active chart timeframe matches the selected one-hour source.")
tf1hSource = input.timeframe("60", "", group = grpTf, inline = "tf1h", tooltip = "Higher-timeframe source used by the one-hour selector.")
tf1w = input.bool(false, "1 week", group = grpTf, inline = "tf1w", tooltip = "Allows output when the active chart timeframe matches the selected one-week source.")
tf1wSource = input.timeframe("1W", "", group = grpTf, inline = "tf1w", tooltip = "Higher-timeframe source used by the one-week selector.")

grpMS = "MARKET STRUCTURES"
msSwingLength = input.int(14, "Swing Length", minval = 1, maxval = 100, group = grpMS, tooltip = "Number of bars on each side used to confirm market-structure pivots.")
msBullColor = input.color(color.new(color.teal, 0), "", group = grpMS, inline = "ms", tooltip = "Color used for market-structure output.")
msBearColor = input.color(color.new(color.red, 0), "", group = grpMS, inline = "ms", tooltip = "Color used for market-structure output.")
msBos = input.bool(true, "BOS", group = grpMS, inline = "msx", tooltip = "Enables the market-structure BOS line and centered label.")
msBosCandleColoring = input.bool(false, "BOS Candle Coloring", group = grpMS, tooltip = "Colors the confirmed BOS candle with the bullish or bearish market-structure color.")

grpEq = "EQUAL HIGHS & LOWS"
showEqh = input.bool(true, "EQH", group = grpEq, inline = "eq", tooltip = "Draws a dotted EQH line and centered EQH label when a newly confirmed pivot high is within 0.10 ATR of the prior confirmed pivot high.")
showEql = input.bool(true, "EQL", group = grpEq, inline = "eq", tooltip = "Draws a dotted EQL line and centered EQL label when a newly confirmed pivot low is within 0.10 ATR of the prior confirmed pivot low.")
eqLabelSize = labelSizeFromString(input.string("Tiny", "EQH / EQL Label Size", options = ["Tiny", "Small", "Normal", "Large", "Auto"], group = grpEq, tooltip = "Controls the size of the centered EQH and EQL labels drawn on their dotted equal-pivot lines."))

int swingLen = obPivotLength
bool chartTfAllowed = tfChart and (tfChartSource == "" or timeframe.period == tfChartSource)
bool timeframeAllowed = chartTfAllowed or (tf1h and timeframe.period == tf1hSource) or (tf1w and timeframe.period == tf1wSource)

grpAL = "ALERTS"
alBullOB = input.bool(true, "Bullish Order Block", group = grpAL, inline = "oba", tooltip = "Enables alerts when a bullish order block is detected.")
alBearOB = input.bool(true, "Bearish Order Block", group = grpAL, inline = "oba", tooltip = "Enables alerts when a bearish order block is detected.")
alBullRetest = input.bool(true, "Bullish OB Retest", group = grpAL, inline = "obr", tooltip = "Enables alerts when price retests a bullish order block.")
alBearRetest = input.bool(true, "Bearish OB Retest", group = grpAL, inline = "obr", tooltip = "Enables alerts when price retests a bearish order block.")

type ObRec
    int leftIndex
    int leftTime
    int createdIndex
    int createdTime
    float top
    float bottom
    bool isBull
    bool active
    bool retested
    int retestIndex
    int retestTime
    int invalidIndex
    int invalidTime
    float bullVol
    float bearVol
    float totalVol
    float bullPct
    float bearPct
    float poc
    bool hasDelta

type RetestRec
    int barIndex
    bool isBull
    int obLeftIndex
    int obCreatedIndex

type FvgRec
    int leftIndex
    float top
    float bottom
    bool isBull
    bool active
    bool isInversion

type BosRec
    int startIndex
    int endIndex
    int startTime
    int endTime
    float level
    bool isBull

type EqRec
    int startIndex
    int endIndex
    int startTime
    int endTime
    float level
    bool isHigh

method clearAll(array<box> bx, array<label> lb) =>
    if bx.size() > 0
        for i = 0 to bx.size() - 1
            bx.get(i).delete()
    bx.clear()
    if lb.size() > 0
        for i = 0 to lb.size() - 1
            lb.get(i).delete()
    lb.clear()

touchesZone(float zTop, float zBot, float cHigh, float cLow) =>
    cHigh >= zBot and cLow <= zTop

zoneDistance(float px, float zTop, float zBot) =>
    px > zTop ? px - zTop : px < zBot ? zBot - px : 0.0

method insertBest(array<float> dists, array<int> idxs, float dist, int idx, int kMax) =>
    if dists.size() == 0
        dists.push(dist)
        idxs.push(idx)
    else
        int pos = dists.size()
        if dists.size() > 0
            for j = 0 to dists.size() - 1
                if dist < dists.get(j)
                    pos := j
                    break
        dists.insert(pos, dist)
        idxs.insert(pos, idx)
    while dists.size() > kMax
        dists.pop()
        idxs.pop()

pickNearest(array<ObRec> store, bool wantBull, int kMax, bool includeInvalid) =>
    array<float> dists = array.new_float()
    array<int> idxs = array.new_int()
    if store.size() > 0
        for i = 0 to store.size() - 1
            ObRec ob = store.get(i)
            bool dominantOk = wantBull ? ob.bullPct >= dominantPctMin : ob.bearPct >= dominantPctMin
            if ob.isBull == wantBull and dominantOk
                bool ok = includeInvalid ? true : ob.active
                if ok
                    float dist = zoneDistance(close, ob.top, ob.bottom)
                    dists.insertBest(idxs, dist, i, kMax)
    idxs

formatVol(float v) =>
    str.tostring(v, format.volume)

tfSec(string tf) =>
    timeframe.in_seconds(tf)

int chartSec = tfSec(timeframe.period)
int srcSec = tfSec(vdTfIn)
bool useLtf = not na(chartSec) and not na(srcSec) and srcSec < chartSec

getBarVols() =>
    float tot = na
    float bull = na
    float bear = na
    if not useLtf or vdTfIn == ""
        float v = volume
        bool up = close > open
        bool dn = close < open
        tot := v
        bull := up ? v : 0.0
        bear := dn ? v : 0.0
    else
        array<float> oArr = request.security_lower_tf(syminfo.tickerid, vdTfIn, open)
        array<float> cArr = request.security_lower_tf(syminfo.tickerid, vdTfIn, close)
        array<float> vArr = request.security_lower_tf(syminfo.tickerid, vdTfIn, volume)
        float tSum = 0.0
        float bSum = 0.0
        float sSum = 0.0
        int n = array.size(vArr)
        if n > 0
            for i = 0 to n - 1
                float v2 = array.get(vArr, i)
                float o2 = array.get(oArr, i)
                float c2 = array.get(cArr, i)
                tSum += v2
                if c2 > o2
                    bSum += v2
                else if c2 < o2
                    sSum += v2
        tot := tSum
        bull := bSum
        bear := sSum
    [tot, bull, bear]

[barTotVol, barBullVol, barBearVol] = getBarVols()

findMostTouchedPrice(int fromIdx, int toIdx, int nBins) =>
    int span = toIdx - fromIdx
    if span <= 0 or na(fromIdx) or na(toIdx)
        [na, 0]
    else
        float minP = 1e10
        float maxP = -1e10
        for idx = fromIdx to toIdx
            int rel = bar_index - idx
            if rel >= 0
                float lo = low[rel]
                float hi = high[rel]
                if not na(lo) and not na(hi)
                    if lo < minP
                        minP := lo
                    if hi > maxP
                        maxP := hi
        if not (minP < maxP)
            [na, 0]
        else
            float step = (maxP - minP) / nBins
            step := step <= 0 ? syminfo.mintick : step
            array<float> diffCnt = array.new_float(nBins, 0.0)
            for idx = fromIdx to toIdx
                int rel2 = bar_index - idx
                if rel2 >= 0
                    float lo2 = low[rel2]
                    float hi2 = high[rel2]
                    if not na(lo2) and not na(hi2)
                        int sBin = int(math.floor((lo2 - minP) / step))
                        int eBin = int(math.floor((hi2 - minP) / step))
                        sBin := sBin < 0 ? 0 : sBin > nBins - 1 ? nBins - 1 : sBin
                        eBin := eBin < 0 ? 0 : eBin > nBins - 1 ? nBins - 1 : eBin
                        float cStart = diffCnt.get(sBin)
                        diffCnt.set(sBin, cStart + 1.0)
                        if eBin + 1 < nBins
                            float cEnd = diffCnt.get(eBin + 1)
                            diffCnt.set(eBin + 1, cEnd - 1.0)
            int   bestBin = 0
            float bestCnt = 0.0
            float runCnt = 0.0
            for i = 0 to nBins - 1
                runCnt += diffCnt.get(i)
                if runCnt > bestCnt
                    bestCnt := runCnt
                    bestBin := i
            float poc = minP + (bestBin + 0.5) * step
            [poc, int(bestCnt)]

volumeAtPrice(int fromIdx, int toIdx, float poc) =>
    int   touches = 0
    float totVol = 0.0
    float bullVol = 0.0
    float bearVol = 0.0
    int span = toIdx - fromIdx
    if not na(poc) and span >= 0
        for step = 0 to span
            int idx = toIdx - step
            int rel = bar_index - idx
            if rel >= 0
                float lo = low[rel]
                float hi = high[rel]
                if not na(lo) and not na(hi) and lo <= poc and hi >= poc
                    touches += 1
                    float vTot = barTotVol[rel]
                    float vBull = barBullVol[rel]
                    float vBear = barBearVol[rel]
                    if not na(vTot)
                        totVol += vTot
                    if not na(vBull)
                        bullVol += vBull
                    if not na(vBear)
                        bearVol += vBear
    [touches, totVol, bullVol, bearVol]

calcMostTouchedPriceVol(int fromIdx, int toIdx, int nBins) =>
    [poc, _approxTouches] = findMostTouchedPrice(fromIdx, toIdx, nBins)
    [touches, totVol, bullVol, bearVol] = volumeAtPrice(fromIdx, toIdx, poc)
    [poc, touches, totVol, bullVol, bearVol]

var array<ObRec> obs = array.new<ObRec>()
var array<RetestRec> obRetests = array.new<RetestRec>()

var int lastBullRetestBar = na
var int lastBearRetestBar = na

var float shPrice = na
var int   shIdx = na
var int   shTime = na
var float slPrice = na
var int   slIdx = na
var int   slTime = na

bool evNewBullOB = false
bool evNewBearOB = false
bool evBullRetest = false
bool evBearRetest = false

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

if not na(ph)
    shPrice := ph
    shIdx := bar_index - swingLen
    shTime := time[swingLen]

if not na(pl)
    slPrice := pl
    slIdx := bar_index - swingLen
    slTime := time[swingLen]

bool bosBearNow = not na(slPrice) and bar_index > slIdx and close < slPrice and close[1] >= slPrice
bool bosBullNow = not na(shPrice) and bar_index > shIdx and close > shPrice and close[1] <= shPrice

bool bosBear = bosBearNow[1]
bool bosBull = bosBullNow[1]

var array<BosRec> bosRecords = array.new<BosRec>()
if bosBull and not na(shIdx[1]) and not na(shPrice[1])
    bosRecords.unshift(BosRec.new(shIdx[1], bar_index, shTime[1], time, shPrice[1], true))
if bosBear and not na(slIdx[1]) and not na(slPrice[1])
    bosRecords.unshift(BosRec.new(slIdx[1], bar_index, slTime[1], time, slPrice[1], false))
while bosRecords.size() > 100
    bosRecords.pop()

int bosIdxBear = bar_index - 1
int fromIdxBear = slIdx[1]
int toIdxBear = bosIdxBear
[pocB, touchesB, totVolB, bullVolB, bearVolB] = calcMostTouchedPriceVol(fromIdxBear, toIdxBear, 40)

int bosIdxBull = bar_index - 1
int fromIdxBull = shIdx[1]
int toIdxBull = bosIdxBull
[pocH, touchesH, totVolH, bullVolH, bearVolH] = calcMostTouchedPriceVol(fromIdxBull, toIdxBull, 40)

pruneObs() =>
    int minLeft = math.max(0, bar_index - 4999)
    if obs.size() > 0
        for i = obs.size() - 1 to 0
            ObRec ob = obs.get(i)
            if ob.leftIndex < minLeft
                obs.remove(i)
    while obs.size() > MAX_STORED_OBS
        bool removed = false
        if obs.size() > 0
            for j = obs.size() - 1 to 0
                ObRec ob2 = obs.get(j)
                if not ob2.active
                    obs.remove(j)
                    removed := true
                    break
        if not removed and obs.size() > 0
            obs.pop()

addObFromPoc(int baseIdx, float top, float bottom, bool isBull, float totSeed, float bullSeed, float bearSeed, float pocSeed, int createdIdx) =>
    int offLeft = bar_index - baseIdx
    int offCreated = bar_index - createdIdx
    int leftTime = time[offLeft]
    int createdTm = time[offCreated]
    float tot = totSeed
    float bVol = bullSeed
    float sVol = bearSeed
    bool hasDelta = tot > 0.0
    float bullPct = hasDelta ? math.round((bVol / tot) * 100.0) : 50.0
    float bearPct = hasDelta ? 100.0 - bullPct : 50.0
    obs.unshift(ObRec.new(baseIdx, leftTime, createdIdx, createdTm, top, bottom, isBull,
     true, false, na, na, na, na, bVol, sVol, tot, bullPct, bearPct, pocSeed, hasDelta))
    pruneObs()

obOverlapsActive(float zoneTop, float zoneBottom) =>
    float zTop = math.max(zoneTop, zoneBottom)
    float zBot = math.min(zoneTop, zoneBottom)
    bool overlaps = false
    if obs.size() > 0
        for i = 0 to obs.size() - 1
            ObRec ob = obs.get(i)
            if ob.active
                float oTop = math.max(ob.top, ob.bottom)
                float oBot = math.min(ob.top, ob.bottom)
                bool rangeOverlap = zTop >= oBot and zBot <= oTop
                if rangeOverlap
                    overlaps := true
                    break
    overlaps

hasGapBetween(int anchorIdx, int bosIdx, bool isBull) =>
    bool gap = false
    int fromIdx = math.min(anchorIdx, bosIdx)
    int toIdx = math.max(anchorIdx, bosIdx)
    if toIdx - fromIdx >= 1
        for absIdx = fromIdx + 1 to toIdx
            int relNow = bar_index - absIdx
            int relPrev = relNow + 1  
            if relNow >= 0 and relPrev >= 0
                float hiPrev = high[relPrev]
                float loPrev = low[relPrev]
                float hiNow = high[relNow]
                float loNow = low[relNow]
                if

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