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

Support & Resistance Ultra Toolkit

indicator support & resistance ultra toolkit for tradingview.pine
Вы автор или правообладатель?

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

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

О программе

Индикатор «Support & Resistance Ultra Toolkit» предназначен для определения и визуализации зон поддержки и сопротивления на графике TradingView. Он работает как перекрывающий индикатор (overlay), отрисовывая прямоугольные зоны, промежуточные линии и метки прямо на ценовом графике.

Индикатор поддерживает два режима обнаружения зон. В режиме «Pivots» зоны формируются на основе пар близких флектов (swing highs и swing lows), заданных пользователем параметрами длины флектов и максимального разрыва между ними. В режиме «Donchian» зоны создаются при стабильном поведении границ канала на заданном количестве баров.

Для каждой зоны индикатор отслеживает количество касаний, отклонений, завалов (wick sweeps) и пробитий. Зоны имеют настраиваемый срок действия и могут автоматически завершаться при пробитии внешней границы. Панель дашборда отображает статистику по активным зонам: количество целых и расширяющихся зон, расстояние до ближайшей границы, возраст, количество тестов и отклонений, а также оценку вероятности пробития.

Индикатор поддерживает получение данных с более высоких таймфреймов для создания зон, задаёт множество условий оповещений (новые зоны, касания, отклонения, завалы, пробития, истечение срока) и позволяет настраивать цвета, положение панели и видимость элементов интерфейса.

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

НастройкаОписание
showSignals Отображение маркеров отклонений, завалов и пробитий на графике
showZoneLabels Отображение информационных меток с данными об активных зонах рядом с ними
showDashboard Отображение панели статистики с данными о зонах в углу графика
panelPosition Положение панели статистики на графике: верхний правый, нижний правый или нижний левый угол
mode Режим обнаружения зон: Pivots (по флектам) или Donchian (по каналу)
timeHorizon Количество баров по каждой стороне флекта для обнаружения пивотов
pairBars Максимальное количество баров между двумя совпадающими флектами при обнаружении зон по пивотам
matchMult Множитель допустимого ценового разрыва между совпадающими флектами при обнаружении зон по пивотам
donchLength Длина канала для расчёта максимумов и минимумов в режиме обнаружения Donchian
flatBars Количество последовательных баров без изменения границы канала, необходимое для создания зоны в режиме Donchian
expiryBars Количество баров после создания зоны до её автоматического истечения
stopOnBreak Автоматическое завершение зоны при первом закрытии цены за внешней границей зоны
useMTF Использование данных с более высокого таймфрейма для создания зон
zoneTF Таймфрейм для создания зон; должен быть равен или выше таймфрейма графика
bullCol Цвет для зон поддержки и бычьих сигналов
bearCol Цвет для зон сопротивления и медвежьих сигналов

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

indicator("Support & Resistance Ultra Toolkit", "S&R Ultra", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_bars_back = 5000)

generalGR = "General"
showSignals = input.bool(true, "Signals", inline = "display", group = generalGR)
showZoneLabels = input.bool(true, "Zone Labels", inline = "display", group = generalGR, tooltip = "Signals shows rejection, wick-sweep, and breakout triangles. Zone Labels shows live data beside active zones. These switches do not change alerts.")
showDashboard = input.bool(true, "Dashboard", inline = "dashboard", group = generalGR)
panelPosition = input.string("Top Right", "", options = ["Top Right", "Bottom Right", "Bottom Left"], inline = "dashboard", group = generalGR, active = showDashboard, display = display.none, tooltip = "Show the zone table at the selected corner. Historical break estimates need at least 20 completed samples. They are not guaranteed forecasts.")

