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

Range Profile Structure

indicator range profile structure for tradingview.pine
Вы автор или правообладатель?

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

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

О программе

Range Profile Structure — индикатор для TradingView, который автоматически обнаруживает диапазоны консолидации на графике цены и отображает внутри них профиль объёмов. В основе работы лежит движок свинг-точек: индикатор ищет локальные максимумы и минимумы, затем анализирует чередование этих точек для подтверждения диапазона. Для формирования диапазона требуется минимальное количество касаний верхней и нижней границ, определённое число вращений между ними, а также ограничения по ширине и стабильности, заданные в параметрах.

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

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

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

НастройкаОписание
swingLen Количество баров с каждой стороны, необходимых для подтверждения свинг-хай или свинг-лоу, используемых для обнаружения диапазонов.
swingMemory Количество последних чередующихся свинг-точек, сохраняемых и оцениваемых для обнаружения диапазонов. Последовательные свинги на одной стороне объединяются в более экстремальную.
atrLen Количество баров для расчёта среднего истинного диапазона (ATR), используемого для ограничений ширины диапазона, стабильности границ и буфера пробития.
minTouches Минимальное количество свинг-высоких и свинг-низких точек, необходимых для формирования диапазона на каждой границе.
minRotations Минимальное количество чередующихся свингов между верхней и нижней границами диапазона, необходимых для подтверждения диапазона.
minRangeBars Минимальное количество баров между самой старой и самой новой свинг-точкой в кандидате на диапазон.
clusterATR Допуск в долях ATR для того, насколько плотно свинги должны кластеризоваться для формирования границы. Также определяет, насколько близко новая свинг-точка должна быть к активной границе, чтобы засчитаться как касание.
minWidthATR Минимальная высота диапазона в долях ATR. Диапазоны за пределами этого лимита игнорируются.
maxWidthATR Максимальная высота диапазона в долях ATR. Диапазоны за пределами этого лимита игнорируются.
edgeAdapt Насколько активная граница диапазона сдвигается к каждой новой свинг-точке, касающейся её. Значение 0 оставляет границы фиксированными после обнаружения.
maxRangeAge Максимальное количество баров, в течение которых диапазон остаётся активным, прежде чем быть закрытым без пробития. Значение 0 отключает ограничение.
showProfile Включает или отключает видимость профиля объёмов внутри каждого диапазона.
profileBins Количество горизонтальных строк, на которые распределяется объём внутри диапазона. Большее значение даёт более детальный профиль.
profileWidth Ширина строки с наибольшим объёмом профиля в процентах от длины диапазона в барах. Остальные строки масштабируются относительно неё.
showPOC Включает или отключает линию на ценовой строке с наибольшим объёмом торгов внутри диапазона (точка контроля).
breakBuffer Расстояние за пределами границы диапазона в долях ATR, которое цена должна закрыть, чтобы считаться за пределами диапазона.
breakCloses Количество последовательных закрытий за пределами буфера пробития, необходимых для подтверждения пробития или пробоя вниз.
showBreakLabel Включает или отключает метки BREAKOUT и BREAKDOWN на подтверждённых пробитиях диапазона.
showDeviations Включает или отключает ромбовидные маркеры на экстремумах движений, которые закрылись за пределами диапазона и затем вернулись внутрь.
deviationHistory Максимальное количество маркеров отклонений, сохраняемых на графике. Самый старый маркер удаляется первым.
showPosition Включает или отключает инструмент позиции, отрисуемый при каждом подтверждённом пробитии, с входом на пробитой границе и стоп-лоссом на противоположной границе.
positionBars Количество баров, на которое инструмент позиции простирается вперёд от бара пробития.
tp1Mult Расстояние первого тейк-профита от входа в долях высоты диапазона.
tp2Mult Расстояние второго тейк-профита от входа в долях высоты диапазона.
tp3Mult Расстояние третьего тейк-профита от входа в долях высоты диапазона.
showPositionLabels Включает или отключает метки ENTRY, SL, TP1, TP2 и TP3 на инструменте позиции.
gradientRows Количество слоёв, используемых для отрисовки градиента диапазона. Большее значение даёт более плавное затухание.
historyCount Количество завершённых диапазонов, сохраняемых на графике. Самый старый диапазон удаляется первым.
paintCandles Включает или отключает раскрашивание свечей во время активности диапазона. Свечи меняют цвет от бычьего у нижней границы к медвежьему у верхней и получают полный цвет при закрытии за пределами диапазона.
candleTransparency Прозрачность, применяемая к свечам, раскрашенным внутри активного диапазона.
showMidline Включает или отключает пунктирную линию по середине каждого диапазона (уровень равновесия).
cooldownBars Количество баров ожидания после разрешения диапазона, прежде чем новый диапазон может быть обнаружен.
rangeCol Цвет для профиля активного диапазона, цвета свечей в средней части диапазона и диапазонов, закрывающихся без пробития.
bullCol Цвет для бычьей части диапазона (нижняя половина и восходящие пробития), границ, градиентов, отклонений и свечей.
bearCol Цвет для медвежьей части диапазона (верхняя половина и нисходящие пробития), границ, градиентов, отклонений и свечей.

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

