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

FVG Volume Profiles PRO

indicator fair value gap profiles for tradingview.pine
Вы автор или правообладатель?

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

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

О программе

FVG Volume Profiles PRO — индикатор для TradingView, который выявляет зоны справедливой стоимости (Fair Value Gap) на графике и отображает объёмные профили для каждой обнаруженной зоны. Индикатор анализирует трёхсвечные паттерны разрывов цены и использует данные нижнего таймфрейма для построения детализированных профилей объёма внутри каждой зоны.

Зоны FVG могут быть бычьими или медвежьими, их отображение и фильтрация настраиваются пользователем. Индикатор поддерживает правила митигации — автоматическое закрытие зоны при достижении цены определённого уровня. Доступны два режима: полное заполнение и первое касание.

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

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

НастройкаОписание
sampleLength Количество последних наблюдений ширины разрывов, используемых для расчёта средней ширины при определении порога обнаружения FVG.
gapMultiplier Множитель, на который умножается средняя ширина ранее наблюдавшихся разрывов для определения порога обнаружения новой зоны FVG.
maxAge Максимальное количество баров, в течение которого активная зона FVG остаётся на графике до автоматического удаления.
maxZones Максимальное количество одновременно отображаемых зон FVG на графике. При превышении удаляется самая старая зона.
preventOverlap При включении предотвращает создание новой зоны FVG, если она пересекается с существующей активной зоной.
enableBull Включает или отключает отображение бычьих зон FVG на графике.
enableBear Включает или отключает отображение медвежьих зон FVG на графике.
mitigationMode Правило закрытия (митигации) активной зоны: «Full Fill» — зона закрывается при достижении цены её границы, «First Touch» — зона закрывается при касании средней точки.
lowerTF Нижний таймфрейм, с которого берутся данные о ценах и объёмах для построения объёмного профиля внутри зоны FVG.
bins Количество корзин (сегментов), на которые делится объёмный профиль внутри каждой зоны FVG.
lowWindow Размер окна (в корзинах) для поиска зоны с наименьшим суммарным объёмом внутри профиля.
profileScale Коэффициент, определяющий пропорциональную ширину коробок объёмного профиля относительно ширины зоны.
minimumBoxWidth Минимальная ширина в барах для коробок объёмного профиля, обеспечивающая видимость даже при малом объёме.
showGap Отображает или скрывает основную полупрозрачную коробку зоны FVG на графике.
showProfile Отображает или скрывает коробки объёмного профиля внутри зоны FVG.
showLow Отображает или скрывает выделенную зону с наименьшим объёмом внутри профиля FVG.
showTotalNumbers Отображает общий суммарный объём внутри зоны FVG в виде числовой подписи.
showEachNumber Отображает числовое значение объёма внутри каждой коробки объёмного профиля.
showZeroBins Отображает или скрывает пустые корзины объёмного профиля (с нулевым объёмом).
bullishColor Цвет отображения бычьих зон FVG и связанных элементов профиля.
bearishColor Цвет отображения медвежьих зон FVG и связанных элементов профиля.

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

indicator("FVG Volume Profiles PRO", shorttitle="FVG PRO", overlay=true, max_boxes_count=450)

int sampleLength = input.int(50, "Average Gap Sample", minval=1, maxval=500, group="FVG Detection")
float gapMultiplier = input.float(1.5, "Gap Size Multiplier", minval=0.1, step=0.1, group="FVG Detection")
int maxAge = input.int(1000, "Expire After Bars", minval=1, maxval=10000, group="FVG Detection")
int maxZones = input.int(25, "Maximum FVG Zones", minval=1, maxval=35, group="FVG Detection")
bool preventOverlap = input.bool(true, "Prevent Active Zone Overlap", group="FVG Detection")
bool enableBull = input.bool(true, "Show Bullish FVG", group="FVG Detection")
bool enableBear = input.bool(true, "Show Bearish FVG", group="FVG Detection")
string mitigationMode = input.string("Full Fill", "Mitigation Rule", options=["Full Fill", "First Touch"], group="FVG Detection")

string lowerTF = input.timeframe("1", "Profile Lower Timeframe", group="Volume Profile")
int bins = input.int(7, "Profile Bins", minval=1, maxval=8, group="Volume Profile")
int lowWindow = input.int(2, "Low Volume Window", minval=1, maxval=8, group="Volume Profile")
float profileScale = input.float(0.5, "Profile Width Ratio", minval=0.1, maxval=0.9, step=0.1, group="Volume Profile")
int minimumBoxWidth = input.int(4, "Minimum Profile Width (bars)", minval=1, maxval=20, group="Volume Profile")

