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

Price Acceptance vs Rejection Engine [PARE]

indicator_price_acceptance_vs_rejection_engine_for_tradingview.pine
Вы автор или правообладатель?

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

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

О программе

Индикатор «Price Acceptance vs Rejection Engine [PARE]» для TradingView (Pine Script v6) выполняет анализ внутридневного поведения цены. Он рассчитывает два основных компонента — оценку принятия цены (Acceptance) и оценку отвержения (Rejection) — по нескольким независимым измерениям для бычьей и медвежьей стороны, а также строит референсные зоны на основе пивотов и кластеризации закрытий.

Индикатор включает детектор неудачного принятия (Failed Acceptance), движок переходов между поведенческими режимами, оценку удержания цены (Staying Power), детектор конфликта покупателей и продавцов, а также индикатор поведенческого моментума. Все оценки комбинируются в единый «маркет-эвиденс» с настраиваемыми весами и штрафом за конфликт.

Система генерирует сигналы трёх уровней — EARLY, CONFIRMED и HIGH-CONVICTION — с охлаждающим периодом между сигналами. Визуальная часть включает дашборд «Price Behaviour Terminal», референсные зоны с подсветкой, маркеры отвержения, кольца и планы сделок с уровнями Entry/SL/TP1-TP3 (отображение без реальной торговли). Поддерживается подтверждение с более высокого таймфрейма через request.security().

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

НастройкаОписание
sensitivity Чувствительность анализа: выше = реакция на меньшие расстояния / более быстрая оценка. 1.0 настроено для 5-минутных графиков.
refMode Режим расчёта референсной зоны: Rolling Midpoint, Rolling High/Low, User Price или Adaptive Area.
lookbackLen Длина стандартного окна отката для расчётов.
userPrice Ценовой уровень, заданный пользователем (при режиме User Price).
minSignalScore Минимальный оценочный балл для подтверждённого сигнала.
cooldownBars Количество баров охлаждения между последовательными сигналами.
trendFilter Включить фильтр контекста тренда (EMA).
trendLen Длина EMA для фильтра тренда.
accLen Длина окна для расчёта принятия (количество баров, учитываемых при оценке Acceptance).
minCloses Минимальное количество последовательных закрытий для подтверждения принятия.
minAccPct Минимальный процент принятия (доля закрытий с одной стороны) для признания Acceptance.
stayThr Порог удержания цены (Staying Power) в процентах.
wickSens Чувствительность теней (минимальная тень / диапазон) для оценки отвержения.
minFailed Минимальное количество неудачных попыток для оценки отвержения.
rejLen Длина окна для расчёта отвержения (количество баров).
retBars Порог скорости возврата (в барах) для расчёта отвержения.
trigRejMin Минимальный балл отвержения для запуска настройки.
areaWidthATR Ширина референсной зоны в кратных значениях ATR.
clusterTol Допуск слияния зон при кластеризации в единицах ATR.
minInter Минимальное количество взаимодействий (визитов цены в зону) для активной зоны.
maxAreas Максимальное количество активных референсных зон на графике.
pivLen Длина пивота (задержка обнаружения = это количество баров).
failConfirm Количество баров подтверждения для детектора неудачного принятия.
failRetThr Порог возврата (x ATR ниже/выше зоны) для детектора неудачного принятия.
failEstablish Инвалидация: движение, считающееся установленным (в кратных ATR).
failExpire Инвалидация: отслеживание истекает через N баров.
momLen Длина окна для расчёта поведенческого моментума.
atrLen Период расчёта ATR, используемый для нормализации расчётов.
effThr Порог эффективности для расчёта поведенческого моментума.
decaySens Чувствительность затухания моментума.
minConviction Минимальный оценочный балл для сигнала HIGH-CONVICTION.
stopPad Отступ стоп-лосса в кратных ATR.
tp1R Соотношение риск/награда для цели TP1.
tp2R Соотношение риск/награда для цели TP2.
tp3R Соотношение риск/награда для цели TP3.
minRiskATR Минимальное расстояние риска в кратных ATR.
maxRiskATR Максимальное расстояние риска в кратных ATR.
maxPlans Максимальное количество исторических планов сделок на графике.
planWidth Ширина блока плана сделки в барах.
dynAlerts Отправка динамических сообщений alert() с ценовыми уровнями (один алерт на индикатор через 'Any alert() function call').
wAcc Вес фактора принятия в комбинированной оценке.
wRej Вес фактора отвержения в комбинированной оценке.
wStay Вес фактора удержания цены в комбинированной оценке.
wFail Вес фактора неудачного принятия в комбинированной оценке.
wMom Вес поведенческого моментума в комбинированной оценке.
wConf Сила штрафа за конфликт (в процентах).
useHtf Использовать подтверждение с более высокого таймфрейма.
htf1 Таймфрейм подтверждения с более высоким интервалом.
useHtf2 Использовать второй более высокий таймфрейм.
htf2 Второй таймфрейм более высокого порядка.
htfMode Требование подтверждения: «Not Opposing» (не противоположное) или «Supporting» (поддерживающее).
showHtfRow Отображать строку более высокого таймфрейма в дашборде.
showDash Отображение дашборда «Price Behaviour Terminal».
dashPosIn Позиция дашборда на графике.
showStrip Отображать нижнюю полосу состояния.
showZones Отображать референсные зоны.
showGlow Отображать подсветку зоны / след отвержения.
showMidline Отображать среднюю линию зоны.
showZoneLabels Отображать подписи зон.
zoneLabelOff Смещение подписи зоны от последнего бара.
showRejMarkers Отображать маркеры отвержения.
showRings Отображать пунктирные подсветочные кольца.
showFailed Отображать неудачное принятие (Failed Acceptance).
failFormal Использовать формальные названия (FAILED BULLISH ACCEPTANCE) для маркеров неудачного принятия.
showTransitions Отображать метки переходов на графике.
showSignals Отображать сигналы BUY / SELL на графике.
showEarly Отображать ранние (EARLY) настройки.
showPlans Отображать планы сделок (Entry/SL/TP) — визуально, без реальной торговли.
cBull Цвет бычьего направления.
cBear Цвет медвежьего направления.
cAcc Цвет принятия (Acceptance Zone).
cAmb Цвет конфликта / неопределённости.
cGrey Цвет нейтрального состояния.
cCyan Цвет бычьего отвержения (Bullish Rejection).
cPurple Цвет медвежьего отвержения (Bearish Rejection Bar).
cFail Цвет неудачного принятия (Failed Acceptance).
cNavy Цвет фона дашборда.
cHeader Цвет заголовка дашборда.
cFrame Цвет рамки дашборда.

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

