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

Order Block Holding Power

indicator order block holding power for tradingview.pine
Вы автор или правообладатель?

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

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

О программе

Индикатор «Order Block Holding Power» анализирует ордер-блоки на графике — зоны, образующиеся при пробое свинговых уровней. Для каждой стороны (бычьей и медвежьей) рассчитывается вероятность удержания блока в зависимости от его возраста (в барах), и результаты отображаются в виде кривых удержания на отдельном графике справа от цены. Ближайшие к цене живые ордер-блоки рисуются зонами непосредственно на графике с ценой. Данные берутся только по закрытым барам, что исключает перерисовку. Панель показывает ближайшие уровни сопротивления и поддержки, статистику удержания, медианную продолжительность жизни блоков и результат проверки значимости преимущества одной стороны над другой.

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

НастройкаОписание
pivotLen Количество баров с каждой стороны, подтверждающих свинг-хай или свинг-лоу. Закрытие цены через этот уровень является пробоем структуры, а последняя противоположная свеча перед пробом становится ордер-блоком. Зоны формируются и ломаются только по закрытию бара.
obLookback Количество баров назад от точки структурного прорыва, на которые нужно смотреть для поиска последней свечной противоположной стороны, формирующей ордер-блок.
maxShown Количество живых ордер-блоков, отображаемых зонами на цене с каждой стороны. Каждая зона занимает пять полилиний из лимита Pine Script.
horizon Максимальный возраст (в барах), на который рассчитываются кривые удержания. Соотношение, p-значение и медиана измеряются только до этого возраста, поэтому его изменение может повлиять на выводы.
curveW Ширина графика кривых удержания, отрисовываемого справа от последнего бара. Каждая кривая имеет одну точку на столбец бара в пределах этой ширины.
curveGap Расстояние между правым краем зон и началом графика кривых (в барах). Совместно с шириной кривой определяет требуемый правый отступ графика.
smoothBars Ширина сглаживания по возрасту, в барах. Уменьшается вблизи возраста ноль, где блоки ломаются быстрее всего, чтобы кривая и все считываемые из неё значения оставались близки к исходной скорости удержания. Более высокое значение даёт более плавные кривые.
showBand При включении на каждом возрасте отображается 95%-й доверительный интервал вокруг кривой ведущей стороны. Показывается после того, как каждая сторона набрала не менее 5 пробоев в пределах горизонта. Вариация рассчитывается с учётом группировки блоков, проживших одинаковые движения цены.
linkZones При включении каждой зоне на цене присваивается номерной круг и доля блоков, достигших её возраста, а тот же номерной круг размещается на кривой соответствующей стороны на возрасте этой зоны.
showPanel При включении отображается панель с информацией о ближайших к цене блоках сопротивления (медвежий) и поддержки (бычий), их вероятности удержания, статистике преимущества одной стороны, медианной продолжительности жизни блоков и количестве живых блоков.
panelPos Угол графика, в котором размещается информационная панель. «Top left» разделяет угол с собственной легенмой TradingView.
panelTxt Размер текста в информационной панели.
holdWin Количество дополнительных баров, на которые рассчитывается вероятность удержания ближайших блоков поддержки и сопротивления, при условии что они уже удержались определённое число баров.

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

indicator("Order Block Holding Power", shorttitle = "O.B.H.P", overlay = true, max_lines_count = 100, max_labels_count = 200, max_polylines_count = 100)

