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

Order Blocks FVG & BOS

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

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

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

О программе

Order Blocks FVG & BOS — это индикатор для TradingView (Pine Script v6), который отображает на графике зоны ордер-блоков, фейр-вол gaps (FVG) и точки пробоя структуры (BOS). Индикатор определяет ордер-блоки на основе POC (Point of Control), привязанного к свечам BOS, с настраиваемой длиной пивота и методами невалидации. Зоны отрисовываются цветными ящиками с возможностью отображения объёмного дельта-анализа.

Индикатор также выявляет фейр-вол gaps (трехсвечные дисбалансы), инверсионные FVG, структурные пробои, а также равные хаи и лоу (EQH/EQL). При совпадении ордер-блока, FVG и BOS формируются конфлюэнтные сигналы LONG/SHORT. Доступны фильтры по таймфреймам и множество оповещений для ключевых событий.

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

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

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

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