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

Quiet Range Tracker

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

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

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

О программе

Quiet Range Tracker — индикатор TradingView, который выявляет периоды консолидации цены, называемые «тихими диапазонами». Диапазон считается тихим, если его высота (разница между максимальным максимумом и минимальным минимумом за заданное число баров) ниже определённого кратного значения ATR. Для каждого такого диапазона индикатор фиксирует прямоугольник и рассчитывает уровни выхода за его границы, которые активируются только при закрытии бара за пределами уровня.

Индикатор отображает замороженные коробки, уровни выхода, маркеры реальных выходов, линии стоп-лосса и целей, а также предоставляет информационную панель с текущим состоянием обнаруженных диапазонов и позиций. Доступны настройки фильтрации по более высокому таймфрейму и силе тренда (ADX), а также адаптивное сглаживание ATR.

Поддерживаются условные оповещения TradingView для открытия и закрытия позиций, достижения целей и срабатывания стоп-лосса. Вебхуки отправляют сообщения с действиями, направлениями, ценами входа, стопа и целей. Индикатор работает только на стандартных графиках.

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

НастройкаОписание
i_boxLen Количество баров, чей максимальный максимум и минимальный минимум формируют коробку.
i_atrLen Период ATR, используемый для определения тихости коробки.
i_thr Кратное ATR, при котором коробка считается тихой: высота коробки ниже этого значения. 2.5 — более свободная настройка.
i_exitMult Кратное нормального ATR, определяющее уровни выхода. Реальный выход — это закрытие бара за границей замороженной коробки плюс или минус это кратное. Прикосновение без закрытия не считается выходом.
i_normLen Количество баров для расчёта нормального ATR — медианы ATR за этот период. Новые коробки не начинаются, пока ATR не накопит столько значений.
i_fHtf Включает подтверждение по более высокому таймфрейму: для длинной позиции последний реальный выход на более высоком таймфрейме должен быть вверх, для короткой — вниз. Более низкий таймфрейм чем график пропускается и отображается на панели.
i_htf Таймфрейм подтверждения. Не должен быть ниже таймфрейма графика; равный допускается.
i_fAdx Включает дополнительное требование: значение ADX на баре сигнала должно быть не ниже порога силы тренда.
i_adxLen Период ADX, используемый фильтром силы тренда.
i_adxThr Минимальное значение ADX, при котором допускается сделка при включённом фильтре силы тренда.
i_smMode Метод сглаживания ATR перед расчётом коробки и уровней выхода. None оставляет ATR сырым. Подтверждение по более высокому таймфрейму использует ту же настройку.
i_smLen Период адаптивного сглаживания. Не работает, когда сглаживание установлено в None.
i_lock Замораживает текущую позицию, блокирует новые сигналы. Текущая сделка на графике остаётся, отслеживание цели и стопа и оповещения продолжают работу. Коробки, начавшиеся после заблокированной сделки, скрываются.
i_showBox Рисует замороженную коробку. При отключении скрывается только отрисовка; обнаружение, сделки, оповещения и панель продолжают работать.
i_showLvl Рисует два уровня выхода каждой коробки. При отключении скрывается только отрисовка.
i_showMk Отмечает бар, где происходит реальный выход. При отключении скрывается только отрисовка.
i_maxSets Количество последних коробок, сохраняемых на графике; более старые чертежи удаляются. Остальные функции не затронуты.
i_dashShow Отображает таблицу информационной панели.
i_dashPos Угол графика, в котором отрисовывается информационная панель.
i_actLong Слово, отправляемое как действие вебхука при открытии длинной позиции.
i_actShort Слово, отправляемое как действие вебхука при открытии короткой позиции.
i_actCL Слово, отправляемое как действие вебхука при закрытии длинной позиции — по последней цели, стопу, короткой позицией или новым сигналом длинной позиции.
i_actCS Слово, отправляемое как действие вебхука при закрытии короткой позиции — по последней цели, стопу, длинной позицией или новым сигналом короткой позиции.
i_actPL Слово, отправляемое как действие вебхука при достижении не последней цели длинной позиции.
i_actPS Слово, отправляемое как действие вебхука при достижении не последней цели короткой позиции.
C_BD Цвет границы коробки, которая ещё наблюдается.
C_WFILL Цвет заливки коробки, которая ещё наблюдается.
C_FILL Цвет заливки коробки после её реального выхода.
C_EXU Цвет верхнего уровня выхода, коробки с выходом вверх и его маркера.
C_EXD Цвет нижнего уровня выхода, коробки с выходом вниз и его маркера.
C_SL Цвет линии стоп-лосса и её метки.
C_ENT Цвет линии входа и её метки.
C_TP Цвет меток целей и линии TP3. Линии TP1 и TP2 — приглушённые копии.
C_MTX Цвет текста маркеров на графике и меток позиций.
C_SUP Цвет длинной позиции, бычьего показателя и строки фильтра, прошедшего проверку.
C_RES Цвет короткой позиции, медвежьего показателя, срабатывания стоп-лосса и строки фильтра, не прошедшего проверку.
C_DASH_BG Фон строк информационной панели.
C_DASH_HDR Фон заголовка информационной панели.
C_DASH_TXT Цвет текста информационной панели.
C_WARN Фон строки панели с предупреждением о пропущенной настройке.

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