bool showGap = input.bool(true, "Show Main FVG Box", group="Appearance")
bool showProfile = input.bool(true, "Show Volume Profile Boxes", group="Appearance")
bool showLow = input.bool(true, "Show Low Volume Zone", group="Appearance")
bool showTotalNumbers = input.bool(true, "Show Total Volume Number", group="Appearance")
bool showEachNumber = input.bool(true, "Show Number Inside Every Profile Box", group="Appearance")
bool showZeroBins = input.bool(true, "Show Empty Profile Bins (0)", group="Appearance")
color bullishColor = input.color(#00ffbb, "Bullish Color", group="Appearance")
color bearishColor = input.color(#ff3355, "Bearish Color", group="Appearance")

[ltfCloses, ltfVolumes] = request.security_lower_tf(syminfo.tickerid, lowerTF, [close, volume])

var array<float> previousGapSizes = array.new_float()
var array<box> mainBoxes = array.new<box>()
var array<box> lowBoxes = array.new<box>()
var array<float> tops = array.new_float()
var array<float> bottoms = array.new_float()
var array<int> starts = array.new_int()
var array<int> ends = array.new_int() // -1 = active
var array<int> directions = array.new_int()
var array<box> binBoxes = array.new<box>()
var array<float> binVolumes = array.new_float()

f_remove_zone(int index) =>
    box.delete(array.remove(mainBoxes, index))
    box lowBox = array.remove(lowBoxes, index)
    if not na(lowBox)
        box.delete(lowBox)
    array.remove(tops, index)
    array.remove(bottoms, index)
    array.remove(starts, index)
    array.remove(ends, index)
    array.remove(directions, index)
    for j = bins - 1 to 0
        int flatIndex = index * bins + j
        box item = array.remove(binBoxes, flatIndex)
        if not na(item)
            box.delete(item)
        array.remove(binVolumes, flatIndex)

f_overlap(float top, float bottom) =>
    bool found = false
    if array.size(mainBoxes) > 0
        for i = 0 to array.size(mainBoxes) - 1
            if array.get(ends, i) == -1 and top > array.get(bottoms, i) and bottom < array.get(tops, i)
                found := true
                break
    found

bool rawBull = bar_index >= 2 and low > high[2]
bool rawBear = bar_index >= 2 and high < low[2]
float gapWidth = rawBull ? low - high[2] : rawBear ? low[2] - high : na

float avgGap = array.size(previousGapSizes) > 0 ? array.avg(previousGapSizes) : na
bool bullishFVG = barstate.isconfirmed and enableBull and rawBull and not na(avgGap) and gapWidth > avgGap * gapMultiplier
bool bearishFVG = barstate.isconfirmed and enableBear and rawBear and not na(avgGap) and gapWidth > avgGap * gapMultiplier
bool bullishMitigation = false
bool bearishMitigation = false

if array.size(mainBoxes) > 0
    for i = array.size(mainBoxes) - 1 to 0
        float top = array.get(tops, i)
        float bottom = array.get(bottoms, i)
        int created = array.get(starts, i)
        int finished = array.get(ends, i)
        int direction = array.get(directions, i)
        if barstate.isconfirmed and finished == -1 and bar_index > created
            bool filled = mitigationMode == "Full Fill" ? (direction == 1 ? low <= bottom : high >= top) : (direction == 1 ? low <= top : high >= bottom)
            if filled
                finished := bar_index
                array.set(ends, i, finished)
                bullishMitigation := bullishMitigation or direction == 1
                bearishMitigation := bearishMitigation or direction == -1
        if bar_index - created > maxAge
            f_remove_zone(i)
        else
            int rightEdge = finished == -1 ? bar_index : finished
            box.set_right(array.get(mainBoxes, i), math.max(created + 1, rightEdge))
            box lowBox = array.get(lowBoxes, i)
            if not na(lowBox)
                box.set_right(lowBox, math.max(created + 1, rightEdge))
            float maximumVol = 0.0
            for j = 0 to bins - 1
                maximumVol := math.max(maximumVol, array.get(binVolumes, i * bins + j))
            for j = 0 to bins - 1
                int pos = i * bins + j
                box b = array.get(binBoxes, pos)
                if not na(b)
                    float value =

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