const string G_OB  = "Order blocks"
const string G_CRV = "Hold curves"
const string G_PNL = "Panel"
pivotLen   = input.int(5, "Swing length", minval = 2, maxval = 30, group = G_OB, tooltip = "Bars on each side that confirm the swing high / low. A close through it is a structure break, and the last opposite candle before the break becomes the order block. Blocks form and break only on bar close. A block's age is counted from the structure break, not from the order block candle, so the painted zone starts a few bars before age zero.", display = display.none)
obLookback = input.int(15, "Order block search", minval = 2, maxval = 50, group = G_OB, tooltip = "How many bars back from the structure break to look for the last opposite candle.", display = display.none)
maxShown   = input.int(3, "Zones shown per side", minval = 0, maxval = 8, group = G_OB, tooltip = "Live order blocks painted on price: the nearest to price on each side, up to 8 (each zone takes five of Pine's 100 polylines). Every live block still counts in the curves.", display = display.none)
horizon    = input.int(150, "Curve horizon (bars)", minval = 30, maxval = 500, group = G_CRV, tooltip = "The oldest age the hold curves cover. The lead, the ratio and the p value are measured only up to this age, so changing it can change the verdict.", display = display.none)
curveW     = input.int(70, "Curve width (bars)", minval = 30, maxval = 200, group = G_CRV, tooltip = "Width of the curve chart, drawn to the right of the last bar. Each curve has one point per bar column across it. The chart needs room there: set the chart's right margin to about Space before curve + Curve width + 15 bars (about 115 at the defaults).", display = display.none)
curveGap   = input.int(28, "Space before curve (bars)", minval = 3, maxval = 60, group = G_CRV, tooltip = "Gap between the right end of the zones and the start of the curve chart. Together with the curve width it sets how much right margin the chart needs.", display = display.none)
smoothBars = input.float(8.0, "Curve smoothing (bars)", minval = 1.0, maxval = 30.0, step = 1.0, group = G_CRV, tooltip = "Width of the smoothing applied along age, in bars. It narrows near age 0, where blocks break fastest, so the curve and the numbers read off it (zone percentages, medians, hold odds) stay close to the raw hold rate. Higher = rounder curves.", display = display.none)
showBand   = input.bool(false, "Confidence band", group = G_CRV, tooltip = "Off by default: the painted curves already show the gap. On: a 95% band at each age around the leading side's curve, shown once each side has 5 breaks inside the horizon; Greenwood's band widened for blocks that live through the same price moves.", display = display.none)
linkZones  = input.bool(true, "Link zones to curve", group = G_CRV, tooltip = "Each zone drawn on price gets a numbered circle and the share of blocks that reach its age, or at most the curve's end value (≤) with the block's age in brackets once it has outlived the curve. The same numbered circle sits on its side's curve at the zone's age.", display = display.none)
showPanel  = input.bool(true, "Show panel", group = G_PNL, tooltip = "The nearest bear block above price and bull block below it with their odds of holding, which side's blocks hold longer and whether that gap could be chance, each side's median life and the live block count. Every count is taken on closed bars only.", display = display.none)
panelPos   = input.string("Top right", "Position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = G_PNL, tooltip = "Corner of the chart the panel sits in. Top left shares its corner with TradingView's own chart legend.", display = display.none)
panelTxt   = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = G_PNL, tooltip = "Size of the panel text.", display = display.none)
holdWin    = input.int(20, "Hold window (bars)", minval = 1, maxval = 200, group = G_PNL, tooltip = "The panel's odds that the nearest support and resistance blocks hold this many more bars, given how long each has already held. Odds are given while the block's age plus this window stays inside the curve horizon.", display = display.none)

const color UP_COL    = #00E676
const color DN_COL    = #FF1744
const color MUTED_COL = #9598A1
const color NUM_COL   = #131722
const int   ZONE_END  = 7      // bars past the live bar where the zones end
const int   MAX_LIVE  = 60     // live blocks tracked per side; the oldest past this stops being tracked
const int   PAST_MAX  = 4990   // furthest back a zone starts: inside the 5,000 bars of bar times reserved below
const int   MIN_EV    = 5      // breaks per side before the lead is tested and painted
const float SIG_P     = 0.05   // p value below which the lead is read as unlikely to be chance
fg = chart.fg_color

max_bars_back(time, 5000)

chan(float v) =>
    u = v / 255.0
    u <= 0.03928 ? u / 12.92 : math.pow((u + 0.055) / 1.055, 2.4)
lum(color c) =>
    0.2126 * chan(color.r(c)) + 0.7152 * chan(color.g(c)) + 0.0722 * chan(color.b(c))
ink(color c) =>
    a = lum(c)
    b = lum(chart.bg_color)
    (math.max(a, b) + 0.05) / (math.min(a, b) + 0.05) >= 3.0 ? c : fg