indicator(title = "Quiet Range Tracker", overlay = true, max_lines_count = 402, max_labels_count = 105, max_boxes_count = 201)

const string GRP_CORE = "⚙️ Core Settings"
const string GRP_FLT  = "🕯️ Filters"
const string GRP_TRD  = "📐 Trade Tools"
const string GRP_VIS  = "🎨 Visuals"
const string GRP_DASH = "📊 Dashboard"
const string GRP_ALR  = "🔔 Alerts"
const string GRP_COL  = "🌈 Colors"

i_boxLen   = input.int(12, "Box Length", minval = 2, maxval = 100, tooltip = "Number of bars whose highest high and lowest low form the box.", group = GRP_CORE)
i_atrLen   = input.int(14, "ATR Length", minval = 1, maxval = 100, tooltip = "ATR length used to judge whether the box is quiet.", group = GRP_CORE)
i_thr      = input.float(2.5, "Quiet Threshold", options = [2.0, 2.5], tooltip = "The box is quiet when its height is below this multiple of the ATR. 2.5 is the looser setting.", group = GRP_CORE)
i_exitMult = input.float(2.0, "Exit Distance", minval = 0.1, maxval = 10.0, step = 0.1, tooltip = "A real exit is a bar closing beyond the frozen box edge plus or minus this multiple of the normal ATR. A touch without a close is not an exit.", group = GRP_CORE)
i_normLen  = input.int(250, "Normal ATR Lookback", minval = 20, maxval = 1000, tooltip = "Normal ATR is the median of the ATR over this many bars. No box starts until the ATR has produced this many readings.", group = GRP_CORE)