calcGR = "Calculations"
mode = input.string("Pivots", "Detection Mode", options = ["Pivots", "Donchian"], group = calcGR, display = display.none, tooltip = "Pivots matches two nearby swing highs or lows. Donchian creates zones when a channel edge stays flat.")
timeHorizon = input.int(7, "Pivot Length", minval = 1, maxval = 100, inline = "pivots", group = calcGR, active = mode == "Pivots", display = display.none)
pairBars = input.int(100, "Max Gap", minval = 1, maxval = 2000, inline = "pivots", group = calcGR, active = mode == "Pivots", display = display.none, tooltip = "Pivot Length sets the bars on each side of a swing. Max Gap sets the maximum bars between two matching swings. Both use the zone source timeframe.")
matchMult = input.float(1.0, "Match Tolerance", minval = 0.01, step = 0.05, group = calcGR, active = mode == "Pivots", display = display.none, tooltip = "Higher values allow wider price gaps between matching swings. The limit is this value times the 40-bar standard deviation of source closes.")
donchLength = input.int(30, "Channel Length", minval = 2, maxval = 1000, inline = "donchian", group = calcGR, active = mode == "Donchian", display = display.none)
flatBars = input.int(5, "Flat Bars", minval = 1, maxval = 1000, inline = "donchian", group = calcGR, active = mode == "Donchian", display = display.none, tooltip = "Channel Length sets the high/low lookback. Flat Bars sets how many consecutive source-bar changes must leave the edge unchanged before one zone is created. Zone depth is set automatically.")
expiryBars = input.int(500, "Zone Expiry", minval = 1, maxval = 5000, inline = "life", group = calcGR, display = display.none)
stopOnBreak = input.bool(true, "Stop on Break", inline = "life", group = calcGR, tooltip = "Zone Expiry is the number of chart bars after creation. Stop on Break also stops a zone at the first close through its outer edge. Otherwise, it extends until expiry. Stopped boxes remain on the chart.")
useMTF = input.bool(false, "Higher Timeframe", inline = "mtf", group = calcGR)
zoneTF = input.timeframe("60", "", inline = "mtf", group = calcGR, active = useMTF, display = display.none, tooltip = "Use this timeframe for zone creation only. Select the chart timeframe or higher. Higher-timeframe zones use confirmed source bars. Signals, breaks, age, and expiry still use chart bars.")