indicator(title = "Price Acceptance vs Rejection Engine [PARE]", shorttitle = "PARE", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_polylines_count = 100, max_bars_back = 500)

G_GEN  = "A. General Settings"
G_ACC  = "B. Acceptance Engine"
G_REJ  = "C. Rejection Engine"
G_AREA = "D. Reference Areas"
G_FAIL = "E. Failed Acceptance"
G_MOM  = "F. Momentum"
G_SIG  = "G. Signals and Risk"
G_WGT  = "G2. Evidence Weights"
G_HTF  = "H. Multi-Timeframe"
G_VIS  = "I. Visual Settings"
G_COL  = "I2. Colours"

sensitivity    = input.float(1.0, "Analysis Sensitivity", minval = 0.5, maxval = 2.0, step = 0.1, group = G_GEN, tooltip = "Higher = reacts to smaller distances / faster evidence. 1.0 is tuned for 5-minute charts. Use ~0.8 on 1m, ~1.2 on 15m.")
refMode        = input.string("Adaptive Area", "Reference Calculation Mode", options = ["Rolling Midpoint", "Rolling High/Low", "User Price", "Adaptive Area"], group = G_GEN)
lookbackLen    = input.int(40, "Default Lookback", minval = 10, maxval = 150, group = G_GEN)
userPrice      = input.price(0.0, "User-Defined Price Level (mode: User Price)", group = G_GEN)
minSignalScore = input.int(60, "Minimum Signal Score", minval = 30, maxval = 100, group = G_GEN)
cooldownBars   = input.int(8, "Cooldown Bars Between Signals", minval = 1, maxval = 100, group = G_GEN)
trendFilter    = input.bool(false, "Optional Trend-Context Filter", group = G_GEN)
trendLen       = input.int(100, "Trend Filter Length (EMA)", minval = 20, maxval = 400, group = G_GEN)

accLen         = input.int(20, "Acceptance Lookback", minval = 8, maxval = 100, group = G_ACC)
minCloses      = input.int(3, "Minimum Consecutive Closes", minval = 2, maxval = 20, group = G_ACC)
minAccPct      = input.int(55, "Minimum Acceptance % (closes on one side)", minval = 30, maxval = 100, group = G_ACC)
stayThr        = input.int(60, "Staying Power Threshold", minval = 30, maxval = 100, group = G_ACC)

wickSens       = input.float(0.40, "Wick Sensitivity (min wick / range)", minval = 0.2, maxval = 0.8, step = 0.05, group = G_REJ)
minFailed      = input.int(2, "Minimum Failed Attempts", minval = 1, maxval = 10, group = G_REJ)
rejLen         = input.int(12, "Rejection Lookback", minval = 5, maxval = 60, group = G_REJ)
retBars        = input.int(2, "Return-Speed Threshold (bars)", minval = 1, maxval = 10, group = G_REJ)
trigRejMin     = input.int(60, "Rejection Score Needed To Trigger Setup", minval = 40, maxval = 95, group = G_REJ)

areaWidthATR   = input.float(0.8, "Area Width (x ATR)", minval = 0.2, maxval = 3.0, step = 0.1, group = G_AREA)
clusterTol     = input.float(0.5, "ATR Clustering / Merge Tolerance", minval = 0.0, maxval = 3.0, step = 0.1, group = G_AREA)
minInter       = input.int(2, "Minimum Interactions", minval = 1, maxval = 10, group = G_AREA)
maxAreas       = input.int(3, "Maximum Active Areas", minval = 1, maxval = 6, group = G_AREA)
pivLen         = input.int(3, "Pivot Length (detection delay = this many bars)", minval = 2, maxval = 10, group = G_AREA)

failConfirm    = input.int(3, "Confirmation Bars", minval = 2, maxval = 8, group = G_FAIL)
failRetThr     = input.float(0.15, "Return Threshold (x ATR below/above area)", minval = 0.0, maxval = 1.5, step = 0.05, group = G_FAIL)
failEstablish  = input.float(2.5, "Invalidation: Move Considered Established (x ATR)", minval = 1.0, maxval = 6.0, step = 0.25, group = G_FAIL)
failExpire     = input.int(40, "Invalidation: Tracking Expires After (bars)", minval = 10, maxval = 200, group = G_FAIL)

momLen         = input.int(14, "Momentum Lookback", minval = 6, maxval = 60, group = G_MOM)
atrLen         = input.int(14, "ATR Period", minval = 5, maxval = 50, group = G_MOM)
effThr         = input.float(0.35, "Efficiency Threshold", minval = 0.1, maxval = 0.9, step = 0.05, group = G_MOM)
decaySens      = input.float(1.0, "Decay Sensitivity", minval = 0.3, maxval = 3.0, step = 0.1, group = G_MOM)