indicator("Range Profile Structure", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count=500, max_bars_back=2000)

const string g1 = "Swing Engine"
const string g2 = "Range Detection"
const string g3 = "Volume Profile"
const string g4 = "Breakout Structure"
const string g5 = "Position Tool"
const string g6 = "Display"

const color BULL = #00FF66
const color BEAR = #FF0066
const color RANGE = #A0A0A0

int swingLen            = input.int(5, "Swing Length", minval = 2, maxval = 30, group = g1,
     tooltip = "Number of bars on each side required to confirm a swing high or low used to detect ranges.")
int swingMemory         = input.int(10, "Swing Memory", minval = 4, maxval = 20, group = g1,
     tooltip = "Number of recent alternating swing points stored and evaluated for range detection. Consecutive swings on the same side merge into the more extreme one.")
int atrLen              = input.int(14, "ATR Length", minval = 2, group = g1,
     tooltip = "Number of bars used to calculate the Average True Range, used for range width limits, edge stability, and the break buffer.")

int minTouches          = input.int(2, "Touches Per Edge", minval = 2, maxval = 5, group = g2,
     tooltip = "Minimum number of swing highs and swing lows each required to form a range.")
int minRotations        = input.int(3, "Minimum Rotations", minval = 3, maxval = 10, group = g2,
     tooltip = "Minimum number of alternating swings between the range high and range low required before a range is confirmed.")
int minRangeBars        = input.int(8, "Minimum Range Span", minval = 3, maxval = 100, group = g2,
     tooltip = "Minimum number of bars between the oldest and newest swing in a range candidate.")
float clusterATR        = input.float(0.30, "Edge Stability ATR", minval = 0.05, maxval = 1.0, step = 0.05, group = g2,
     tooltip = "Tolerance, as a multiple of ATR, for how tightly swings must cluster to form an edge. Also sets how close a new swing must be to an active edge to count as a touch.")
float minWidthATR       = input.float(1.0, "Minimum Width ATR", minval = 0.25, maxval = 5.0, step = 0.25, inline = "W", group = g2,
     tooltip = "Minimum and maximum range height, as multiples of ATR. Ranges outside these limits are ignored.")
float maxWidthATR       = input.float(6.0, "Maximum", minval = 1.0, maxval = 15.0, step = 0.25, inline = "W", group = g2,
     tooltip = "Minimum and maximum range height, as multiples of ATR. Ranges outside these limits are ignored.")
float edgeAdapt         = input.float(0.20, "Edge Adaptation", minval = 0.0, maxval = 0.50, step = 0.05, group = g2,
     tooltip = "How far an active range edge shifts toward each new swing that touches it. A value of 0 keeps the edges fixed after detection.")
int maxRangeAge         = input.int(0, "Maximum Range Age", minval = 0, maxval = 2000, group = g2,
     tooltip = "Maximum number of bars a range stays active before it is closed without a breakout. A value of 0 disables the limit.")

bool showProfile        = input.bool(true, "Range Volume Profile", group = g3,
     tooltip = "Toggles visibility of the volume profile inside each range.")
int profileBins         = input.int(14, "Profile Rows", minval = 8, maxval = 16, group = g3,
     tooltip = "Number of horizontal rows the range volume is distributed into. Higher values produce a more detailed profile.")
int profileWidth        = input.int(40, "Profile Width %", minval = 15, maxval = 60, group = g3,
     tooltip = "Width of the highest-volume profile row, as a percentage of the range's length in bars. Other rows scale relative to it.")
bool showPOC            = input.bool(true, "Point of Control", group = g3,
     tooltip = "Toggles the line at the price row with the highest traded volume inside the range.")

float breakBuffer       = input.float(0.10, "Break Buffer ATR", minval = 0.0, maxval = 2.0, step = 0.05, group = g4,
     tooltip = "Distance beyond the range edge, as a multiple of ATR, that price must close to count as outside the range.")
int breakCloses         = input.int(2, "Break Acceptance Closes", minval = 1, maxval = 5, group = g4,
     tooltip = "Number of consecutive closes beyond the break buffer required to confirm a breakout or breakdown.")
bool showBreakLabel     = input.bool(true, "Breakout Tag", group = g4,
     tooltip = "Toggles the BREAKOUT and BREAKDOWN labels on confirmed range breaks.")
