Dober Stop Noise Map

DoberInvest · study · 161 行 · 点赞 18 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=6
indicator("Dober Stop Noise Map", shorttitle = "Dober Noise", overlay = true, max_boxes_count = 20, max_lines_count = 20, max_labels_count = 20)
 
// ════════════════════════════════════════════════════════════════════════
// Dober Stop Noise Map: где стоп выбивает обычный шум этого графика.
// Метод «случайного входа»: на каждом закрытом баре считаем, что кто-то вошёл по закрытию,
// и меряем, как далеко цена ушла ПРОТИВ него за следующие H баров (MAE, в ATR на момент входа).
// Из последних N таких входов строим распределение: стоп ближе медианы задевают 50 % входов,
// ближе 80-го перцентиля 20 % и так далее. Направление не угадываем: это шум, а не прогноз.
// Без перерисовки: выборка для входа на баре t завершается на баре t+H и дальше не меняется.
// ════════════════════════════════════════════════════════════════════════
 
// ── Палитра ──
D_TEAL  = #19D3F0
D_NAVY  = #04121A
D_NAVY2 = #0B1F38
D_GOLD  = #F5C542
D_RED   = #E5484D
D_GREY  = #7D8B99
D_TEXT  = #EAF2F5
 
gLang = "Language"
gNs   = "Noise sample"
gSt   = "Your stop"
gVis  = "Visuals"
 
LANG = input.string("English", "Chart language / Язык", options = ["English", "Русский"], group = gLang)
RU   = LANG == "Русский"
tr(string en, string ru) => RU ? ru : en
 
H       = input.int(20, "Horizon, bars", minval = 2, maxval = 300, group = gNs, tooltip = "How long a random entry is held. MAE is the deepest move against it within these bars. RU: сколько баров держим случайный вход.")
N       = input.int(500, "Sample size, entries", minval = 100, maxval = 5000, group = gNs, tooltip = "How many past random entries form the distribution. RU: сколько прошлых входов в выборке.")
atrLen  = input.int(14, "ATR length", minval = 2, maxval = 100, group = gNs)
pA      = input.float(50, "Level A, percentile", minval = 1, maxval = 99, group = gNs, tooltip = "A stop at this distance is touched by (100 - A)% of random entries. RU: стоп на этом расстоянии задевают (100 - A)% входов.")
pB      = input.float(80, "Level B, percentile", minval = 1, maxval = 99, group = gNs)
pC      = input.float(95, "Level C, percentile", minval = 1, maxval = 99, group = gNs)
sideSel = input.string("Both", "Show for", options = ["Both", "Long", "Short"], group = gNs)
 
stopPx  = input.price(0.0, "Your stop price (0 = off)", group = gSt, tooltip = "Optional. The table shows how often a stop at this distance from the last close was touched by random entries. RU: ваш стоп, по желанию.")
 