minConviction  = input.int(78, "Minimum Conviction Score (HIGH-CONVICTION)", minval = 50, maxval = 100, group = G_SIG)
stopPad        = input.float(0.25, "Stop Padding (x ATR)", minval = 0.0, maxval = 3.0, step = 0.05, group = G_SIG)
tp1R           = input.float(1.0, "TP1 Risk/Reward", minval = 0.25, step = 0.25, group = G_SIG)
tp2R           = input.float(2.0, "TP2 Risk/Reward", minval = 0.5, step = 0.25, group = G_SIG)
tp3R           = input.float(3.0, "TP3 Risk/Reward", minval = 0.75, step = 0.25, group = G_SIG)
minRiskATR     = input.float(0.5, "Minimum Risk Distance (x ATR)", minval = 0.1, step = 0.1, group = G_SIG)
maxRiskATR     = input.float(4.0, "Maximum Risk Distance (x ATR)", minval = 0.5, step = 0.5, group = G_SIG)
maxPlans       = input.int(3, "Maximum Historical Trade Plans", minval = 1, maxval = 20, group = G_SIG)
planWidth      = input.int(14, "Trade Plan Box Width (bars)", minval = 4, maxval = 60, group = G_SIG)
dynAlerts      = input.bool(true, "Send Dynamic alert() Messages With Price Levels", group = G_SIG, tooltip = "Create ONE alert on this indicator using 'Any alert() function call' to receive messages with levels. alertcondition() entries remain available separately.")

wAcc           = input.float(25.0, "Weight: Acceptance", minval = 1.0, maxval = 100.0, group = G_WGT)
wRej           = input.float(25.0, "Weight: Rejection", minval = 1.0, maxval = 100.0, group = G_WGT)
wStay          = input.float(15.0, "Weight: Staying Power", minval = 1.0, maxval = 100.0, group = G_WGT)
wFail          = input.float(15.0, "Weight: Failed-Acceptance Evidence", minval = 1.0, maxval = 100.0, group = G_WGT)
wMom           = input.float(20.0, "Weight: Behaviour Momentum", minval = 1.0, maxval = 100.0, group = G_WGT)
wConf          = input.float(30.0, "Conflict Penalty Strength (%)", minval = 0.0, maxval = 100.0, group = G_WGT)

useHtf         = input.bool(true, "Use Higher-Timeframe Confirmation", group = G_HTF)
htf1           = input.timeframe("15", "Confirmation Timeframe", group = G_HTF)
useHtf2        = input.bool(false, "Use Second Higher Timeframe", group = G_HTF)
htf2           = input.string("60", "Second Timeframe", options = ["30", "60", "240"], group = G_HTF)
htfMode        = input.string("Not Opposing", "Confirmation Requirement", options = ["Not Opposing", "Supporting"], group = G_HTF)
showHtfRow     = input.bool(false, "Show HTF Row In Dashboard", group = G_HTF)