light    = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color) > 140
upTxt    = ink(light ? #007A36 : UP_COL)
dnTxt    = ink(light ? #D3002D : DN_COL)
mutedTxt = ink(light ? #6A6D78 : MUTED_COL)

type OB
    float top
    float bot
    int   side        // 1 = bull, -1 = bear
    int   bornBar     // bar of the structure break that created it
    int   obBar       // bar of the order block candle

type Life
    int  born
    int  age
    bool broke

var array<OB>       bulls     = array.new<OB>()
var array<OB>       bears     = array.new<OB>()
var array<Life>     bullLives = array.new<Life>()
var array<Life>     bearLives = array.new<Life>()
var array<polyline> polys     = array.new<polyline>()
var array<line>     lns       = array.new<line>()
var array<label>    lbls      = array.new<label>()
var float lastPH  = na
var float lastPL  = na
var bool  phLive  = false
var bool  plLive  = false
var float visHi   = na
var float visLo   = na
var int   visBars = 0

ph = ta.pivothigh(high, pivotLen, pivotLen)
pl = ta.pivotlow(low, pivotLen, pivotLen)

if time >= chart.left_visible_bar_time
    visBars += 1
    visHi := na(visHi) ? high : math.max(visHi, high)
    visLo := na(visLo) ? low : math.min(visLo, low)

heldAge(OB o) =>
    bar_index - o.bornBar - (barstate.isconfirmed ? 0 : 1)

breakCheck(array<OB> obs, array<Life> lives) =>
    if obs.size() > 0
        for i = obs.size() - 1 to 0
            ob = obs.get(i)
            if ob.side == 1 ? close < ob.bot : close > ob.top
                lives.push(Life.new(ob.bornBar, bar_index - ob.bornBar, true))
                obs.remove(i)

addOB(array<OB> obs, array<Life> lives, int side, float top, float bot, int obX) =>
    bool dup = false
    for o in obs
        if o.obBar == obX
            dup := true
            break
    if not dup
        obs.push(OB.new(top, bot, side, bar_index, obX))
        if obs.size() > MAX_LIVE
            old = obs.shift()
            lives.push(Life.new(old.bornBar, bar_index - old.bornBar, false))

obDist(OB o) =>
    close > o.top ? close - o.top : close < o.bot ? o.bot - close : 0.0

lifeTable(array<Life> lives, array<OB> obs) =>
    array<Life> out = lives.copy()
    for o in obs
        out.push(Life.new(o.bornBar, heldAge(o), false))
    out

km(array<Life> lf) =>
    ev  = array.new<int>(horizon + 1, 0)
    cnt = array.new<int>(horizon + 2, 0)
    for b in lf
        k = math.min(b.age, horizon + 1)
        cnt.set(k, cnt.get(k) + 1)
        if b.broke and b.age <= horizon
            ev.set(k, ev.get(k) + 1)
    risk = array.new<int>(horizon + 1, 0)
    int acc = cnt.get(horizon + 1)
    for t = horizon to 1
        acc += cnt.get(t)
        risk.set(t, acc)
    s = array.new<float>(horizon + 1, 1.0)
    float sv = 1.0
    for t = 1 to horizon
        d = ev.get(t)
        if d > 0
            sv *= 1.0 - float(d) / risk.get(t)
        s.set(t, sv)
    [s, ev, risk]

greenwood(array<float> s, array<int> ev, array<int> risk) =>
    array<float> g = array.new<float>(horizon + 1, 0.0)
    float gw = 0.0
    for t = 1 to horizon
        n = risk.get(t)
        d = ev.get(t)
        if n > d
            gw += float(d) / (n * (n - d))
        g.set(t, s.get(t) * s.get(t) * gw)
    g

lifeInfluence(array<float> s, array<int> ev, array<int> risk) =>
    array<float> area = array.new<float>(horizon + 2, 0.0)
    for t = horizon to 1
        area.set(t, area.get(t + 1) + s.get(t))
    array<float> bk = array.new<float>(horizon + 1, 0.0)
    array<float> sv = array.new<float>(horizon + 1, 0.0)
    for t = 1 to horizon
        n = risk.get(t)
        h = n > 0 ? float(ev.get(t)) / n : 0.0
        if n > 0 and h < 1.0
            bk.set(t, area.get(t) / ((1.0 - h) * n))
        sv.set(t, sv.get(t - 1) + bk.get(t) * h)
    [bk, sv]

clusterVar(array<float> cl) =>
    float sq = 0.0
    int   g  = 0
    for v in cl
        if v != 0.0
            sq += v * v
            g += 1
    [g > 1 ? sq * g / (g - 1) : na, g]

blockPsi(Life b, array<float> bk, array<float> sv) =>
    a = math.min(b.age, horizon)
    sv.get(a) - (b.broke and b.age <= horizon ? bk.get(a) : 0.0)

groupOf(Life b) =>
    int(b.born / (2 * horizon))

groupGap(array<Life> lf, array<float> bk, array<float> sv, array<float> clGap, float sign) =>
    for b in lf
        idx = groupOf(b)
        clGap.set(idx, clGap.get(idx) + sign * blockPsi(b, bk, sv))

bandWiden(array<Life> lf, array<float> bk, array<float> sv, int groups) =>
    array<float> cl = array.new<float>(groups, 0.0)
    float sq = 0.0
    for b in lf
        psi = blockPsi(b, bk, sv)
        idx = groupOf(b)
        cl.set(idx, cl.get(idx) + psi)
        sq += psi * psi
    [vC, gC] = clusterVar(cl)
    gC > 1 ? math.max(1.0, vC / sq) : 1.0

leadP(float gap, float v, int g) =>
    float p = na
    if g > 2
        nu = g - 1
        th = math.atan(math.abs(gap) / math.sqrt(v * nu))   // t = gap / sqrt(v), angle atan(|t| / sqrt(nu))
        c2 = math.pow(math.cos(th), 2)
        float term = 1.0
        float acc  = 1.0
        int   k    = 1
        if nu % 2 == 0
            while 2 * k < nu
                term *= c2 * (2.0 * k - 1.0) / (2.0 * k)
                acc += term
                k += 1
            p := 1.0 - math.sin(th) * acc
        else
            while 2 * k + 3 <= nu
                term *= c2 * (2.0 * k) / (2.0 * k + 1.0)
                acc += term
                k += 1
            p := 1.0 - 2.0 / math.pi * (th + math.sin(th) * math.cos(th) * acc)
        p := math.max(0.0, p)
    p

bound(array<float> s, array<float> g, float z) =>
    array<float> out = array.new<float>(horizon + 1, 1.0)
    for t = 1 to horizon
        out.set(t, math.max(0.0, math.min(1.0, s.get(t) + z * math.sqrt(g.get(t)))))
    out

rising(array<float> y) =>
    array<float> vals = array.new<float>()
    array<int>   lens = array.new<int>()
    for v in y
        vals.push(v)
        lens.push(1)
        while vals.size() > 1
            n = vals.size()
            if vals.get(n - 2) <= vals.get(n - 1)
                break
            v2 = vals.pop()
            l2 = lens.pop()
            l1 = lens.get(n - 2)
            vals.set(n - 2, (vals.get(n - 2) * l1 + v2 * l2) / (l1 + l2))
            lens.set(n - 2, l1 + l2)
    array<float> out = array.new<float>()
    for [i, v] in vals
        for k = 1 to lens.get(i)
            out.push(v)
    out

convexKM(array<float> s) =>
    array<float> d = array.new<float>()
    for t = 1 to horizon
        d.push(s.get(t) - s.get(t - 1))
    d := rising(d)
    array<float> e = array.new<float>(horizon, 0.0)
    for t = 0 to horizon - 1
        sg = math.max(0.5, math.min(smoothBars, (t + 1) / 3.0))
        r  = int(math.ceil(3.0 * sg))
        float acc  = 0.0
        float wsum = 0.0
        for j = -r to r
            w = math.exp(-0.5 * j * j / (sg * sg))
            acc  += w * d.get(math.max(0, math.min(horizon - 1, t + j)))
            wsum += w
        e.set(t, acc / wsum)
    e := rising(e)
    float k = e.sum() != 0.0 ? d.sum() / e.sum() : 0.0
    array<float> out = array.new<float>(horizon + 1, 1.0)
    float lvl = 1.0
    for t = 1 to horizon
        lvl += k * e.get(t - 1)
        out.set(t, math.max(0.0, lvl))   // float rounding at a fully broken tail would otherwise print -0%
    out

sampleCols(array<float> sm) =>
    array<float> c = array.new<float>(curveW + 1, 1.0)
    for k = 0 to curveW
        a  = float(k) * horizon / curveW
        i0 = int(math.floor(a))
        i1 = math.min(i0 + 1, horizon)
        f  = a - i0
        c.set(k, sm.get(i0) * (1.0 - f) + sm.get(i1) * f)
    c

colOf(int age) =>
    int(math.round(float(age) * curveW / horizon))

barsTxt(int n) =>
    str.tostring(n) + (n == 1 ? " bar" : " bars")
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)

oddsPct(array<float> sm, int age) =>
    age > horizon ? "≤" + str.tostring(100.0 * sm.get(horizon), "#") + "% (" + str.tostring(age) + " bars)" : str.tostring(100.0 * sm.get(age), "#") + "%"

holdOdds(array<float> sm, int age) =>
    string out = "—"
    if age > horizon
        out := "outlived " + str.tostring(horizon) + " bars"
    else if age + holdWin > horizon
        out := "window runs past the " + str.tostring(horizon) + "-bar horizon · " + barsTxt(age) + " old"
    else if sm.get(age) > 0
        out := str.tostring(100.0 * sm.get(age + holdWin) / sm.get(age), "#") + "% · " + barsTxt(age) + " old"
    out

medianAge(array<float> sm) =>
    int m = na
    for t = 1 to horizon
        if sm.get(t) <= 0.5
            m := t
            break
    m

drawCurve(array<float> c, int x0, float yBot, float span, color col) =>
    array<chart.point> pts = array.new<chart.point>()
    for k = 0 to curveW
        pts.push(chart.point.from_index(x0 + k, yBot + c.get(k) * span))
    polys.push(polyline.new(pts, curved = true, line_color = col, line_width = 3))

drawBand(array<float> cu, array<float> cl, int x0, float yBot, float span, color col) =>
    array<chart.point> pts = array.new<chart.point>()
    for k = 0 to curveW
        pts.push(chart.point.from_index(x0 + k, yBot + cu.get(k) * span))
    for k = curveW to 0
        pts.push(chart.point.from_index(x0 + k, yBot + cl.get(k) * span))
    polys.push(polyline.new(pts, closed = true, line_color = color.new(col, 100), fill_color = color.new(col, 82)))

paintHero(array<float> lag, array<float> lead, int x0, float yBot, float span, color lagCol, color leadCol, bool lagOn, bool leadOn) =>
    lagT  = array.from(84, 76, 67, 58)
    leadT = array.from(81, 72, 61, 50)
    for j = 0 to 3
        ka = j / 4.0
        kb = (j + 1) / 4.0
        if lagOn
            array<chart.point> a = array.new<chart.point>()
            for k = 0 to curveW
                a.push(chart.point.from_index(x0 + k, yBot + kb * lag.get(k) * span))
            for k = curveW to 0
                a.push(chart.point.from_index(x0 + k, yBot + ka * lag.get(k) * span))
            polys.push(polyline.new(a, false, true, line_color = na, fill_color = color.new(lagCol, lagT.get(j))))
        if leadOn
            array<chart.point> b = array.new<chart.point>()
            for k = 0 to curveW
                b.push(chart.point.from_index(x0 + k, yBot + (lag.get(k) + kb * math.max(0.0, lead.get(k) - lag.get(k))) * span))
            for k = curveW to 0
                b.push(chart.point.from_index(x0 + k, yBot + (lag.get(k) + ka * math.max(0.0, lead.get(k) - lag.get(k))) * span))
            polys.push(polyline.new(b, false, true, line_color = na, fill_color = color.new(leadCol, leadT.get(j))))

zoneLayer(int xa, int xb, int nose, float mid, float a, color c) =>
    if xb - xa >= 2
        r = math.min(nose, xb - xa - 1)
        array<chart.point> pts = array.new<chart.point>()
        pts.push(chart.point.from_index(xa, mid))
        for x = xa + 1 to xa + r
            u = float(x - xa) / r
            pts.push(chart.point.from_index(x, mid + a * math.sqrt(u * (2.0 - u))))
        pts.push(chart.point.from_index(xb, mid + a))
        pts.push(chart.point.from_index(xb, mid - a))
        for x = xa + r to 

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