projBars  = input.int(20, "Zone length, bars", minval = 5, maxval = 200, group = gVis)
showHist  = input.bool(false, "Historical level B lines", group = gVis, tooltip = "Draws level B under and over price on every bar. Off by default: it is a noise envelope, not a trailing stop. RU: исторические линии уровня B.")
showTable = input.bool(true, "Table", group = gVis)
tablePos  = input.string("Top right", "Table position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = gVis)
 
// ── Серии (все ta.* на глобальном уровне) ──
atr    = ta.atr(atrLen)
lowH   = ta.lowest(low, H)
highH  = ta.highest(high, H)
entC   = close[H]
entA   = atr[H]
maeL   = entA > 0 ? math.max(0.0, (entC - lowH) / entA) : na
maeS   = entA > 0 ? math.max(0.0, (highH - entC) / entA) : na
 
// перцентили по скользящему окну для исторических линий
hLB = ta.percentile_nearest_rank(maeL, N, pB)
hSB = ta.percentile_nearest_rank(maeS, N, pB)
histOk = showHist and bar_index > H + N
plot(histOk and sideSel != "Short" ? close - hLB * atr : na, "Long noise B", color = color.new(D_TEAL, 60), style = plot.style_linebr)
plot(histOk and sideSel != "Long" ? close + hSB * atr : na, "Short noise B", color = color.new(D_RED, 60), style = plot.style_linebr)
 
// ── Выборка случайных входов (только закрытые бары) ──
var array<float> aL = array.new_float()
var array<float> aS = array.new_float()
if barstate.isconfirmed and not na(maeL) and not na(maeS)
    array.push(aL, maeL)
    array.push(aS, maeS)
    if array.size(aL) > N
        array.shift(aL)
        array.shift(aS)
 
// доля входов, у которых ход против позиции дошёл до k ATR
f_hit(array<float> a, float k) =>
    int cnt = 0
    int n = array.size(a)
    if n > 0
        for i = 0 to n - 1
            if array.get(a, i) >= k
                cnt += 1
    n > 0 ? 100.0 * cnt / n : na
 
f_pct(float v) =>
    na(v) ? "-" : str.tostring(v, "#") + "%"
 
f_pos(string p) =>
    p == "Top right" ? position.top_right : p == "Bottom right" ? position.bottom_right : p == "Top left" ? position.top_left : position.bottom_left
 
// ── Отрисовка на последнем баре ──
var box[]   zBoxes = array.new_box()
var label[] zLabs  = array.new_label()
var table   tb     = na
 
minN = 100
nNow = array.size(aL)
 
if barstate.islast
    for b in zBoxes
        box.delete(b)
    array.clear(zBoxes)
    for l in zLabs
        label.delete(l)
    array.clear(zLabs)
 
    if nNow >= minN and atr > 0
        lA = array.percentile_nearest_rank(aL, pA)
        lB = array.percentile_nearest_rank(aL, pB)
        lC = array.percentile_nearest_rank(aL, pC)
        sA = array.percentile_nearest_rank(aS, pA)
        sB = array.percentile_nearest_rank(aS, pB)
        sC = array.percentile_nearest_rank(aS, pC)
        x1 = bar_index + 1
        x2 = bar_index + projBars
        if sideSel != "Short"
            array.push(zBoxes, box.new(x1, close, x2, close - lA * atr, border_color = color.new(D_TEAL, 100), bgcolor = color.new(D_TEAL, 62)))
            array.push(zBoxes, box.new(x1, close - lA * atr, x2, close - lB * atr, border_color = color.new(D_TEAL, 100), bgcolor = color.new(D_TEAL, 78)))
            array.push(zBoxes, box.new(x1, close - lB * atr, x2, close - lC * atr, border_color = color.new(D_TEAL, 100), bgcolor = color.new(D_TEAL, 90)))
            array.push(zLabs, label.new(x2, close - lA * atr, tr("long stop here: hit by ", "стоп лонга тут: задели ") + f_pct(100 - pA), style = label.style_label_left, color = color.new(D_NAVY, 10), textcolor = D_TEXT, size = size.small))
            array.push(zLabs, label.new(x2, close - lB * atr, f_pct(100 - pB) + " · " + str.tostring(lB, "#.##") + " ATR", style = label.style_label_left, color = color.new(D_NAVY, 10), textcolor = D_TEAL, size = size.small))
            array.push(zLabs, label.new(x2, close - lC * atr, f_pct(100 - pC) + " · " + str.tostring(lC, "#.##") + " ATR", style = label.style_label_left, color = color.new(D_NAVY, 10), textcolor = D_GREY, size = size.small))
        if sideSel != "Long"
            array.push(zBoxes, box.new(x1, close + sA * atr, x2, close, border_color = color.new(D_RED, 100), bgcolor = color.new(D_RED, 66)))
            array.push(zBoxes, box.new(x1, close + sB * atr, x2, close + sA * atr, border_color = color.new(D_RED, 100), bgcolor = color.new(D_RED, 80)))
            array.push(zBoxes, box.new(x1, close + sC * atr, x2, close + sB * atr, border_color = color.new(D_RED, 100), bgcolor = color.new(D_RED, 91)))
            array.push(zLabs, label.new(x2, close + sA * atr, tr("short stop here: hit by ", "стоп шорта тут: задели ") + f_pct(100 - pA), style = label.style_label_left, color = color.new(D_NAVY, 10), textcolor = D_TEXT, size = size.small))
            array.push(zLabs, label.new(x2, close + sB * atr, f_pct(100 - pB) + " · " + str.tostring(sB, "#.##") + " ATR", style = label.style_label_left, color = color.new(D_NAVY, 10), textcolor = D_RED, size = size.small))
            array.push(zLabs, label.new(x2, close + sC * atr, f_pct(100 - pC) + " · " + str.tostring(sC, "#.##") + " ATR", style = label.style_label_left, color = color.new(D_NAVY, 10), textcolor = D_GREY, size = size.small))
 
    if showTable
        if not na(tb)
            table.delete(tb)
        tb := table.new(f_pos(tablePos), 3, 12, bgcolor = D_NAVY, frame_color = D_NAVY2, frame_width = 1, border_color = D_NAVY2, border_width = 1)
        table.cell(tb, 0, 0, tr("STOP NOISE · next ", "ШУМ СТОПА · за ") + str.tostring(H) + tr(" bars", " бар."), text_color = D_TEAL, text_size = size.small, text_halign = text.align_left)
        table.merge_cells(tb, 0, 0, 2, 0)
        if nNow < minN
            table.cell(tb, 0, 1, tr("Collecting sample: ", "Копим выборку: ") + str.tostring(nNow) + " / " + str.tostring(minN), text_color = D_GOLD, text_size = size.small)
            table.merge_cells(tb, 0, 1, 2, 1)
        else
            table.cell(tb, 0, 1, tr("Stop distance", "Расстояние стопа"), text_color = D_GREY, text_size = size.small, text_halign = text.align_left)
            table.cell(tb, 1, 1, tr("Long hit", "Лонг задет"), text_color = D_GREY, text_size = size.small)
            table.cell(tb, 2, 1, tr("Short hit", "Шорт задет"), text_color = D_GREY, text_size = size.small)
            ks = array.from(0.5, 1.0, 1.5, 2.0, 3.0)
            for j = 0 to 4
                k = array.get(ks, j)
                hl = f_hit(aL, k)
                hs = f_hit(aS, k)
                distPct = close > 0 ? 100 * k * atr / close : na
                table.cell(tb, 0, 2 + j, str.tostring(k, "#.#") + " ATR · " + str.tostring(distPct, "#.##") + "%", text_color = D_TEXT, text_size = size.small, text_halign = text.align_left)
                table.cell(tb, 1, 2 + j, f_pct(hl), text_color = color.from_gradient(hl, 5, 60, D_TEAL, D_RED), text_size = size.small)
                table.cell(tb, 2, 2 + j, f_pct(hs), text_color = color.from_gradient(hs, 5, 60, D_TEAL, D_RED), text_size = size.small)
            if stopPx > 0 and atr > 0
                isLong = stopPx < close
                d = math.abs(close - stopPx) / atr
                hy = isLong ? f_hit(aL, d) : f_hit(aS, d)
                table.cell(tb, 0, 7, tr("Your stop: ", "Ваш стоп: ") + str.tostring(d, "#.##") + " ATR (" + (isLong ? tr("long", "лонг") : tr("short", "шорт")) + ")", text_color = D_GOLD, text_size = size.small, text_halign = text.align_left)
                table.cell(tb, 1, 7, tr("hit by ", "задели ") + f_pct(hy), text_color = D_GOLD, text_size = size.small)
                table.merge_cells(tb, 1, 7, 2, 7)
            table.cell(tb, 0, 8, tr("Sample: ", "Выборка: ") + str.tostring(nNow) + tr(" random entries, ATR ", " случайных входов, ATR ") + str.tostring(atrLen), text_color = D_GREY, text_size = size.tiny, text_halign = text.align_left)
            table.merge_cells(tb, 0, 8, 2, 8)
            table.cell(tb, 0, 9, tr("Wick touch counts as hit. Past noise, not a forecast.", "Касание тенью = задет. Прошлый шум, не прогноз."), text_color = D_GREY, text_size = size.tiny, text_halign = text.align_left)
            table.merge_cells(tb, 0, 9, 2, 9)

← 返回列表