i_fHtf     = input.bool(false, "Higher Timeframe Confirmation", tooltip = "A long additionally needs the last real exit of the Higher Timeframe to be up, and a short needs it to be down. The Higher Timeframe is found by the same calculation and the same settings as the chart, and only closed Higher Timeframe bars are read. A Higher Timeframe lower than the chart timeframe is skipped and shown on the dashboard. Turning it off stops this calculation.", group = GRP_FLT)
i_htf      = input.timeframe("240", "Higher Timeframe", tooltip = "Timeframe of the confirmation. It must not be lower than the chart timeframe; equal is allowed.", group = GRP_FLT)
i_fAdx     = input.bool(false, "Trend Strength Filter", tooltip = "A trade additionally needs the ADX on the signal bar to be at or above the Trend Strength Threshold.", group = GRP_FLT)
i_adxLen   = input.int(14, "Trend Strength Length", minval = 1, maxval = 100, tooltip = "Length of the ADX used by the Trend Strength Filter.", group = GRP_FLT)
i_adxThr   = input.float(20.0, "Trend Strength Threshold", minval = 1.0, maxval = 100.0, step = 0.5, tooltip = "Lowest ADX reading at which a trade is allowed while the Trend Strength Filter is on.", group = GRP_FLT)
i_smMode   = input.string("None", "Adaptive Smoothing", options = ["None", "SMA", "EMA", "WMA", "RMA", "HMA"], tooltip = "Smooths the ATR before any box or exit level is calculated from it. None leaves the ATR raw. The Higher Timeframe confirmation uses the same setting.", group = GRP_FLT)
i_smLen    = input.int(5, "Smoothing Length", minval = 2, maxval = 100, tooltip = "Length of the Adaptive Smoothing. It does nothing while Adaptive Smoothing is None.", group = GRP_FLT)

i_lock     = input.bool(false, "Lock Signal", tooltip = "Freeze current signal · block new ones. The trade on the chart stays, and its target and stop tracking and alerts keep running. Boxes that start after the locked trade are hidden until the lock is turned off.", group = GRP_TRD)

i_showBox  = input.bool(true, "Show Box", tooltip = "Draws the frozen box. Turning it off hides the drawing only; detection, trades, alerts and the dashboard keep running.", group = GRP_VIS)
i_showLvl  = input.bool(true, "Show Exit Levels", tooltip = "Draws the two exit levels of each box. Turning it off hides the drawing only.", group = GRP_VIS)
i_showMk   = input.bool(true, "Show Markers", tooltip = "Marks the bar where a real exit happens. Turning it off hides the drawing only.", group = GRP_VIS)
i_maxSets  = input.int(50, "Max Boxes Shown", minval = 2, maxval = 100, tooltip = "Keeps this many of the latest boxes on the chart and removes older drawings. It removes drawings only; detection, trades, alerts and the dashboard are not affected.", group = GRP_VIS)