showDash       = input.bool(true, "Show Dashboard", group = G_VIS)
dashPosIn      = input.string("Top Right", "Dashboard Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = G_VIS)
showStrip      = input.bool(true, "Show Bottom Status Strip", group = G_VIS)
showZones      = input.bool(true, "Show Reference Zones", group = G_VIS)
showGlow       = input.bool(true, "Show Zone Glow / Rejection Footprint", group = G_VIS)
showMidline    = input.bool(true, "Show Zone Midpoint", group = G_VIS)
showZoneLabels = input.bool(true, "Show Zone Labels", group = G_VIS)
zoneLabelOff   = input.int(60, "Zone Label Offset From Last Bar", minval = 10, maxval = 200, group = G_VIS)
showRejMarkers = input.bool(true, "Show Rejection Markers", group = G_VIS)
showRings      = input.bool(true, "Show Dashed Highlight Circles", group = G_VIS)
showFailed     = input.bool(true, "Show Failed Acceptance", group = G_VIS)
failFormal     = input.bool(false, "Use Formal Names (FAILED BULLISH ACCEPTANCE)", group = G_VIS)
showTransitions= input.bool(false, "Show Transition Labels On Chart", group = G_VIS)
showSignals    = input.bool(true, "Show BUY / SELL Signals", group = G_VIS)
showEarly      = input.bool(true, "Show EARLY Setups", group = G_VIS)
showPlans      = input.bool(true, "Show Trade Plans (Entry/SL/TP)", group = G_VIS)

cBull   = input.color(#00E676, "Bullish", group = G_COL)
cBear   = input.color(#FF1744, "Bearish", group = G_COL)
cAcc    = input.color(#2979FF, "Acceptance Zone", group = G_COL)
cAmb    = input.color(#FFB300, "Conflict / Uncertainty", group = G_COL)
cGrey   = input.color(#787B86, "Neutral", group = G_COL)
cCyan   = input.color(#00E5FF, "Bullish Rejection", group = G_COL)
cPurple = input.color(#B388FF, "Bearish Rejection Bar", group = G_COL)
cFail   = input.color(#D500F9, "Failed Acceptance", group = G_COL)
cNavy   = input.color(#0B1530, "Dashboard Background", group = G_COL)
cHeader = input.color(#0D47A1, "Dashboard Header", group = G_COL)
cFrame  = input.color(#2979FF, "Dashboard Frame", group = G_COL)

cDim    = #1C2A4A
cBlueM  = #00B0FF
cWhite  = color.white

type Area
    float top
    float bot
    float mid
    int inter = 0
    int turns = 0
    float acc = 0.0
    float rej = 0.0
    float pri = 0.0
    int state = 0
    int lastBar = 0
    int lastType = 0
    int born = 0
    int origin = 0       // 1 = born from pivot low (support-like), -1 = pivot high (resistance-like), 0 = close cluster
    int accDir = 1
    int rejDir = 1
    bool touched = false
    box bx
    box glow
    line ml
    label lb
    label tx

type Plan
    int dir = 0
    int entryBar = 0
    float entry
    float sl
    float tp1
    float tp2
    float tp3
    float inv
    int status = 0       // 0 active | 1 stop loss | 2 TP3 complete | 3 invalidated
    int hit = 0          // highest TP reached
    int endBar = 0
    box riskBox
    box rewBox
    line lnEntry
    line ln1
    line ln2
    line ln3
    line lnSl
    label lbEntry
    label lbSl
    label lb1
    label lb2
    label lb3

var array<Area>     areas    = array.new<Area>()
var array<Plan>     plans    = array.new<Plan>()
var array<label>    evLabels = array.new<label>()
var array<box>      evBoxes  = array.new<box>()
var array<polyline> evPolys  = array.new<polyline>()
var array<float>    bins     = array.new_float(20, 0.0)
var Plan            curPlan  = na

f_clamp(float x, float lo, float hi) =>
    math.max(lo, math.min(hi, x))

f_band(float s, bool rejection) =>
    s <= 30.0 ? "WEAK" : s <= 50.0 ? "DEVELOPING" : s <= 70.0 ? "MODERATE" : s <= 85.0 ? "STRONG" : rejection ? "EXTREME" : "VERY STRONG"

f_pos(string s) =>
    s == "Top Right" ? position.top_right : s == "Top Left" ? position.top_left : s == "Bottom Right" ? position.bottom_right : position.bottom_left

f_trimLabels(array<label> arr, int maxN) =>
    while arr.size() > maxN
        label.delete(arr.shift())

f_trimBoxes(array<box> arr, int maxN) =>
    while arr.size() > maxN
        box.delete(arr.shift())

f_trimPolys(array<polyline> arr, int maxN) =>
    while arr.size() > maxN
        polyline.delete(arr.shift())

f_ring(float cx, float cy, float rx, float ry, color c, int w) =>
    array<chart.point> pts = array.new<chart.point>()
    for k = 0 to 11
        float ang = 2.0 * math.pi * k / 12.0
        int px = int(math.round(cx + rx * math.cos(ang)))
        pts.push(chart.point.from_index(px, cy + ry * math.sin(ang)))
    polyline.new(pts, curved = true, closed = true, xloc = xloc.bar_index, line_color = c, fill_color = na, line_style = line.style_dashed, line_width = w)

f_accept(int dir, float top, float bot, float mid, float atrV, int len, int minCl, float sens) =>
    float score = 0.0
    float pct = 0.0
    int consec = 0
    if bar_index > len + 2
        int n = 0
        int bodyOk = 0
        int returns = 0
        bool away = false
        for i = len - 1 to 0
            bool ab = dir == 1 ? close[i] > top : close[i] < bot
            if ab
                n += 1
                away := true
            else if away
                returns += 1
                away := false
            bool bOk = dir == 1 ? math.min(open[i], close[i]) > mid : math.max(open[i], close[i]) < mid
            if bOk
                bodyOk += 1
        float ext = dir == 1 ? 1.0e10 : -1.0e10
        for i = 0 to len - 1
            bool ab2 = dir == 1 ? close[i] > top : close[i] < bot
            if ab2
                consec += 1
                ext := dir == 1 ? math.min(ext, low[i]) : math.max(ext, high[i])
            else
                break
        pct := 100.0 * n / len
        if n > 0
            float a = n / (len * 1.0)
            float b = f_clamp(consec / (minCl * 2.5), 0.0, 1.0)
            float c = bodyOk / (len * 1.0)
            float dist = dir == 1 ? (close - top) / atrV : (bot - close) / atrV
            float d = f_clamp(dist / (1.5 / sens), 0.0, 1.0)
            float e = f_clamp(1.0 - returns / 4.0, 0.0, 1.0)
            float prog = 0.0
            if consec > 0
                float baseC = nz(close[consec], close)
                prog := (dir == 1 ? close - baseC : baseC - close) / atrV
            float f = f_clamp(prog / (1.2 / sens), 0.0, 1.0)
            float g = 0.0
            if consec > 0
                g := dir == 1 ? (ext > bot ? 1.0 : ext > bot - 0.25 * atrV ? 0.5 : 0.0) : (ext < top ? 1.0 : ext < top + 0.25 * atrV ? 0.5 : 0.0)
            score := 100.0 * (0.22 * a + 0.15 * b + 0.12 * c + 0.14 * d + 0.10 * e + 0.15 * f + 0.12 * g)
            if consec < 2
                score := math.min(score, 30.0)
            else if consec < minCl
                score := math.min(score, 50.0)
    [f_clamp(score, 0.0, 100.0), pct, consec]

f_reject(int dir, float top, float bot, float mid, float atrV, int len, int retB, float wickS, int inter, int minI, bool shrink, int minFail) =>
    float score = 0.0
    int fails = 0
    int consRej = 0
    int ago = 999
    if bar_index > len + retB + 3
        int broke = 0
        int quick = 0
        int rc = 0
        int visits = 0
        float sumWick = 0.0
        float sumPos = 0.0
        float maxDepth = 0.0
        float extreme = dir == 1 ? 1.0e10 : -1.0e10
        bool inVisit = false
        for i = len - 1 to 0
            float rg = math.max(high[i] - low[i], syminfo.mintick)
            bool attempt = dir == 1 ? low[i] < mid : high[i] > mid
            bool recovered = dir == 1 ? close[i] > mid : close[i] < mid
            bool touch = high[i] >= bot and low[i] <= top
            if touch and not inVisit
                visits += 1
            inVisit := touch
            extreme := dir == 1 ? math.min(extreme, low[i]) : math.max(extreme, high[i])
            if attempt
                float depth = dir == 1 ? (mid - low[i]) / atrV : (high[i] - mid) / atrV
                maxDepth := math.max(maxDepth, depth)
                if recovered
                    fails += 1
                    quick += 1
                else
                    broke += 1
                    for j = 1 to retB
                        if i - j >= 0
                            bool rec2 = dir == 1 ? close[i - j] > mid : close[i - j] < mid
                            if rec2
                                quick += 1
                                break
                float wk = dir == 1 ? (math.min(open[i], close[i]) - low[i]) / rg : (high[i] - math.max(open[i], close[i])) / rg
                float cp = dir == 1 ? (close[i] - low[i]) / rg : (high[i] - close[i]) / rg
                if recovered and wk >= wickS and cp >= 0.5
                    rc += 1
                    sumWick += wk
                    sumPos += cp
                    ago := i
        for i = 0 to len - 1
            float rg2 = math.max(high[i] - low[i], syminfo.mintick)
            bool att2 = dir == 1 ? low[i] < mid : high[i] > mid
            bool rec3 = dir == 1 ? close[i] > mid : close[i] < mid
            float wk2 = dir == 1 ? (math.min(open[i], close[i]) - low[i]) / rg2 : (high[i] - math.max(open[i], close[i])) / rg2
            if att2 and rec3 and wk2 >= wickS * 0.7
                consRej += 1
            else
                break
        if rc > 0
            float avgW = sumWick / rc
            float avgP = sumPos / rc
            float wS = f_clamp(avgW / 0.7, 0.0, 1.0)
            float pS = f_clamp((avgP - 0.4) / 0.5, 0.0, 1.0)
            float aS = f_clamp(fails / (minFail * 1.5), 0.0, 1.0)
            float dS = f_clamp(maxDepth / 0.8, 0.0, 1.0)
            int tot = fails + broke
            float spS = tot > 0 ? quick / (tot * 1.0) : 0.0
            float cS = f_clamp(consRej / 2.0, 0.0, 1.0)
            int tested = math.max(visits, inter)
            float prS = f_clamp(tested / (minI + 2.0), 0.0, 1.0)
            float shS = (shrink and fails >= 2) ? 1.0 : 0.0
            float moved = dir == 1 ? (close - extreme) / atrV : (extreme - close) / atrV
            float mvS = f_clamp(moved / 1.5, 0.0, 1.0)
            score := 100.0 * (0.16 * wS + 0.14 * pS + 0.18 * aS + 0.10 * dS + 0.12 * spS + 0.08 * cS + 0.08 * prS + 0.04 * shS + 0.10 * mvS)
            if fails < minFail
                score := math.min(score, 55.0)
            if tested < minI
                score := math.min(score, 60.0)
            float dec = f_clamp(1.0 - ago / (len * 0.75), 0.0, 1.0)
            score := score * (0.45 + 0.55 * dec)
    [f_clamp(score, 0.0, 100.0), fails, consRej, ago]

f_stay(int dir, float top, float bot, float atrV, int consec, int len, int minCl) =>
    float score = 0.0
    if consec >= 1 and bar_index > len + 8
        float bound = dir == 1 ? top : bot
        int c1 = math.min(consec, len)
        int w = math.min(len, math.max(consec, 6))
        int cnt = 0
        int held = 0
        float adv = 0.0
        float minD = 1.0e10
        for i = 0 to w - 1
            bool ab = dir == 1 ? close[i] > bound : close[i] < bound
            if ab
                cnt += 1
            if i < c1
                float ad = dir == 1 ? bound - low[i] : high[i] - bound
                adv := math.max(adv, ad)
                float dc = dir == 1 ? close[i] - bound : bound - close[i]
                minD := math.min(minD, dc)
                bool tc = dir == 1 ? low[i] <= bound : high[i] >= bound
                if tc and ab
                    held += 1
        float persist = f_clamp(consec / (minCl * 3.0), 0.0, 1.0)
        float pS = cnt / (w * 1.0)
        float advS = f_clamp(1.0 - adv / (0.8 * atrV), 0.0, 1.0)
        float distS = f_clamp(minD / (0.6 * atrV), 0.0, 1.0)
        float heldS = held > 0 ? f_clamp(0.5 + held / 4.0, 0.0, 1.0) : 0.4
        score := 100.0 * (0.25 * persist + 0.25 * pS + 0.20 * advS + 0.15 * distS + 0.15 * heldS)
    f_clamp(score, 0.0, 100.0)

f_htfAcc() =>
    float hi = ta.highest(high, 20)
    float lo = ta.lowest(low, 20)
    float md = (hi + lo) / 2.0
    ta.sma(close > md ? 100.0 : 0.0, 10)

f_htfRej() =>
    float r = math.max(high - low, syminfo.mintick)
    ta.sma(((math.min(open, close) - low) - (high - math.max(open, close))) / r, 8)

f_htfBias(float acc, float rej) =>
    f_clamp(0.6 * (acc - 50.0) * 2.0 + 0.4 * f_clamp(rej * 250.0, -100.0, 100.0), -100.0, 100.0)

f_htfText(float b) =>
    na(b) ? "N/A" : b >= 35.0 ? "BULL ACCEPT" : b <= -35.0 ? "BEAR ACCEPT" : b >= 15.0 ? "BULL LEAN" : b <= -15.0 ? "BEAR LEAN" : "NEUTRAL"

f_killArea(Area a) =>
    if not na(a.bx)
        box.delete(a.bx)
    if not na(a.glow)
        box.delete(a.glow)
    if not na(a.ml)
        line.delete(a.ml)
    if not na(a.lb)
        label.delete(a.lb)
    if not na(a.tx)
        label.delete(a.tx)

f_makeArea(float c, float w, int origin, int bornBar) =>
    Area a = Area.new(top = c + w / 2.0, bot = c - w / 2.0, mid = c, inter = origin == 0 ? 0 : 1, lastBar = bar_index, born = math.max(0, bornBar), origin = origin)
    a.pri := a.inter * 8.0 + 25.0
    if showZones
        if showGlow
            a.glow := box.new(a.born, a.top, bar_index, a.bot, border_color = na, bgcolor = color.new(cAcc, 94), extend = extend.right, xloc = xloc.bar_index)
        a.bx := box.new(a.born, a.top, bar_index, a.bot, border_color = color.new(cAcc, 35), border_width = 1, bgcolor = color.new(cAcc, 84), extend = extend.right, xloc = xloc.bar_index)
        if showMidline
            a.ml := line.new(a.born, a.mid, bar_index + 1, a.mid, xloc = xloc.bar_index, extend = extend.right, color = color.new(cAcc, 25), style = line.style_dotted, width = 1)
        if showZoneLabels
            a.lb := label.new(bar_index, a.mid, "", xloc = xloc.bar_index, style = label.style_label_down, color = cAcc, textcolor = cWhite, size = size.small)
            a.tx := label.new(bar_index, a.mid, "", xloc = xloc.bar_index, style = label.style_none, color = color.new(cAcc, 100), textcolor = cAcc, size = size.small)
    a

f_pruneAreas(array<Area> arr, int maxN) =>
    while arr.size() > maxN
        int worst = 0
        float wp = 1.0e10
        for i = 0 to arr.size() - 1
            Area a = arr.get(i)
            if a.pri < wp
                wp := a.pri
                worst := i
        f_killArea(arr.get(worst))
        arr.remove(worst)

f_addOrMerge(array<Area> arr, float c, float w, int origin, bool isPivot, int bornBar, float tol, float maxW) =>
    float nTop = c + w / 2.0
    float nBot = c - w / 2.0
    int found = -1
    if arr.size() > 0
        for i = 0 to arr.size() - 1
            Area a = arr.get(i)
            float gap = math.max(0.0, math.max(a.bot, nBot) - math.min(a.top, nTop))
            if gap <= tol and a.state != 5
                found := i
                break
    if found >= 0
        Area m = arr.get(found)
        float t = math.max(m.top, nTop)
        float b = math.min(m.bot, nBot)
        if t - b > maxW
            float wt = math.max(m.inter, 1)
            float cc = (m.mid * wt + c) / (wt + 1.0)
            t := cc + maxW / 2.0
            b := cc - maxW / 2.0
        m.top := t
        m.bot := b
        m.mid := (t + b) / 2.0
        if isPivot
            m.turns += 1
    else
        arr.push(f_makeArea(c, w, origin, bornBar))
    true

f_mergePass(array<Area> arr, float tol, float maxW) =>
    bool again = true
    int guard = 0
    while again and guard < 8
        again := false
        guard += 1
        int n = arr.size()
        if n > 1
            for i = 0 to n - 2
                for j = i + 1 to n - 1
                    Area a = arr.get(i)
                    Area b = arr.get(j)
                    float gap = math.max(0.0, math.max(a.bot, b.bot) - math.min(a.top, b.top))
                    if gap <= tol
                        float t = math.max(a.top, b.top)
                        float bt = math.min(a.bot, b.bot)
                        if t - bt > maxW
                            float wa = math.max(a.inter, 1)
                            float wb = math.max(b.inter, 1)
                            float cc = (a.mid * wa + b.mid * wb) / (wa + wb)
                            t := cc + maxW / 2.0
                            bt := cc - maxW / 2.0
                        a.top := t
                        a.bot := bt
                        a.mid := (t + bt) / 2.0
                        a.inter += b.inter
                        a.turns += b.turns
                        a.lastBar := math.max(a.lastBar, b.lastBar)
                        f_killArea(b)
                        arr.remove(j)
                        again := true
                        break
                if again
                    break

f_styleArea(Area a, float atrV) =>
    int kind = 0
    if a.state == 3
        kind := a.rejDir
    else if a.state == 2 and a.origin == 1 and a.accDir == 1
        kind := 1
    color base = (a.state == 5 or a.state == 0) ? cGrey : a.state == 4 ? cAmb : kind == 1 ? cBull : kind == -1 ? cBear : cAcc
    float sc = a.state == 3 ? a.rej : a.acc
    int tr = int(math.round(f_clamp(90.0 - sc * 0.25, 62.0, 92.0)))
    if not na(a.bx)
        box.set_top(a.bx, a.top)
        box.set_bottom(a.bx, a.bot)
        box.set_bgcolor(a.bx, color.new(base, tr))
        box.set_border_color(a.bx, color.new(base, a.state == 5 ? 70 : 35))
        box.set_border_style(a.bx, a.state == 5 ? line.style_dashed : line.style_solid)
    if not na(a.glow)
        float gp = 0.18 * atrV
        box.set_top(a.glow, a.top + gp)
        box.set_bottom(a.glow, a.bot - gp)
        box.set_bgcolor(a.glow, color.new(base, a.state == 3 ? 86 : 94))
    if not na(a.ml)
        line.set_y1(a.ml, a.mid)
        line.set_y2(a.ml, a.mid)
        line.set_color(a.ml, color.new(base, 25))
    if not na(a.lb) and not na(a.tx)
        string loS = str.tostring(a.bot, format.mintick)
        string hiS = str.tostring(a.top, format.mintick)
        int sx = math.max(a.born, bar_index - zoneLabelOff)
        if kind == -1 and a.state == 3
            label.set_style(a.lb, label.style_none)
            label.set_xy(a.lb, bar_index - 14, a.top + 0.35 * atrV)
            label.set_text(a.lb, "Rejected Area")
            label.set_textcolor(a.lb, cBear)
            label.set_color(a.lb, color.new(base, 100))
            label.set_xy(a.tx, bar_index - 14, a.top - 0.2 * atrV)
            label.set_text(a.tx, "RZ: " + loS + " – " + hiS)
            label.set_textcolor(a.tx, cBear)
        else if kind == 1
            label.set_style(a.lb, label.style_label_up)
            label.set_xy(a.lb, sx, a.bot)
            label.set_text(a.lb, "Strong Support\n(" + (a.state == 2 ? "Acceptance: " + str.tostring(int(math.round(a.acc))) : "Rejection: " + str.tostring(int(math.round(a.rej)))) + ")")
            label.set_textcolor(a.lb, #69F0AE)
            label.set_color(a.lb, #0B3D1F)
            label.set_xy(a.tx, bar_index - 40, a.bot - 0.45 * atrV)
            label.set_text(a.tx, "SZ: " + loS + " – " + hiS)
            label.set_textcolor(a.tx, cBull)
        else
            string nm = a.state == 2 ? "Acceptance Zone\n(Score: " + str.tostring(int(math.round(a.acc))) + ")" : a.state == 4 ? "Balanced Area" : a.state == 5 ? "Invalidated Area" : a.state == 0 ? "Untested Area" : "Developing Area"
            label.set_style(a.lb, label.style_label_down)
            label.set_xy(a.lb, sx, a.top)
            label.set_text(a.lb, nm)
            label.set_textcolor(a.lb, a.state == 4 ? cAmb : #40C4FF)
            label.set_color(a.lb, #0A2A55)
            label.set_xy(a.tx, bar_index - 40, a.bot)
            label.set_text(a.tx, "")

f_makePlan(int dir, float entry, float sl, float t1, float t2, float t3, float inv) =>
    int rb = bar_index + planWidth
    Plan p = Plan.new(dir = dir, entryBar = bar_index, entry = entry, sl = sl, tp1 = t1, tp2 = t2, tp3 = t3, inv = inv, endBar = bar_index)
    if showPlans
        float rwTop = math.max(entry, t3)
        float rwBot = math.min(entry, t3)
        float rkTop = math.max(entry, sl)
        float rkBot = math.min(entry, sl)
        p.rewBox := box.new(bar_index, rwTop, rb, rwBot, border_color = na, bgcolor = color.new(cBull, 80), xloc = xloc.bar_index)
        p.riskBox := box.new(bar_index, rkTop, rb, rkBot, border_color = color.new(cBear, 40), border_width = 1, bgcolor = color.new(cBear, 76), xloc = xloc.bar_index)
        p.lnEntry := line.new(bar_index, entry, rb, entry, xloc = xloc.bar_index, color = cBull, style = line.style_dashed, width = 1)
        p.ln1 := line.new(bar_index, t1, rb, t1, xloc = xloc.bar_index, color = color.new(cBull, 25), style = line.style_dashed, width = 1)
        p.ln2 := line.new(bar_index, t2, rb, t2, xloc = xloc.bar_index, color = color.new(cBull, 25), style = line.style_dashed, width = 1)
        p.ln3 := line.new(bar_index, t3, rb, t3, xloc = xloc.bar_index, color = cCyan, style = line.style_solid, width = 2)
        p.lnSl := line.new(bar_index, sl, rb, sl, xloc = xloc.bar_index, color = cBear, style = line.style_solid, width = 1)
        p.lbEntry := label.new(rb, entry, "ENTRY: " + str.tostring(entry, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = #0B3D1F, textcolor = #69F0AE, size = size.small)
        p.lb1 := label.new(rb, t1, "TP1: " + str.tostring(t1, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = #0B3D1F, textcolor = #69F0AE, size = size.small)
        p.lb2 := label.new(rb, t2, "TP2: " + str.tostring(t2, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = #0B3D1F, textcolor = #69F0AE, size = size.small)
        p.lb3 := label.new(rb, t3, "TP3: " + str.tostring(t3, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = #0B3D1F, textcolor = #84FFFF, size = size.small)
        p.lbSl := label.new(rb, sl, "SL: " + str.tostring(sl, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = #5A0F0F, textcolor = #FF8A80, size = size.small)
    p

f_planLayout(Plan p, int rb) =>
    if showPlans and not na(p.rewBox)
        box.set_right(p.rewBox, rb)
        box.set_right(p.riskBox, rb)
        line.set_x2(p.lnEntry, rb)
        line.set_x2(p.ln1, rb)
        line.set_x2(p.ln2, rb)
        line.set_x2(p.ln3, rb)
        line.set_x2(p.lnSl, rb)
        label.set_x(p.lbEntry, rb)
        label.set_x(p.lb1, rb)
        label.set_x(p.lb2, rb)
        label.set_x(p.lb3, rb)
        label.set_x(p.lbSl, rb)

f_planMarkHit(Plan p, int lvl) =>
    if showPlans and not na(p.rewBox)
        if lvl == 1
            label.set_text(p.lb1, "TP1 ✓ " + str.tostring(p.tp1, format.mintick))
            line.set_style(p.ln1, line.style_solid)
        else if lvl == 2
            label.set_text(p.lb2, "TP2 ✓ " + str.tostring(p.tp2, format.mintick))
            line.set_style(p.ln2, line.style_solid)
        else if lvl == 3
            label.set_text(p.lb3, "TP3 ✓ " + str.tostring(p.tp3, format.mintick))

f_killPlan(Plan p) =>
    if not na(p.rewBox)
        box.delete(p.rewBox)
    if not na(p.riskBox)
        box.delete(p.riskBox)
    if not na(p.lnEntry)
        line.delete(p.lnEntry)
    if not na(p.ln1)
        line.delete(p.ln1)
    if not na(p.ln2)
        line.delete(p.ln2)
    if not na(p.ln3)
        line.delete(p.ln3)
    if not na(p.lnSl)
        line.delete(p.lnSl)
    if not na(p.lbEntry)
        label.delete(p.lbEntry)
    if not na(p.lb1)
        label.delete(p.lb1)
    if not na(p.lb2)
        label.delete(p.lb2)
    if not na(p.lb3)
        label.delete(p.lb3)
    if not na(p.lbSl)
        label.delete(p.lbSl)
var table wm = table.new(position.bottom_right, 1, 1)
if barstate.isfirst
    table.cell(wm, 0, 0, "Telegram @SimpleForexTools", text_color = color.new(color.gray, 70), text_size = size.large)

float atrN  = math.max(nz(ta.atr(atrLen), ta.tr), syminfo.mintick * 3)
float rng   = math.max(high - low, syminfo.mintick)
float body  = math.abs(close - open)
bool  warm  = bar_index > lookbackLen + 12
bool  conf  = barstate.isconfirmed

float rollHi   = nz(ta.highest(high, lookbackLen)[1], high)
float rollLo   = nz(ta.lowest(low, lookbackLen)[1], low)
float rollMid  = (rollHi + rollLo) / 2.0
float hiClose  = ta.highest(close, lookbackLen)
float loClose  = ta.lowest(close, lookbackLen)
float ph       = ta.pivothigh(high, pivLen, pivLen)
float pl       = ta.pivotlow(low, pivLen, pivLen)
bool  bodyShrink = ta.sma(body, 3) < nz(ta.sma(body, 6)[3], 1.0e10)
float lowRej   = ta.lowest(low, rejLen)
float highRej  = ta.highest(high, rejLen)
int   lbOff    = ta.lowestbars(low, 4)
int   hbOff    = ta.highestbars(high, 4)
float lowAnch  = ta.lowest(low, 4)
float highAnch = ta.highest(high, 4)
float emaT     = ta.ema(close, trendLen)
float compress = 100.0 - nz(ta.percentrank(ta.sma(rng, 5), 100), 50.0)

float areaW    = areaWidthATR * atrN
float areaTol  = clusterTol * atrN
float areaMaxW = areaW * 2.0

if warm

    if not na(ph)
        f_addOrMerge(areas, ph - 0.25 * areaW, areaW, -1, true, bar_index - pivLen, areaTol, areaMaxW)
        f_mergePass(areas, areaTol, areaMaxW)
        f_pruneAreas(areas, maxAreas)
    if not na(pl)
        f_addOrMerge(areas, pl + 0.25 * areaW, areaW, 1, true, bar_index - pivLen, areaTol, areaMaxW)
        f_mergePass(areas, areaTol, areaMaxW)
        f_pruneAreas(areas, maxAreas)

    if bar_index % 5 == 0 and conf and (hiClose - loClose) > atrN * 0.8
        bins.fill(0.0)
        float bw = (hiClose - loClose) / 20.0
        for i = 0 to lookbackLen - 1
            int bi = int(math.max(0, math.min(19, math.floor((close[i] - loClose) / bw))))
            bins.set(bi, bins.get(bi) + 1.0)
        float best = 0.0
        int bestI = -1
        for k = 0 to 19
            float lft = k > 0 ? bins.get(math.max(k - 1, 0)) : 0.0
            float rgt = k < 19 ? bins.get(math.min(k + 1, 19)) : 0.0
            float v = bins.get(k) + 0.5 * lft + 0.5 * rgt
            if v > best
                best := v
                bestI := k
        if bestI >= 0 and best / lookbackLen >= 0.35
            f_addOrMerge(areas, loClose + (bestI + 0.5) * bw, areaW, 0, false, bar_index, areaTol, areaMaxW)
            f_mergePass(areas, areaTol, areaMaxW)
            f_pruneAreas(areas, maxAreas)

int   actIdx     = -1
float actTop     = na
float actBot     = na
float actMid     = na
int   actInter   = 0
int   actState   = 0
float bestSc     = 0.0

if warm and areas.size() > 0
    for i = 0 to areas.size() - 1
        Area a = areas.get(i)

        bool tch = high >= a.bot - 0.05 * atrN and low <= a.top + 0.05 * atrN
        if tch and not a.touched
            a.inter += 1
            a.lastBar := bar_index
            a.lastType := close > a.top ? 1 : close < a.bot ? -1 : 0
        a.touched := tch

        [aB, aBp, aBc] = f_accept(1, a.top, a.bot, a.mid, atrN, accLen, minCloses, sensitivity)
        [aS, aSp, aSc] = f_accept(-1, a.top, a.bot, a.mid, atrN, accLen, minCloses, sensitivity)
        [rB, rBf, rBc, rBa] = f_reject(1, a.top, a.bot, a.mid, atrN, rejLen, retBars, wickSens / sensitivity, a.inter, minInter, bodyShrink, minFailed)
        [rS, rSf, rSc, rSa] = f_reject(-1, a.top, a.bot, a.mid, atrN, rejLen, retBars, wickSens / sensitivity, a.inter, minInter, bodyShrink, minFailed)
        a.acc := math.max(aB, aS)
        a.accDir := aB >= aS ? 1 : -1
        a.rej := math.max(rB, rS)
        a.rejDir := rB >= rS ? 1 : -1

        bool inside = close <= a.top and close >= a.bot
        bool broken = (a.origin == 1 and aS >= 80.0) or (a.origin == -1 and aB >= 80.0)
        bool stale = bar_index - a.lastBar > lookbackLen * 5
        int st = 1
        if broken or stale
            st := 5
        else if a.inter == 0
            st := 0
        else if a.rej >= 55.0 and a.rej > a.acc
            st := 3
        else if a.acc >= 60.0
            st := 2
        else if inside or (a.acc < 40.0 and a.rej < 40.0 and a.inter >= minInter)
            st := 4
        a.state := st

        float rec = math.max(0.0, 1.0 - (bar_index - a.lastBar) / (lookbackLen * 4.0))
        a.pri := a.inter * 8.0 + a.turns * 4.0 + math.max(a.acc, a.rej) * 0.4 + rec * 25.0 - (st == 5 ? 1000.0 : 0.0)
        float dist = math.abs(close - a.mid) / atrN
        if st != 5 and a.inter >= minInter and dist <= 4.0
            float sc2 = a.pri / (1.0 + dist)
            if sc2 > bestSc
                bestSc := sc2
                actIdx := i
        f_styleArea(a, atrN)
    if actIdx >= 0
        Area aa = areas.get(actIdx)
        actTop := aa.top
        actBot := aa.bot
        actMid := aa.mid
        actInter := aa.inter
        actState := aa.state

float rHalf   = 0.5 * areaW
float nearHL  = math.abs(close - rollHi) < math.abs(close - rollLo) ? rollHi : rollLo
bool  useAdapt = refMode == "Adaptive Area" and actIdx >= 0
float refMid  = refMode == "Rolling Midpo

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