bool showDeviations     = input.bool(true, "Range Deviations", group = g4,
     tooltip = "Toggles diamond markers at the extreme of moves that closed outside the range and then closed back inside.")
int deviationHistory    = input.int(30, "Deviation History", minval = 5, maxval = 100, group = g4,
     tooltip = "Maximum number of deviation markers kept on the chart. The oldest marker is removed first.")

bool showPosition       = input.bool(true, "Breakout Position Tool", group = g5,
     tooltip = "Toggles the position tool drawn on each confirmed breakout, with entry at the broken edge and stop at the opposite edge.")
int positionBars        = input.int(10, "Position Width", minval = 3, maxval = 40, group = g5,
     tooltip = "Number of bars the position tool extends forward from the breakout bar.")
float tp1Mult           = input.float(0.50, "TP1", minval = 0.10, maxval = 3.0, step = 0.10, inline = "TP", group = g5,
     tooltip = "Take profit distances from entry, as multiples of the range height.")
float tp2Mult           = input.float(1.00, "TP2", minval = 0.10, maxval = 4.0, step = 0.10, inline = "TP", group = g5,
     tooltip = "Take profit distances from entry, as multiples of the range height.")
float tp3Mult           = input.float(2.00, "TP3", minval = 0.10, maxval = 5.0, step = 0.10, inline = "TP", group = g5,
     tooltip = "Take profit distances from entry, as multiples of the range height.")
bool showPositionLabels = input.bool(true, "Position Labels", group = g5,
     tooltip = "Toggles the ENTRY, SL, TP1, TP2, and TP3 labels on the position tool.")

int gradientRows        = input.int(22, "Gradient Smoothness", minval = 12, maxval = 24, group = g6,
     tooltip = "Number of layers used to draw the range gradient. Higher values produce a smoother fade.")
int historyCount        = input.int(10, "Completed Ranges", minval = 1, maxval = 10, group = g6,
     tooltip = "Number of completed ranges kept on the chart. The oldest range is removed first.")
bool paintCandles       = input.bool(true, "Range Candle Colors", group = g6,
     tooltip = "Toggles candle coloring while a range is active. Candles shift from the bullish color near the range low to the bearish color near the range high, and take the full color once they close outside the range.")
int candleTransparency  = input.int(10, "Candle Transparency", minval = 0, maxval = 70, group = g6,
     tooltip = "Transparency applied to candles colored inside an active range.")
bool showMidline        = input.bool(false, "Equilibrium", group = g6,
     tooltip = "Toggles the dotted line at the midpoint of each range.")
int cooldownBars        = input.int(4, "New Range Cooldown", minval = 0, maxval = 50, group = g6,
     tooltip = "Number of bars to wait after a range resolves before a new range can be detected.")
color rangeCol          = input.color(RANGE, "Profile", group = g6,
     tooltip = "Color used for the active range profile, the candle color at mid-range, and ranges that close without a breakout.")
color bullCol           = input.color(BULL, "Bullish", inline = "COL", group = g6,
     tooltip = "Colors used for range edges, gradients, breakouts, deviations, and candles. Bullish applies to the lower half and upward breaks, Bearish to the upper half and downward breaks.")
color bearCol           = input.color(BEAR, "Bearish", inline = "COL", group = g6,
     tooltip = "Colors used for range edges, gradients, breakouts, deviations, and candles. Bullish applies to the lower half and upward breaks, Bearish to the upper half and downward breaks.")

type RangeDraw
    box shell
    array<box> gradient
    array<box> profile
    line upper
    line lower
    line middle
    line poc
    label breakTag
    box rewardBox
    box riskBox
    line entryLine
    line stopLine
    line tp1Line
    line tp2Line
    line tp3Line
    label entryTag
    label stopTag
    label tp1Tag
    label tp2Tag
    label tp3Tag

var array<float> swingPrice = array.new_float()
var array<int> swingBar = array.new_int()
var array<int> swingSide = array.new_int()
var array<float> rangeProfile = array.new_float()
var array<RangeDraw> history = array.new<RangeDraw>()
var array<label> deviationMarks = array.new<label>()

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

f_add_swing(array<float> prices, array<int> bars, array<int> sides, float price, int bi, int side) =>
    if prices.size() > 0 and sides.get(0) == side
        bool replace = side == 1 ? price >= prices.get(0) : price <= prices.get(0)
        if replace
            prices.set(0, price)
            bars.set(0, bi)
    else
        prices.unshift(price)
        bars.unshift(bi)
        sides.unshift(side)

    while prices.size() > swingMemory
        prices.pop()
        bars.pop()
        sides.pop()
    true