i_dashShow = input.bool(true, "Show Dashboard", tooltip = "Shows the dashboard table.", group = GRP_DASH)
i_dashPos  = input.string("Top Right", "Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], tooltip = "Corner of the chart where the dashboard is drawn.", group = GRP_DASH)

i_actLong  = input.string("long", "↑ Long Action", tooltip = "Word sent as the action of the webhook message when a long trade opens.", group = GRP_ALR)
i_actShort = input.string("short", "↓ Short Action", tooltip = "Word sent as the action of the webhook message when a short trade opens.", group = GRP_ALR)
i_actCL    = input.string("closelong", "✕ Close Long Action", tooltip = "Word sent as the action when a long trade is closed by its last target, by its stop, by a short trade or by a new long signal that replaces it.", group = GRP_ALR)
i_actCS    = input.string("closeshort", "✕ Close Short Action", tooltip = "Word sent as the action when a short trade is closed by its last target, by its stop, by a long trade or by a new short signal that replaces it.", group = GRP_ALR)
i_actPL    = input.string("partialcloselong", "✕ Partial Close Long Action", tooltip = "Word sent as the action when a target that is not the last one is hit on a long trade.", group = GRP_ALR)
i_actPS    = input.string("partialcloseshort", "✕ Partial Close Short Action", tooltip = "Word sent as the action when a target that is not the last one is hit on a short trade.", group = GRP_ALR)

C_BD       = input.color(#ffeb3b, "Box Border", tooltip = "Border of a box that is still being watched.", group = GRP_COL)
C_WFILL    = input.color(color.new(#ffeb3b, 85), "Watched Box Fill", tooltip = "Fill of a box that is still being watched.", group = GRP_COL)
C_FILL     = input.color(color.new(#7e57c2, 88), "Box Fill", tooltip = "Fill of a box after its real exit.", group = GRP_COL)
C_EXU      = input.color(#26a69a, "Exit Up", tooltip = "Colour of the upper exit level, of a box that ended with a real exit up, and of its marker.", group = GRP_COL)
C_EXD      = input.color(#ef5350, "Exit Down", tooltip = "Colour of the lower exit level, of a box that ended with a real exit down, and of its marker.", group = GRP_COL)
C_SL       = input.color(#ef5350, "Stop", tooltip = "Colour of the stop line and its label.", group = GRP_COL)
C_ENT      = input.color(#2196f3, "Entry", tooltip = "Colour of the entry line and its label.", group = GRP_COL)
C_TP       = input.color(#26a69a, "Targets", tooltip = "Colour of the target labels and of the TP3 line. The TP1 and TP2 lines are faded copies of it.", group = GRP_COL)
C_MTX      = input.color(#ffffff, "Marker Text", tooltip = "Text colour of the chart markers and of the trade labels.", group = GRP_COL)
C_SUP      = input.color(#26a69a, "Bullish", tooltip = "Colour of a long trade, of a bullish reading and of a filter row that passes.", group = GRP_COL)
C_RES      = input.color(#ef5350, "Bearish", tooltip = "Colour of a short trade, of a bearish reading, of a hit stop and of a filter row that fails.", group = GRP_COL)
C_DASH_BG  = input.color(color.new(#0a0f1a, 10), "Dashboard Background", tooltip = "Background of the dashboard rows.", group = GRP_COL)
C_DASH_HDR = input.color(color.new(#3a2a6d, 55), "Dashboard Header", tooltip = "Background of the dashboard header row.", group = GRP_COL)
C_DASH_TXT = input.color(#ffffff, "Dashboard Text", tooltip = "Text colour of the dashboard.", group = GRP_COL)
C_WARN     = input.color(color.new(#f9a825, 80), "Dashboard Warning", tooltip = "Background of a dashboard row that warns a setting was skipped.", group = GRP_COL)

type BoxSet
    box bx
    line upLn
    line dnLn
    label mk
    int st
    bool hid

const int DASH_ROWS = 24

f_tf() =>
    int m = timeframe.multiplier
    string r = str.tostring(m) + "M"
    if timeframe.isseconds
        r := str.tostring(m) + "s"
    else if timeframe.isticks
        r := str.tostring(m) + "t"
    else if timeframe.isminutes
        r := m % 60 == 0 ? str.tostring(math.floor(m / 60)) + "H" : str.tostring(m) + "m"
    else if timeframe.isdaily
        r := str.tostring(m) + "D"
    else if timeframe.isweekly
        r := str.tostring(m) + "W"
    r

f_abbr(float v) =>
    float a = math.abs(v)
    float r0 = math.round(a, 2)
    float rk = math.round(a / 1000, 1)
    float rm = math.round(a / 1000000, 1)
    float rb = math.round(a / 1000000000, 1)
    string body = r0 < 1000 ? str.tostring(r0, "0.##") : rk < 1000 ? str.tostring(rk, "0.#") + "K" : rm < 1000 ? str.tostring(rm, "0.#") + "M" : str.tostring(rb, "0.#") + "B"
    na(v) ? "—" : (v < 0 ? "-" : "") + body

f_esc(string s) =>
    str.replace_all(str.replace_all(s, "\\", "\\\\"), "\"", "\\\"")

f_pos(string p) =>
    switch p
        "Top Left" => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left" => position.bottom_left
        => position.top_right

f_q(float v) =>
    na(v) ? "null" : "\"" + str.tostring(v, format.mintick) + "\""

f_entryPayload(string actWord, string dir, float en, float sl, float t1, float t2, float t3) =>
    string inner = str.format('"action":"{0}","ticker":"{1}","tf":"{2}","direction":"{3}","entry":{4},"sl":{5},"tp1":{6},"tp2":{7},"tp3":{8}', f_esc(actWord), f_esc(syminfo.tickerid), f_esc(timeframe.period), dir, f_q(en), f_q(sl), f_q(t1), f_q(t2), f_q(t3))
    "{" + inner + "}"

f_closePayload(string actWord, string dir, float en, float px, float sl, string why) =>
    string inner = str.format('"action":"{0}","ticker":"{1}","tf":"{2}","direction":"{3}","entry":{4},"price":{5},"sl":{6},"reason":"{7}"', f_esc(actWord), f_esc(syminfo.tickerid), f_esc(timeframe.period), dir, f_q(en), f_q(px), f_q(sl), why)
    "{" + inner + "}"

f_pctTxt(float lvl, float entry, bool isLong) =>
    float p = (isLong ? lvl - entry : entry - lvl) / entry * 100
    (p >= 0 ? "+" : "") + str.tostring(p, "0.00") + "%"

f_del(BoxSet o) =>
    if not na(o.bx)
        box.delete(o.bx)
    if not na(o.upLn)
        line.delete(o.upLn)
    if not na(o.dnLn)
        line.delete(o.dnLn)
    if not na(o.mk)
        label.delete(o.mk)
    o

f_put(table t, int r, string lbl, string val, color vc, string tip) =>
    color bg = r % 2 == 1 ? C_DASH_BG : color.new(C_DASH_BG, 40)
    table.cell(t, 0, r, "  " + lbl, text_color = color.new(C_DASH_TXT, 25), text_halign = text.align_left, text_size = size.small, bgcolor = bg, tooltip = tip)
    table.cell(t, 1, r, val + "  ", text_color = vc, text_halign = text.align_right, text_size = size.small, bgcolor = bg)
    r + 1

f_warn(table t, int r, string lbl, string val, string tip) =>
    table.cell(t, 0, r, "  " + lbl, text_color = color.new(C_DASH_TXT, 25), text_halign = text.align_left, text_size = size.small, bgcolor = C_WARN, tooltip = tip)
    table.cell(t, 1, r, val + "  ", text_color = C_DASH_TXT, text_halign = text.align_right, text_size = size.small, bgcolor = C_WARN)
    r + 1

f_smooth(float src, string m, int len) =>
    float vS = ta.sma(src, len)
    float vE = ta.ema(src, len)
    float vW = ta.wma(src, len)
    float vR = ta.rma(src, len)
    float vH = ta.hma(src, len)
    switch m
        "SMA" => vS
        "EMA" => vE
        "WMA" => vW
        "RMA" => vR
        "HMA" => vH
        => src

f_htf(int pBox, int pAtr, float pThr, float pMult, int pNorm, string pSm, int pSmLen) =>
    float xAtr = f_smooth(ta.atr(pAtr), pSm, pSmLen)
    float xHi = ta.highest(high, pBox)
    float xLo = ta.lowest(low, pBox)
    float xMed = ta.median(xAtr, pNorm)
    int xLeft = time[pBox - 1]
    var int xCnt = 0
    if not na(xAtr)
        xCnt += 1
    float xNorm = xCnt >= pNorm ? xMed : na
    bool xQuiet = bar_index >= pBox - 1 and not na(xHi) and not na(xLo) and not na(xAtr) and not na(xLeft) and (xHi - xLo) < pThr * xAtr
    var bool xOn = false
    var float xUl = float(na)
    var float xDl = float(na)
    int xCd = 0
    if xOn
        bool xU = close > xUl
        bool xD = xDl > 0 and close < xDl
        if xU or xD
            xOn := false
            xCd := xU ? 1 : 2
    else if xQuiet and not na(xNorm)
        xOn := true
        xUl := math.round_to_mintick(xHi + pMult * xNorm)
        xDl := math.round_to_mintick(xLo - pMult * xNorm)
    xCd[1]

bool stdChart = chart.is_standard
float atrRaw   = ta.atr(i_atrLen)
float atrV     = f_smooth(atrRaw, i_smMode, i_smLen)
float boxHi   = ta.highest(high, i_boxLen)
float boxLo   = ta.lowest(low, i_boxLen)
float medV    = ta.median(atrV, i_normLen)
int leftT     = time[i_boxLen - 1]

var int atrCnt = 0
if not na(atrV)
    atrCnt += 1

float normAtr = atrCnt >= i_normLen ? medV : na
bool isQuiet  = bar_index >= i_boxLen - 1 and not na(boxHi) and not na(boxLo) and not na(atrV) and not na(leftT) and (boxHi - boxLo) < i_thr * atrV

var bool act         = false
var float bHi        = float(na)
var float bLo        = float(na)
var float upLv       = float(na)
var float dnLv       = float(na)
var int sIdx         = int(na)
var int sLeft        = int(na)
var int wAge         = 0
var string lastRes   = "—"
var int lastBars     = 0
var int lastDir        = 0

bool evStart = false
bool evUp    = false
bool evDn    = false

if barstate.isconfirmed and stdChart
    if act
        int age = bar_index - sIdx
        wAge   := age
        evUp   := close > upLv
        evDn   := dnLv > 0 and close < dnLv
        if evUp or evDn
            act      := false
            lastRes  := evUp ? "Exit Up" : "Exit Down"
            lastBars := age
            lastDir  := evUp ? 1 : -1
    else if isQuiet and not na(normAtr)
        act    := true
        evStart := true
        bHi    := boxHi
        bLo    := boxLo
        upLv   := math.round_to_mintick(boxHi + i_exitMult * normAtr)
        dnLv   := math.round_to_mintick(boxLo - i_exitMult * normAtr)
        sIdx   := bar_index
        sLeft  := leftT
        wAge   := 0

bool htfEq  = timeframe.in_seconds(i_htf) == timeframe.in_seconds()
bool htfOk  = i_fHtf and timeframe.in_seconds(i_htf) >= timeframe.in_seconds()
bool htfReq = htfOk and not htfEq and stdChart

int hCd = if htfReq
    request.security(syminfo.tickerid, i_htf, f_htf(i_boxLen, i_atrLen, i_thr, i_exitMult, i_normLen, i_smMode, i_smLen), lookahead = barmerge.lookahead_on)
else
    0

var int hDir = 0
if hCd == 1
    hDir := 1
else if hCd == 2
    hDir := -1

int htfDir = htfEq ? lastDir : hDir

[diP, diM, adxV] = ta.dmi(i_adxLen, i_adxLen)

bool fHtfL = not htfOk or htfDir == 1
bool fHtfS = not htfOk or htfDir == -1
bool fAdx  = not i_fAdx or (not na(adxV) and adxV >= i_adxThr)
bool sigL  = evUp and fHtfL and fAdx
bool sigS  = evDn and fHtfS and fAdx

var bool tOn      = false
var bool tHas     = false
var int tDir      = 0
var float tEn     = float(na)
var float tSl     = float(na)
var float tT1     = float(na)
var float tT2     = float(na)
var float tT3     = float(na)
var int tLast     = 0
var int tBar      = int(na)
var int tCloseBar = int(na)
var bool tH1      = false
var bool tH2      = false
var bool tH3      = false
var bool tSH      = false
var string tState = "—"

var line slLn  = line(na)
var line enLn  = line(na)
var line t1Ln  = line(na)
var line t2Ln  = line(na)
var line t3Ln  = line(na)
var label slLb = label(na)
var label enLb = label(na)
var label t1Lb = label(na)
var label t2Lb = label(na)
var label t3Lb = label(na)

f_delLevels() =>
    if not na(slLn)
        line.delete(slLn)
    if not na(enLn)
        line.delete(enLn)
    if not na(t1Ln)
        line.delete(t1Ln)
    if not na(t2Ln)
        line.delete(t2Ln)
    if not na(t3Ln)
        line.delete(t3Ln)
    if not na(slLb)
        label.delete(slLb)
 

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