appearanceGR = "Appearance"
bullCol = input.color(#00ffbb, "Colours", inline = "colours", group = appearanceGR)
bearCol = input.color(#ff1100, "", inline = "colours", group = appearanceGR, tooltip = "First: support and bullish signals. Second: resistance and bearish signals. Zone shading and solid borders use fixed transparency.")

volLength = 40
donchDepth = 0.5
historyBars = 5000
expiryWarning = 10
minSamples = 20
highRiskThreshold = 70.0
zoneFillTransparency = 60
zoneBorderTransparency = 77
labelOffset = 3
markerMult = 0.15

type PivotPoint
    int idx
    int stamp
    float price
    float o
    float h
    float l
    float c

type Zone
    box bx
    line mid
    label lbl
    float top
    float bottom
    bool isSupport
    int born
    bool extending = true
    int breakAge = na
    int tests = 0
    int rejects = 0
    int sweeps = 0
    float touchVolume = 0.0
    bool wasTouch = false
    bool visitOpen = false
    bool rejectedVisit = false
    bool sweptVisit = false
    bool warned = false

var zones = array.new<Zone>()
var riskSamples = array.new_int((expiryBars + 1) * 2, 0)
var riskBreaks = array.new_int((expiryBars + 1) * 2, 0)
var matureCursor = 0
var lastSourceStamp = int(na)
var firstAllowedBar = math.max(0, last_bar_index - historyBars + 1)

panelAnchor = switch panelPosition
    "Bottom Right" => position.bottom_right
    "Bottom Left" => position.bottom_left
    => position.top_right

textSize = size.small

var dashboard = showDashboard ? table.new(panelAnchor, 3, 16, bgcolor = color.new(chart.bg_color, 5), frame_color = color.new(chart.fg_color, 80), frame_width = 1, border_color = color.new(chart.fg_color, 92), border_width = 1) : na

edgeDistance(isResistance, edge, value) =>
    isResistance ? edge - value : value - edge

includeDistance(currentMax, isResistance, edge, value, tolerance) =>
    distance = edgeDistance(isResistance, edge, value)
    distance >= 0.0 and distance <= tolerance ? math.max(currentMax, distance) : currentMax

zoneThickness(PivotPoint p1, PivotPoint p2, isResistance, tolerance) =>
    edge = isResistance ? math.max(p1.h, p2.h) : math.min(p1.l, p2.l)
    maxDist = math.abs(p1.price - p2.price)
    maxDist := includeDistance(maxDist, isResistance, edge, p1.o, tolerance)
    maxDist := includeDistance(maxDist, isResistance, edge, p1.h, tolerance)
    maxDist := includeDistance(maxDist, isResistance, edge, p1.l, tolerance)
    maxDist := includeDistance(maxDist, isResistance, edge, p1.c, tolerance)
    maxDist := includeDistance(maxDist, isResistance, edge, p2.o, tolerance)
    maxDist := includeDistance(maxDist, isResistance, edge, p2.h, tolerance)
    maxDist := includeDistance(maxDist, isResistance, edge, p2.l, tolerance)
    maxDist := includeDistance(maxDist, isResistance, edge, p2.c, tolerance)
    math.max(maxDist, syminfo.mintick)

zoneBounds(PivotPoint p1, PivotPoint p2, isResistance, tolerance) =>
    edge = isResistance ? math.max(p1.h, p2.h) : math.min(p1.l, p2.l)
    thickness = zoneThickness(p1, p2, isResistance, tolerance)
    top = isResistance ? edge : edge + thickness
    bottom = isResistance ? edge - thickness : edge
    [math.round_to_mintick(top), math.round_to_mintick(bottom)]

pairPivot(array<PivotPoint> memory, PivotPoint current, isResistance, tolerance) =>
    top = float(na)
    bottom = float(na)
    origin = int(na)
    while memory.size() > 0
        oldest = memory.last()
        if current.idx - oldest.idx > pairBars
            memory.pop()
        else
            break
    if not na(tolerance) and memory.size() > 0
        for i = 0 to memory.size() - 1
            previous = memory.get(i)
            gap = current.idx - previous.idx
            if gap > 0 and gap <= pairBars and math.abs(current.price - previous.price) <= tolerance
                [matchedTop, matchedBottom] = zoneBounds(previous, current, isResistance, tolerance)
                top := matchedTop
                bottom := matchedBottom
                origin := previous.stamp
                break
    memory.unshift(current)
    [top, bottom, origin]

sourceZones() =>
    ph = ta.pivothigh(high, timeHorizon, timeHorizon)
    pl = ta.pivotlow(low, timeHorizon, timeHorizon)
    volatility = ta.stdev(close, volLength)
    tolerance = math.max(volatility * matchMult, syminfo.mintick)
    channelHigh = ta.highest(high, donchLength)
    channelLow = ta.lowest(low, donchLength)
    var highs = array.new<PivotPoint>()
    var lows = array.new<PivotPoint>()
    var highFlat = 0
    var lowFlat = 0
    highFlat := bar_index >= donchLength and channelHigh == channelHigh[1] ? math.min(highFlat + 1, flatBars + 1) : 0
    lowFlat := bar_index >= donchLength and channelLow == channelLow[1] ? math.min(lowFlat + 1, flatBars + 1) : 0
    resTop = float(na)
    resBottom = float(na)
    resStart = int(na)
    supTop = float(na)
    supBottom = float(na)
    supStart = int(na)
    if mode == "Pivots"
        if not na(ph)
            current = PivotPoint.new(bar_index - timeHorizon, time[timeHorizon], ph, open[timeHorizon], high[timeHorizon], low[timeHorizon], close[timeHorizon])
            [top, bottom, origin] = pairPivot(highs, current, true, tolerance)
            resTop := top
            resBottom := bottom
            resStart := origin
        if not na(pl)
            current = PivotPoint.new(bar_index - timeHorizon, time[timeHorizon], pl, open[timeHorizon], high[timeHorizon], low[timeHorizon], close[timeHorizon])
            [top, bottom, origin] = pairPivot(lows, current, false, tolerance)
            supTop := top
            supBottom := bottom
            supStart := origin
    else if not na(volatility)
        depth = math.max(volatility * donchDepth, syminfo.mintick)
        if highFlat == flatBars
            resTop := math.round_to_mintick(channelHigh)
            resBottom := math.round_to_mintick(channelHigh - depth)
            resStart := time[flatBars]
        if lowFlat == flatBars
            supTop := math.round_to_mintick(channelLow + depth)
            supBottom := math.round_to_mintick(channelLow)
            supStart := time[flatBars]
    [resTop, resBottom, resStart, not na(resStart), supTop, supBottom, supStart, not na(supStart), time]

confirmedSourceZones() =>
    [resTop, resBottom, resStart, resFound, supTop, supBottom, supStart, supFound, stamp] = sourceZones()
    [resTop[1], resBottom[1], resStart[1], resFound[1], supTop[1], supBottom[1], supStart[1], supFound[1], stamp[1]]

rectsOverlap(aLeft, aRight, aTop, aBottom, bLeft, bRight, bTop, bBottom) =>
    timeOverlap = aLeft <= bRight and aRight >= bLeft
    priceOverlap = aBottom <= bTop and aTop >= bBottom
    timeOverlap and priceOverlap

isOverlapping(left, top, bottom) =>
    overlap = false
    if zones.size() > 0
        for i = 0 to zones.size() - 1
            item = zones.get(i)
            right = item.extending ? time : box.get_right(item.bx)
            if rectsOverlap(left, time, top, bottom, box.get_left(item.bx), right, item.top, item.bottom)
                overlap := true
                break
    overlap

newZone(top, bottom, origin, isSupport) =>
    created = false
    valid = not na(top) and not na(bottom) and not na(origin) and top > bottom
    if valid and zones.size() < 500
        intact = isSupport ? close >= bottom : close <= top
        if intact and not isOverlapping(origin, top, bottom)
            col = isSupport ? bullCol : bearCol
            bx = box.new(left = origin, top = top, right = time, bottom = bottom, xloc = xloc.bar_time, extend = extend.none, border_color = color.new(col, zoneBorderTransparency), border_width = 1, border_style = line.style_solid, bgcolor = color.new(col, zoneFillTransparency))
            mid = line.new(origin, math.avg(top, bottom), time, math.avg(top, bottom), xloc = xloc.bar_time, color = color.new(col, 40), style = line.style_dotted, width = 2)
            zones.push(Zone.new(bx = bx, mid = mid, lbl = na, top = top, bottom = bottom, isSupport = isSupport, born = bar_index))
            created := true
    created

probability(isSupport, age) =>
    index = (isSupport ? 0 : expiryBars + 1) + math.max(0, math.min(age, expiryBars))
    samples = riskSamples.get(index)
    breaks = riskBreaks.get(index)
    value = samples >= minSamples ? 100.0 * breaks / samples : float(na)
    [value, samples]

percentText(value) =>
    na(value) ? "N/A" : str.tostring(value, "#.0") + "%"

priceText(value) =>
    na(value) ? "—" : str.tostring(value, format.mintick)

sourceText(simple string tf) =>
    seconds = timeframe.in_seconds(tf)
    seconds < 60 ? str.tostring(seconds) + "s" : seconds < 3600 ? str.tostring(seconds / 60, "#") + "m" : seconds < 86400 ? str.tostring(seconds / 3600, "#.#") + "H" : tf

clearMarker(value, above, gap) =>
    result = value
    if not na(result) and zones.size() > 0
        for pass = * to zones.size()
            moved = false
            for i = 0 to zones.size() - 1
                item = zones.get(i)
                present = box.get_left(item.bx) <= time and (item.extending or box.get_right(item.bx) >= time)
                if present and result >= item.bottom - gap * 0.5 and result <= item.top + gap * 0.5
                    result := above ? item.top + gap : item.bottom - gap
                    moved := true
            if not moved
                break
    result

writeCell(column, row, value, textCol, background) =>
    table.cell(dashboard, column, row, value, text_color = textCol, bgcolor = background, text_size = textSize, text_halign = column == 0 ? text.align_left : text.align_right)

chartSeconds = timeframe.in_seconds()
sourceSeconds = timeframe.in_seconds(zoneTF)
higherTF = useMTF and sourceSeconds > chartSeconds
if barstate.isfirst
    if useMTF and (na(chartSeconds) or na(sourceSeconds) or sourceSeconds < chartSeconds)
        runtime.error("The zone source must be the chart timeframe or a higher timeframe. Use a time-based chart for MTF detection.")
    if showDashboard
        table.merge_cells(dashboard, 0, 0, 2, 0)
        table.merge_cells(dashboard, 0, 1, 2, 1)
        table.merge_cells(dashboard, 0, 14, 2, 14)
        table.merge_cells(dashboard, 0, 15, 2, 15)

[resTop, resBottom, resStart, resFound, supTop, supBottom, supStart, supFound, sourceStamp] = if higherTF
    request.security(syminfo.tickerid, zoneTF, confirmedSourceZones(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
else
    sourceZones()

sourceTag = sourceText(higherTF ? zoneTF : timeframe.period)
chartAtrRaw = ta.atr(14)
chartAtr = math.max(nz(chartAtrRaw, high - low), syminfo.mintick)
markerGap = math.max(chartAtr * markerMult, syminfo.mintick * 3)

newSupport = false
newResistance = false
supportTouch = false
resistanceTouch = false
bullRejection = false
bearRejection = false
bullSweep = false
bearSweep = false
bullBreak = false
bearBreak = false
supportExpired = false
resistanceExpired = false
nearExpiry = false
highRiskTouch = false
bullRejectY = float(na)
bearRejectY = float(na)
bullSweepY = float(na)
bearSweepY = float(na)
bullBreakY = float(na)
bearBreakY = float(na)

if zones.size() > 0
    for i = 0 to zones.size() - 1
        item = zones.get(i)
        if item.extending
            box.set_right(item.bx, time)
            if not na(item.mid)
                line.set_x2(item.mid, time)
            if barstate.isconfirmed
                age = bar_index - item.born
                remaining = math.max(0, expiryBars - age)

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