f_find_range(array<float> prices, array<int> bars, array<int> sides, float atrValue) =>
    bool found = false
    float bestTop = na
    float bestBottom = na
    int bestLeft = na
    int bestHighTouches = 0
    int bestLowTouches = 0
    int n = prices.size()
    int minEvents = math.max(minTouches * 2, minRotations + 1)
    float tolerance = atrValue * clusterATR

    if n >= minEvents and atrValue > 0
        for count = minEvents to n
            float highSum = 0.0
            float lowSum = 0.0
            float highMin = na
            float highMax = na
            float lowMin = na
            float lowMax = na
            int highCount = 0
            int lowCount = 0
            int oldest = bar_index
            int newest = 0

            for i = 0 to count - 1
                float p = prices.get(i)
                int bi = bars.get(i)
                int side = sides.get(i)

                oldest := math.min(oldest, bi)
                newest := math.max(newest, bi)

                if side == 1
                    highSum += p
                    highCount += 1
                    highMin := na(highMin) ? p : math.min(highMin, p)
                    highMax := na(highMax) ? p : math.max(highMax, p)
                else
                    lowSum += p
                    lowCount += 1
                    lowMin := na(lowMin) ? p : math.min(lowMin, p)
                    lowMax := na(lowMax) ? p : math.max(lowMax, p)

            if highCount >= minTouches and lowCount >= minTouches
                float top = highSum / highCount
                float bottom = lowSum / lowCount
                float width = top - bottom
                bool stable = highMax - highMin <= tolerance * 2.0 and lowMax - lowMin <= tolerance * 2.0
                bool widthOK = width >= atrValue * minWidthATR and width <= atrValue * math.max(maxWidthATR, minWidthATR)
                bool spanOK = newest - oldest >= minRangeBars
                bool rotationsOK = count - 1 >= minRotations

                if top > bottom and stable and widthOK and spanOK and rotationsOK
                    found := true
                    bestTop := top
                    bestBottom := bottom
                    bestLeft := oldest
                    bestHighTouches := highCount
                    bestLowTouches := lowCount

    [found, bestTop, bestBottom, bestLeft, bestHighTouches, bestLowTouches]

f_reset_profile(array<float> profile) =>
    profile.clear()
    for i = 0 to profileBins - 1
        profile.push(0.0)
    true

f_add_profile_bar(array<float> profile, float barLow, float barHigh, float barVolume, float bottom, float top) =>
    float height = top - bottom

    if height > 0 and barVolume > 0
        if barHigh == barLow
            if barHigh >= bottom and barHigh <= top
                int idx = int(math.floor((barHigh - bottom) / height * profileBins))
                idx := math.max(0, math.min(profileBins - 1, idx))
                profile.set(idx, profile.get(idx) + barVolume)
        else
            float candleSpan = math.max(barHigh - barLow, syminfo.mintick)

            for i = 0 to profileBins - 1
                float binLow = bottom + height * i / profileBins
                float binHigh = bottom + height * (i + 1) / profileBins
                float overlap = math.max(0.0, math.min(barHigh, binHigh) - math.max(barLow, binLow))

                if overlap > 0
                    profile.set(i, profile.get(i) + barVolume * overlap / candleSpan)
    true

f_rebuild_profile(array<float> profile, int left, float top, float bottom) =>
    f_reset_profile(profile)
    int span = math.min(bar_index - left, 1500)

    if span >= 0
        for i = 0 to span
            f_add_profile_bar(profile, low[i], high[i], nz(volume[i], 0.0), bottom, top)
    true

f_new_range(int left, float top, float bottom) =>
    box shell = box.new(left, top, bar_index, bottom, xloc=xloc.bar_index, border_color=na, bgcolor=na)
    array<box> gradient = array.new<box>()
    array<box> profile = array.new<box>()

    for i = 0 to gradientRows - 1
        gradient.push(box.new(left, top, bar_index, bottom, xloc=xloc.bar_index, border_color=na, bgcolor=na))

    for i = 0 to profileBins - 1
        profile.push(box.new(left, top, left, bottom, xloc=xloc.bar_index, border_color=na, bgcolor=na))

    line upper = line.new(left, top, bar_index, top, xloc=xloc.bar_index, color=na, width=2)
    line lower = line.new(left, bottom, bar_index, bottom, xloc=xloc.bar_index, color=na, width=2)
    line middle = line.new(left, math.avg(top, bottom), bar_index, math.avg(top, bottom), xloc=xloc.bar_index, color=na, width=1, style=line.style_dotted)
    line poc = line.new(left, math.avg(top, bottom), bar_index, math.avg(top, bottom), xloc=xloc.bar_index, color=na, width=2)

    RangeDraw.new(shell, gradient, profile, upper, lower, middle, poc, na, na, na, na, na, na, na, na, na, na, na, na)

f_delete_range(RangeDraw d) =>
    box.delete(d.shell)
    box.delete(d.rewardBox)
    box.delete(d.riskBox)

    if d.gradient.size() > 0
        fo

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