Regime Range Filter - Dynamic RSI Bands

Seckin_Tuncay · study · 584 行 · 点赞 58 · 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/
// © Seckin_Tuncay
// ══════════════════════════════════════════════════════════════════════════════
//  REGIME RANGE FILTER - DYNAMIC RSI BANDS   v1.3
//
//  EN: Range filter for trend flips + a reversal engine that hunts tops and
//      bottoms at the dynamic RSI bands, graded by RSI divergence and the
//      higher timeframe.
//  TR: Trend donusleri icin range filter + dinamik RSI bantlarinda tepe ve dip
//      arayan donus motoru. RSI uyumsuzlugu ve ust zaman dilimiyle derecelenir.
//
//  How it works
//    · Range filter: price must travel a multiple of its average move before
//      the line steps; a change of direction is a BULL / BEAR flip
//    · Dynamic RSI bands: the price at which RSI would reach its OWN recent
//      overbought / oversold percentile on the next bar
//    · Reversal engine: band touch + rejection candle, graded by RSI
//      divergence (diamond) and higher-timeframe alignment (star)
//    · Statistics panel: every raw signal is tracked to its target or stop
//      and reported as hit rate and average R, split by each filter. It is a
//      measuring tool, not a promise - results differ by symbol and timeframe
//
//  Credits
//    · Range filter formula: the open-source "Range Filter" by guikroth /
//      DonovanWall, re-implemented here
//    · RSI-to-price inversion: Giorgos Siligardos, "Reverse Engineering RSI",
//      Technical Analysis of Stocks and Commodities, 2003
//    · Inspired by Adaptive Range Filter (MarkitTick) and RSI Master
//      (SimpleAlgo); no code from either was used
// ══════════════════════════════════════════════════════════════════════════════
//@version=6
indicator("Regime Range Filter - Dynamic RSI Bands", shorttitle="RRF", overlay=true, max_labels_count=500)
 
// ══════════════ 1 · Range Filter ══════════════
gF      = "1 · Range Filter"
rfSrc   = input.source(close, "Source", group=gF)
rngMode = input.string("Classic", "Range base", options=["Classic", "ATR"], group=gF, tooltip="Classic: double EMA of the close-to-close move. Wicks are ignored.\nATR: average true range. Counts wicks and gaps.\nClassic: kapanis farkinin cift EMA'si. ATR: fitilleri ve gap'leri de sayar.")
rfLen   = input.int(50, "Sampling period", minval=5, group=gF, tooltip="Higher = slower filter, fewer flips.\nBuyuk = yavas filtre, daha az donus.")
rfMult  = input.float(2.5, "Multiplier (Classic)", minval=0.5, step=0.1, group=gF)
atrMult = input.float(1.5, "Multiplier (ATR)", minval=0.3, step=0.1, group=gF)
flipOn  = input.bool(true, "Show filter flips (BULL / BEAR)", group=gF)
confBar = input.bool(true, "Confirm signals on bar close only", group=gF, tooltip="ON: a signal is drawn only when the bar closes and never disappears.\nACIK iken sinyal ancak mum kapaninca cizilir ve bir daha kaybolmaz.")
 
// ══════════════ 2 · Reversal Engine ══════════════
gRv     = "2 · Reversal Engine"
revOn   = input.bool(true, "Reversal signals at dynamic bands", group=gRv, tooltip="TOP: price touched the dynamic upper band within the window, then a red candle closes back inside the band and below the previous candle's midpoint.\nBOTTOM: the mirror image at the lower band.\nWorks in any regime.\nTEPE: fiyat pencere icinde ust banda degdi, ardindan kirmizi mum bandin icine ve onceki mumun ortasinin altina kapandi. DIP: alt bantta tersi.")
revWin  = input.int(3, "Band touch window (bars)", minval=1, maxval=10, group=gRv, tooltip="How many bars back the band touch may be.\nBanda temasin kac bar geriye kadar sayilacagi.")
revSw   = input.int(3, "Divergence pivot length", minval=2, maxval=10, group=gRv, tooltip="Left bars of the price pivot used for RSI divergence (right side is 1 bar, so it stays early).\nUyumsuzlukta kullanilan fiyat pivotunun sol bar sayisi. Sag taraf 1 bar, gec kalmasin diye.")
revDiv  = input.bool(false, "Require RSI divergence", group=gRv, tooltip="OFF: divergence only grades the signal (◆). ON: no reversal without divergence.\nKAPALI: uyumsuzluk sadece derece verir (◆). ACIK: uyumsuzluk yoksa donus sinyali yok.")
revTgt  = input.float(2.0, "Reversal target (R)", minval=0.5, maxval=6.0, step=0.1, group=gRv, tooltip="Stop sits 0.2 ATR beyond the swing extreme (limited to 0.3 - 3 ATR). Target = this many times the stop distance.\nStop salinim ucunun 0.2 ATR otesinde. Hedef = stop mesafesinin bu kati.")
revCool = input.int(5, "Cooldown (bars)", minval=1, maxval=50, group=gRv)
 
// ══════════════ 3 · Dynamic RSI Bands ══════════════
gB       = "3 · Dynamic RSI Bands"
rsiLen   = input.int(14, "RSI Length", minval=2, group=gB)
obPct    = input.int(88, "Dynamic OB / OS percentiles", minval=70, maxval=99, group=gB, inline="ob", tooltip="The bands are the prices at which RSI would reach these percentiles of its own recent distribution - not fixed 70/30.\nBantlar, RSI'nin kendi dagiliminin bu yuzdeliklerine ulasacagi fiyatlardir.")
osPct    = input.int(12, "", minval=1, maxval=30, group=gB, inline="ob")
bandSm   = input.int(3, "Band smoothing", minval=1, maxval=20, group=gB)
showBand = input.bool(true, "Show bands", group=gB, inline="bd")
showGlow = input.bool(true, "Glow", group=gB, inline="bd")
 
// ══════════════ 4 · Regime (ADX) ══════════════
gRg     = "4 · Regime (ADX)"
diLen   = input.int(14, "DI Length", minval=1, group=gRg)
adxLen  = input.int(14, "ADX Smoothing", minval=1, group=gRg)
regGate = input.string("Off", "Filter flips in RANGE regime", options=["Soft", "Hard", "Off"], group=gRg, tooltip="Soft: flips in a RANGE regime are faded. Hard: hidden. Off: regime ignored.\nStatistics always see every raw flip, so the trend / range split can be compared on any symbol.\nSoft: sikismadaki donusler soluk. Hard: gizli. Istatistik her durumda tum ham sinyalleri gorur.")
 
// ══════════════ 5 · Higher Timeframe ══════════════
gM      = "5 · Higher Timeframe (MTF)"
htfGate = input.string("Soft", "Signals against higher TF", options=["Soft", "Hard", "Off"], group=gM, tooltip="Hidden signals are still counted in the statistics - check the Higher TF split on your own symbol before choosing Hard.\nGizlenen sinyaller istatistikte yine sayilir - Hard secmeden once kendi sembolunde Ust TF satirina bak.\n\nApplies to flips AND reversals. A TOP is aligned when the higher TF is not up, a BOTTOM when it is not down - a reversal with the bigger trend is a pullback ending.\nAlways read from the last CLOSED higher bar - no repainting.\nDonuslere de uygulanir. Ust TF yonunde donus = geri cekilmenin bitisi.")
mtfMode = input.string("Auto", "Higher period", options=["Auto", "Manual"], group=gM, tooltip="Auto ladder:\n<=3m -> 15m · <=15m -> 1h · 30m -> 2h · 1h -> 4h · 4h -> Daily · Daily -> Weekly")
mtfMan  = input.timeframe("240", "Manual period", group=gM)
 
// ══════════════ 6 · Room to Target ══════════════
gQ       = "6 · Room to Target"
roomGate = input.string("Off", "Flips with little room", options=["Soft", "Hard", "Off"], group=gQ, tooltip="A BULL flip needs room up to the upper band, a BEAR flip room down to the lower band.\nSoft: faded. Hard: hidden. Off: ignored.\nBULL icin ust banda, BEAR icin alt banda yeterli mesafe olmali.")
minRoom  = input.float(1.0, "Minimum room (ATR)", minval=0.0, step=0.1, group=gQ)
 
// ══════════════ 7 · Dynamic Multiplier ══════════════
gK      = "7 · Dynamic Multiplier"
useADX  = input.bool(false, "ADX factor", group=gK, tooltip="ADX high in its own history (trend) -> range narrows to x0.7. ADX low (range) -> widens to x1.3.\nADX kendi gecmisinde yuksek -> range daralir, dusuk -> genisler.")
useRSI  = input.bool(false, "RSI factor", group=gK, inline="rsi")
rsiMode = input.string("Tighten at extremes", "", options=["Tighten at extremes", "Widen at extremes"], group=gK, inline="rsi")
useVol  = input.bool(false, "Volume factor", group=gK, tooltip="Spot gold/forex volume is TICK volume. Try on exchange futures or stocks.\nSpot altin/forex hacmi tick hacmidir. Vadeli veya hissede dene.")
kSmLen  = input.int(14, "Multiplier smoothing", minval=1, maxval=50, group=gK)
 
// ══════════════ 8 · Signal Statistics ══════════════
gS      = "8 · Signal Statistics"
statsOn = input.bool(true, "Show statistics rows", group=gS, tooltip="Every raw signal is tracked until target or stop. Both on the same bar = LOSS. No result within max bars = closed at market (out of the hit rate, in the R average).\nAyni barda ikisi = KAYIP. Zaman asimi piyasadan kapatilir.")
rTgt    = input.float(2.0, "Flip target (ATR)", minval=0.2, maxval=10.0, step=0.1, group=gS)
rStop   = input.float(1.0, "Flip stop (ATR)", minval=0.2, maxval=10.0, step=0.1, group=gS)
maxHold = input.int(30, "Max bars to resolve", minval=5, maxval=300, group=gS)
statStart = input.time(timestamp("2026-01-01 00:00 +0000"), "Statistics start date", group=gS, tooltip="Signals from this date on are ALSO counted in a separate set. Set it to the day you stop changing settings: that set is then data the settings were never tuned on - the honest test.\nBu tarihten sonraki sinyaller ayrica ayri bir kumede sayilir. Ayarlarla oynamayi biraktigin gune kur: o kume ayarlarin hic gormedigi veridir - durust test.")
statView  = input.string("History", "Statistics view", options=["Both", "History", "Since start date"], group=gS, tooltip="Both: full history rows + a short since-start block.\nHistory: full history only.\nSince start date: every statistics row counts only from the start date.\nBoth: tum gecmis + baslangictan beri ozet. Since start date: tum satirlar sadece baslangictan beri.")
 
// ══════════════ 9 · Appearance ══════════════
gV        = "9 · Appearance"
panelLang = input.string("English", "Panel Language", options=["English", "Turkce"], group=gV)
showPanel = input.bool(true, "Info panel", group=gV)
pnlMode   = input.string("Normal", "Panel mode", options=["Normal", "Mini"], group=gV)
pnlPosStr = input.string("Top Right", "Panel position", options=["Top Right", "Middle Right", "Bottom Right", "Top Left", "Middle Left", "Bottom Left"], group=gV)
pnlSizStr = input.string("Small", "Panel text size", options=["Small", "Normal", "Large"], group=gV)
colorBars = input.bool(false, "Colour candles by filter state", group=gV)
cBull     = input.color(#00e68a, "Bull", inline="c1", group=gV)
cBear     = input.color(#ff1a75, "Bear", inline="c1", group=gV)
cTop      = input.color(#ffb300, "Top", inline="c2", group=gV)
cBot      = input.color(#29b6f6, "Bottom", inline="c2", group=gV)
 
tr = panelLang == "Turkce"
 
// ══════════════ Period-derived settings ══════════════
tfSec   = nz(timeframe.in_seconds(), 3600)
regLook = tfSec <= 300 ? 400 : tfSec <= 900 ? 300 : tfSec <= 3600 ? 250 : tfSec <= 86400 ? 200 : 150
regPct  = tfSec <= 300 ? 62 : tfSec <= 900 ? 58 : tfSec <= 86400 ? 55 : 50
warm    = bar_index > regLook
 
// ══════════════ Range filter ══════════════
rngFilt(float x, float r) =>
    var float f = na
    prev = nz(f, x)
    f := x > prev ? (x - r < prev ? prev : x - r) : (x + r > prev ? prev : x + r)
    f
 
// Self-contained so the higher-timeframe copy runs the exact same logic on its own bars
rfState(float x, int t) =>
    chgAbs = math.abs(x - nz(x[1], x))
    baseC  = ta.ema(ta.ema(chgAbs, t), t * 2 - 1)
    baseA  = ta.atr(t)
    useAtr = rngMode == "ATR"
    base   = useAtr ? baseA : baseC
    mB     = useAtr ? atrMult : rfMult
    [dpI, dmI, adxI] = ta.dmi(diLen, adxLen)
    adxRk = nz(ta.percentrank(adxI, regLook), 50)
    kA    = useADX ? 1.3 - 0.6 * adxRk / 100 : 1.0
    rsiI = ta.rsi(close, rsiLen)
    obI  = nz(ta.percentile_linear_interpolation(rsiI, regLook, obPct), 70)
    osI  = nz(ta.percentile_linear_interpolation(rsiI, regLook, osPct), 30)
    ext  = rsiI >= 50 ? (rsiI - 50) / math.max(obI - 50, 1) : (50 - rsiI) / math.max(50 - osI, 1)
    extC = math.min(math.max(nz(ext), 0), 1)
    kR   = useRSI ? (rsiMode == "Tighten at extremes" ? 1 - 0.3 * extC : 1 + 0.3 * extC) : 1.0
    volAvg = ta.sma(nz(volume), 20)
    relV   = volAvg > 0 ? nz(volume) / volAvg : na
    volRk  = ta.percentrank(relV, regLook)
    kV     = useVol and not na(volRk) ? 1.2 - 0.4 * volRk / 100 : 1.0
    kSm = ta.ema(kA * kR * kV, kSmLen)
    kF  = math.min(math.max(nz(kSm, 1.0), 0.5), 2.0)
    r   = base * mB * kF
    f   = rngFilt(x, r)
    var int fdir = 0
    fdir := f > nz(f[1], f) ? 1 : f < nz(f[1], f) ? -1 : fdir
    var int st = 0
    st := x > f and fdir == 1 ? 1 : x < f and fdir == -1 ? -1 : st
    [f, r, st, kA, kR, kV, kF, mB]
 
[filt, rng, st, kA, kR, kV, kF, mB] = rfState(rfSrc, rfLen)
 
// ══════════════ Higher timeframe ══════════════
htfCall() =>
    [hf, hr, hs, h1, h2, h3, h4, h5] = rfState(rfSrc, rfLen)
    [hf[1], hs[1]]
 
htfAuto = tfSec <= 180 ? "15" : tfSec <= 900 ? "60" : tfSec <= 1800 ? "120" : tfSec <= 3600 ? "240" : tfSec <= 14400 ? "D" : tfSec <= 86400 ? "W" : "M"
htfUse  = mtfMode == "Manual" ? mtfMan : htfAuto
[hFilt, hState] = request.security(syminfo.tickerid, htfUse, htfCall(), lookahead=barmerge.lookahead_off)
hSt = nz(hState)
 
// ══════════════ RSI, regime, ATR ══════════════
atrNow = ta.atr(14)
rsiVal = ta.rsi(close, rsiLen)
[diP, diM, adxVal] = ta.dmi(diLen, adxLen)
 
adxRef  = ta.percentile_linear_interpolation(adxVal, regLook, regPct)
obUse   = ta.percentile_linear_interpolation(rsiVal, regLook, obPct)
osUse   = ta.percentile_linear_interpolation(rsiVal, regLook, osPct)
isTrend = adxVal > adxRef
 
// ══════════════ Dynamic bands: RSI level -> price ══════════════
chg = ta.change(close)
upA = ta.rma(math.max(nz(chg), 0), rsiLen)
dnA = ta.rma(math.max(-nz(chg), 0), rsiLen)
 
// Price the next bar must reach for RSI to equal L
revRsi(float L) =>
    Lc  = math.min(math.max(nz(L, 50), 1), 99)
    rsL = Lc / (100 - Lc)
    k   = rsiLen - 1
    x   = rsL * dnA * k - upA * k
    x >= 0 ? close + x : close - (upA * k / rsL - dnA * k)
 
upB = ta.ema(revRsi(obUse), bandSm)
dnB = ta.ema(revRsi(osUse), bandSm)
 
roomUp = atrNow > 0 ? (upB - close) / atrNow : 0.0
roomDn = atrNow > 0 ? (close - dnB) / atrNow : 0.0
 
okBar = not confBar or barstate.isconfirmed
 
// ══════════════ Filter flips ══════════════
buyRaw  = warm and st == 1 and nz(st[1]) != 1
sellRaw = warm and st == -1 and nz(st[1]) != -1
 
alignBuy  = hSt != -1
alignSell = hSt != 1
roomBuy   = roomUp >= minRoom
roomSell  = roomDn >= minRoom
 
hardBuy  = (regGate == "Hard" and not isTrend) or (htfGate == "Hard" and not alignBuy) or (roomGate == "Hard" and not roomBuy)
hardSell = (regGate == "Hard" and not isTrend) or (htfGate == "Hard" and not alignSell) or (roomGate == "Hard" and not roomSell)
softBuy  = (regGate == "Soft" and not isTrend) or (htfGate == "Soft" and not alignBuy) or (roomGate == "Soft" and not roomBuy)
softSell = (regGate == "Soft" and not isTrend) or (htfGate == "Soft" and not alignSell) or (roomGate == "Soft" and not roomSell)
 
buySig  = flipOn and buyRaw and okBar and not hardBuy
sellSig = flipOn and sellRaw and okBar and not hardSell
 
// ══════════════ Reversal engine ══════════════
// Price pivots with a 1-bar right side - early, and the pivot bar's RSI is kept for divergence
var float pH1 = na
var float pH2 = na
var float rH1 = na
var float rH2 = na
var int   bH1 = na
var int   bH2 = na
var float pL1 = na
var float pL2 = na
var float rL1 = na
var float rL2 = na
var int   bL1 = na
var int   bL2 = na
 
phv = ta.pivothigh(high, revSw, 1)
plv = ta.pivotlow(low, revSw, 1)
if not na(phv)
    pH2 := pH1
    rH2 := rH1
    bH2 := bH1
    pH1 := phv
    rH1 := rsiVal[1]
    bH1 := bar_index - 1
if not na(plv)
    pL2 := pL1
    rL2 := rL1
    bL2 := bL1
    pL1 := plv
    rL1 := rsiVal[1]
    bL1 := bar_index - 1
 
gapH = nz(bH1 - bH2, 0)
gapL = nz(bL1 - bL2, 0)
// Higher price high with a lower RSI high, recent enough to belong to this signal
divBear = not na(pH2) and pH1 > pH2 and rH1 < rH2 and gapH >= 4 and gapH <= 60 and bar_index - nz(bH1, -1000) <= revWin + 1
divBull = not na(pL2) and pL1 < pL2 and rL1 > rL2 and gapL >= 4 and gapL <= 60 and bar_index - nz(bL1, -1000) <= revWin + 1
 
touchUp = warm and high >= upB[1]
touchDn = warm and low <= dnB[1]
bsUp    = nz(ta.barssince(touchUp), 999)
bsDn    = nz(ta.barssince(touchDn), 999)
midPrev = (high[1] + low[1]) / 2
swHi    = ta.highest(high, revWin + 1)
swLo    = ta.lowest(low, revWin + 1)
 
var int lastRT = -1000
var int lastRB = -1000
revTopRaw = revOn and warm and okBar and bsUp < revWin and close < open and close < upB[1] and close < midPrev and bar_index - lastRT > revCool and (not revDiv or divBear)
revBotRaw = revOn and warm and okBar and bsDn < revWin and close > open and close > dnB[1] and close > midPrev and bar_index - lastRB > revCool and (not revDiv or divBull)
if revTopRaw
    lastRT := bar_index
if revBotRaw
    lastRB := bar_index
 
// Stop beyond the swing extreme, limited to 0.3 - 3 ATR
stopTop = math.min(math.max(swHi + 0.2 * atrNow - close, 0.3 * atrNow), 3.0 * atrNow)
stopBot = math.min(math.max(close - (swLo - 0.2 * atrNow), 0.3 * atrNow), 3.0 * atrNow)
 
alignTop = hSt != 1
alignBot = hSt != -1
revTop   = revTopRaw and not (htfGate == "Hard" and not alignTop)
revBot   = revBotRaw and not (htfGate == "Hard" and not alignBot)
dimTop   = htfGate == "Soft" and not alignTop
dimBot   = htfGate == "Soft" and not alignBot
starTop  = revTop and divBear and alignTop
starBot  = revBot and divBull and alignBot
 
// ══════════════ Drawing ══════════════
whyTxt(bool isBuy) =>
    t = ""
    if regGate != "Off" and not isTrend
        t += tr ? "\n· Rejim SIKISMA" : "\n· Regime is RANGE"
    if not (isBuy ? alignBuy : alignSell)
        t += tr ? "\n· Ust zaman dilimiyle TERS" : "\n· Against the higher timeframe"
    if roomGate != "Off" and not (isBuy ? roomBuy : roomSell)
        t += (tr ? "\n· Banda kalan mesafe az: " : "\n· Little room to the band: ") + str.tostring(isBuy ? roomUp : roomDn, "0.0") + " ATR"
    t
 
revTip(bool isTop, bool dv, bool al, float sd) =>
    stopP = isTop ? close + sd : close - sd
    tgtP  = isTop ? close - sd * revTgt : close + sd * revTgt
    (isTop ? (tr ? "TEPE: ust banda temas + ret mumu" : "TOP: upper band touch + rejection candle") : (tr ? "DIP: alt banda temas + ret mumu" : "BOTTOM: lower band touch + rejection candle")) + "\n" + (dv ? (tr ? "◆ RSI uyumsuzlugu VAR" : "◆ RSI divergence: YES") : (tr ? "RSI uyumsuzlugu yok" : "RSI divergence: no")) + "\n" + (al ? (tr ? "Ust TF ile uyumlu" : "Aligned with higher TF") : (tr ? "Ust TF ile TERS" : "Against the higher TF")) + "\n" + (tr ? "Stop: " : "Stop: ") + str.tostring(stopP, format.mintick) + "   " + (tr ? "Hedef: " : "Target: ") + str.tostring(tgtP, format.mintick) + "  (" + str.tostring(revTgt, "0.0") + "R)"
 
if buySig
    dim = softBuy
    label.new(bar_index, low, dim ? "BULL?" : "BULL", yloc=yloc.belowbar, style=label.style_label_up, color=dim ? color.new(cBull, 70) : cBull, textcolor=dim ? color.new(color.white, 40) : color.black, size=size.small, tooltip=(tr ? "Filtre yukari dondu." : "Filter flipped up.") + whyTxt(true))
if sellSig
    dim = softSell
    label.new(bar_index, high, dim ? "BEAR?" : "BEAR", yloc=yloc.abovebar, style=label.style_label_down, color=dim ? color.new(cBear, 70) : cBear, textcolor=dim ? color.new(color.white, 40) : color.white, size=size.small, tooltip=(tr ? "Filtre asagi dondu." : "Filter flipped down.") + whyTxt(false))
if revTop
    txt = "▼" + (divBear ? " ◆" : "") + (starTop ? " ★" : "") + (dimTop ? "?" : "")
    label.new(bar_index, high, txt, yloc=yloc.abovebar, style=label.style_label_down, color=dimTop ? color.new(cTop, 70) : cTop, textcolor=dimTop ? color.new(color.white, 40) : color.black, size=starTop ? size.normal : size.small, tooltip=revTip(true, divBear, alignTop, stopTop))
if revBot
    txt = "▲" + (divBull ? " ◆" : "") + (starBot ? " ★" : "") + (dimBot ? "?" : "")
    label.new(bar_index, low, txt, yloc=yloc.belowbar, style=label.style_label_up, color=dimBot ? color.new(cBot, 70) : cBot, textcolor=dimBot ? color.new(color.white, 40) : color.black, size=starBot ? size.normal : size.small, tooltip=revTip(false, divBull, alignBot, stopBot))
 
// ══════════════ Plots ══════════════
fCol = st == 1 ? cBull : st == -1 ? cBear : color.gray
plot(warm ? filt : na, "Range Filter", color=fCol, linewidth=3)
 
bandOn = showBand and warm
glowW  = atrNow * 0.8
pUp  = plot(bandOn ? upB : na, "Dynamic Upper Band", color=cBear, linewidth=2)
pDn  = plot(bandOn ? dnB : na, "Dynamic Lower Band", color=cBull, linewidth=2)
pUpG = plot(bandOn and showGlow ? upB + glowW : na, "Upper glow edge", color=color.new(cBear, 100), editable=false)
pDnG = plot(bandOn and showGlow ? dnB - glowW : na, "Lower glow edge", color=color.new(cBull, 100), editable=false)
fill(pUp, pUpG, upB + glowW, upB, color.new(cBear, 100), color.new(cBear, 60), "Upper glow")
fill(pDn, pDnG, dnB, dnB - glowW, color.new(cBull, 60), color.new(cBull, 100), "Lower glow")
 
barcolor(colorBars and warm ? fCol : na)
 
// ══════════════ Signal statistics ══════════════
// Flips:     0 all · 1 trend · 2 range · 3 HTF aligned · 4 HTF opposed
// Reversals: 5 all · 6 HTF aligned · 7 HTF opposed · 8 divergence · 9 no divergence · 10 ★ (div + aligned)
// Indexes 11-21: the same groups, counted only for signals after the start date
var sW = array.new_int(22, 0)
var sL = array.new_int(22, 0)
var sT = array.new_int(22, 0)
var sR = array.new_float(22, 0.0)
 
addOne(array<int> aw, array<int> al, array<int> at, array<float> ar, int g, int res, float rv) =>
    if res == 1
        array.set(aw, g, array.get(aw, g) + 1)
    else if res == -1
        array.set(al, g, array.get(al, g) + 1)
    else
        array.set(at, g, array.get(at, g) + 1)
    array.set(ar, g, array.get(ar, g) + rv)
 
addRes(array<int> aw, array<int> al, array<int> at, array<float> ar, int g, int res, float rv, bool lv) =>
    addOne(aw, al, at, ar, g, res, rv)
    if lv
        addOne(aw, al, at, ar, g + 11, res, rv)
 
var trDir   = array.new_int()
var trEntry = array.new_float()
var trSD    = array.new_float()   // stop distance in price
var trTD    = array.new_float()   // target distance in price
var trBar   = array.new_int()
var trKind  = array.new_int()     // 0 = flip, 1 = reversal
var trTrd   = array.new_int()
var trAln   = array.new_int()
var trDv    = array.new_int()
var trLive  = array.new_int()     // 1 = signal after the start date
 
if statsOn and array.size(trDir) > 0
    for i = array.size(trDir) - 1 to 0
        d  = array.get(trDir,   i)
        e  = array.get(trEntry, i)
        sd = array.get(trSD,    i)
        td = array.get(trTD,    i)
        b  = array.get(trBar,   i)
        tg = d == 1 ? e + td : e - td
        sp = d == 1 ? e - sd : e + sd
        hitT = d == 1 ? high >= tg : low <= tg
        hitS = d == 1 ? low <= sp : high >= sp
        res = hitS ? -1 : hitT ? 1 : 0
        if res == 0 and bar_index - b >= maxHold
            res := 2
        if res != 0
            rv = res == 1 ? td / sd : res == -1 ? -1.0 : (close - e) * d / math.max(sd, syminfo.mintick)
            rc = res == 2 ? 0 : res
            aFl = array.get(trAln, i) == 1
            lv  = array.get(trLive, i) == 1
            if array.get(trKind, i) == 1
                dFl = array.get(trDv, i) == 1
                addRes(sW, sL, sT, sR, 5, rc, rv, lv)
                addRes(sW, sL, sT, sR, aFl ? 6 : 7, rc, rv, lv)
                addRes(sW, sL, sT, sR, dFl ? 8 : 9, rc, rv, lv)
                if dFl and aFl
                    addRes(sW, sL, sT, sR, 10, rc, rv, lv)
            else
                tFl = array.get(trTrd, i) == 1
                addRes(sW, sL, sT, sR, 0, rc, rv, lv)
                addRes(sW, sL, sT, sR, tFl ? 1 : 2, rc, rv, lv)
                addRes(sW, sL, sT, sR, aFl ? 3 : 4, rc, rv, lv)
            array.remove(trDir,   i)
            array.remove(trEntry, i)
            array.remove(trSD,    i)
            array.remove(trTD,    i)
            array.remove(trBar,   i)
            array.remove(trKind,  i)
            array.remove(trTrd,   i)
            array.remove(trAln,   i)
            array.remove(trDv,    i)
            array.remove(trLive,  i)
 
// Every RAW signal is recorded, whatever the gates hide. Pushed after evaluation.
pushTrade(int d, float sd, float td, int kind, bool trd, bool aln, bool dv) =>
    array.push(trDir,   d)
    array.push(trEntry, close)
    array.push(trSD,    sd)
    array.push(trTD,    td)
    array.push(trBar,   bar_index)
    array.push(trKind,  kind)
    array.push(trTrd,   trd ? 1 : 0)
    array.push(trAln,   aln ? 1 : 0)
    array.push(trDv,    dv ? 1 : 0)
    array.push(trLive,  time >= statStart ? 1 : 0)
 
if statsOn and okBar and atrNow > 0
    if buyRaw
        pushTrade(1, atrNow * rStop, atrNow * rTgt, 0, isTrend, alignBuy, false)
    if sellRaw
        pushTrade(-1, atrNow * rStop, atrNow * rTgt, 0, isTrend, alignSell, false)
    if revBotRaw
        pushTrade(1, stopBot, stopBot * revTgt, 1, isTrend, alignBot, divBull)
    if revTopRaw
        pushTrade(-1, stopTop, stopTop * revTgt, 1, isTrend, alignTop, divBear)
 
// ══════════════ Last signal ══════════════
var int  lastCode = 0
var int  lastBar  = na
var bool lastDim  = false
var bool lastDv   = false
if buySig
    lastCode := 1
    lastBar  := bar_index
    lastDim  := softBuy
    lastDv   := false
if sellSig
    lastCode := 2
    lastBar  := bar_index
    lastDim  := softSell
    lastDv   := false
if revBot
    lastCode := 3
    lastBar  := bar_index
    lastDim  := dimBot
    lastDv   := divBull
if revTop
    lastCode := 4
    lastBar  := bar_index
    lastDim  := dimTop
    lastDv   := divBear
 
// ══════════════ Info panel ══════════════
tfLabel(string t) =>
    t == "1" ? "1m" : t == "3" ? "3m" : t == "5" ? "5m" : t == "15" ? "15m" : t == "30" ? "30m" : t == "60" ? "1h" : t == "120" ? "2h" : t == "240" ? "4h" : (t == "D" or t == "1D") ? (tr ? "Gunluk" : "Daily") : (t == "W" or t == "1W") ? (tr ? "Haftalik" : "Weekly") : (t == "M" or t == "1M") ? (tr ? "Aylik" : "Monthly") : t
 
gTxt(int g) =>
    w  = array.get(sW, g)
    l  = array.get(sL, g)
    t  = array.get(sT, g)
    n  = w + l
    nn = n + t
    avgR = nn > 0 ? array.get(sR, g) / nn : 0.0
    nn == 0 ? "-" : (n > 0 ? str.tostring(w * 100.0 / n, "0") + "%" : "-") + " " + (avgR >= 0 ? "+" : "") + str.tostring(avgR, "0.00") + "R (" + str.tostring(nn) + ")"
 
gCol(int g) =>
    nn   = array.get(sW, g) + array.get(sL, g) + array.get(sT, g)
    avgR = nn > 0 ? array.get(sR, g) / nn : 0.0
    nn == 0 ? color.gray : avgR >= 0.1 ? cBull : avgR <= -0.1 ? cBear : color.silver
 
pnlPos = pnlPosStr == "Top Right" ? position.top_right : pnlPosStr == "Middle Right" ? position.middle_right : pnlPosStr == "Bottom Right" ? position.bottom_right : pnlPosStr == "Top Left" ? position.top_left : pnlPosStr == "Middle Left" ? position.middle_left : position.bottom_left
pnlSiz = pnlSizStr == "Small" ? size.tiny : pnlSizStr == "Large" ? size.normal : size.small
 
var table pnl = table.new(pnlPos, 2, 23, bgcolor=color.new(#0d1226, 10), border_width=1, border_color=color.new(color.gray, 75))
 
if showPanel and barstate.islast
    table.clear(pnl, 0, 0, 1, 22)
    hd   = color.new(#1a2350, 0)
    cBg  = color.new(#0d1226, 10)
    wht  = color.white
    stC  = st == 1 ? cBull : st == -1 ? cBear : color.gray
    stT  = st == 1 ? (tr ? "YUKARI ▲" : "UP ▲") : st == -1 ? (tr ? "ASAGI ▼" : "DOWN ▼") : "-"
    dist = atrNow > 0 ? (close - filt) / atrNow : 0.0
    regT = (isTrend ? "TREND" : (tr ? "SIKISMA" : "RANGE")) + "  ADX " + str.tostring(adxVal, "0") + "/" + str.tostring(adxRef, "0")
    regC = isTrend ? color.orange : color.new(#42a5f5, 0)
    htfN = tfLabel(htfUse)
    hT   = hSt == 1 ? (tr ? "YUKARI ▲" : "UP ▲") : hSt == -1 ? (tr ? "ASAGI ▼" : "DOWN ▼") : "-"
    alT  = hSt == 0 or st == 0 ? "~" : hSt == st ? (tr ? "✓ uyumlu" : "✓ aligned") : (tr ? "✗ ters" : "✗ opposed")
    hC   = hSt == 1 ? cBull : hSt == -1 ? cBear : color.gray
    age  = na(lastBar) ? -1 : bar_index - lastBar
    sigN = lastCode == 1 ? (lastDim ? "BULL?" : "BULL") : lastCode == 2 ? (lastDim ? "BEAR?" : "BEAR") : lastCode == 3 ? (tr ? "▲ DIP" : "▲ BOTTOM") + (lastDv ? " ◆" : "") + (lastDim ? "?" : "") : lastCode == 4 ? (tr ? "▼ TEPE" : "▼ TOP") + (lastDv ? " ◆" : "") + (lastDim ? "?" : "") : "-"
    sigT = sigN + (age < 0 ? "" : "  ·  " + str.tostring(age) + (tr ? " bar once" : " bars ago"))
    sigC = lastCode == 1 ? cBull : lastCode == 2 ? cBear : lastCode == 3 ? cBot : lastCode == 4 ? cTop : color.gray
    kTot = mB * kF
    rngT = str.tostring(rng, format.mintick) + "   (" + str.tostring(mB, "0.0#") + " × " + str.tostring(kF, "0.00") + " = " + str.tostring(kTot, "0.00") + ")"
    divT = divBear ? (tr ? "AYI ◆ (tepe)" : "BEAR ◆ (top)") : divBull ? (tr ? "BOGA ◆ (dip)" : "BULL ◆ (bottom)") : "-"
    divC = divBear ? cTop : divBull ? cBot : color.gray
 
    off     = statView == "Since start date" ? 11 : 0
    dT      = str.format_time(statStart, "dd.MM.yyyy", syminfo.timezone)
    sfx     = off == 11 ? "  (" + dT + "+)" : ""
    beFlip  = rStop / (rTgt + rStop) * 100
    beRev   = 100 / (1 + revTgt)
    tipStat = tr ? "Donus (BULL/BEAR): hedef " + str.tostring(rTgt, "0.0") + " ATR, stop " + str.tostring(rStop, "0.0") + " ATR, basabas %" + str.tostring(beFlip, "0") + ".\nTepe/Dip: stop salinim ucunun 0.2 ATR otesinde, hedef " + str.tostring(revTgt, "0.0") + "R, basabas %" + str.tostring(beRev, "0") + ".\nYuzde = isabet, R = islem basina ortalama getiri, parantez = ornek.\n\nAsil olcu R: +0.10R ustu anlamli olmaya baslar.\nKabul icin: her grupta 40+ ornek, belirgin R farki, ve ayni fark baska bir sembolde de.\n\nBaslangic tarihi " + dT + ": sonraki sinyaller ayri bir kumede tekrar sayilir - ayarlarin hic gormedigi veri." : "Flips (BULL/BEAR): target " + str.tostring(rTgt, "0.0") + " ATR, stop " + str.tostring(rStop, "0.0") + " ATR, break-even " + str.tostring(beFlip, "0") + "%.\nTop/Bottom: stop 0.2 ATR beyond the swing extreme, target " + str.tostring(revTgt, "0.0") + "R, break-even " + str.tostring(beRev, "0") + "%.\nPercent = hit rate, R = average return per trade, brackets = samples.\n\nR is the real measure: above +0.10R starts to matter.\nTo accept: 40+ samples per group, a clear R gap, and the same gap on another symbol.\n\nStart date " + dT + ": signals after it are counted again in a separate set - data the settings were never tuned on."
 
    if pnlMode == "Mini"
        table.cell(pnl, 0, 0, stT + "  ·  " + htfN + " " + (hSt == 1 ? "▲" : hSt == -1 ? "▼" : "↔") + "  ·  " + (tr ? "Donus " : "Flip ") + gTxt(0 + off) + "  ·  " + (tr ? "Tepe/Dip " : "Rev ") + gTxt(5 + off), text_color=stC, bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
    else
        r = 0
        table.cell(pnl, 0, r, "RRF", text_color=wht, bgcolor=hd, text_size=pnlSiz)
        table.cell(pnl, 1, r, syminfo.ticker + "  ·  " + tfLabel(timeframe.period), text_color=wht, bgcolor=hd, text_size=pnlSiz)
        r += 1
        table.cell(pnl, 0, r, "Trend", text_color=wht, bgcolor=cBg, text_size=pnlSiz)
        table.cell(pnl, 1, r, stT, text_color=stC, bgcolor=cBg, text_size=pnlSiz)
        r += 1
        table.cell(pnl, 0, r, tr ? "Fiyat / Filtre" : "Price vs Filter", text_color=wht, bgcolor=cBg, text_size=pnlSiz)
        table.cell(pnl, 1, r, (close >= filt ? (tr ? "Ustunde " : "Above ") : (tr ? "Altinda " : "Below ")) + str.tostring(math.abs(dist), "0.0") + " ATR", text_color=close >= filt ? cBull : cBear, bgcolor=cBg, text_size=pnlSiz)
        r += 1
        table.cell(pnl, 0, r, "Range", text_color=wht, bgcolor=cBg, text_size=pnlSiz)
        table.cell(pnl, 1, r, rngT, text_color=color.silver, bgcolor=cBg, text_size=pnlSiz)
        r += 1
        table.cell(pnl, 0, r, tr ? "Rejim" : "Regime", text_color=wht, bgcolor=cBg, text_size=pnlSiz)
        table.cell(pnl, 1, r, regT, text_color=regC, bgcolor=cBg, text_size=pnlSiz)
        r += 1
        table.cell(pnl, 0, r, "RSI", text_color=wht, bgcolor=cBg, text_size=pnlSiz)
        table.cell(pnl, 1, r, str.tostring(rsiVal, "0") + "   (" + str.tostring(osUse, "0") + "-" + str.tostring(obUse, "0") + ")", text_color=rsiVal >= obUse ? cBear : rsiVal <= osUse ? cBull : color.silver, bgcolor=cBg, text_size=pnlSiz)
        r += 1
        table.cell(pnl, 0, r, tr ? "Ust bant" : "Upper band", text_color=wht, bgcolor=cBg, text_size=pnlSiz)
        table.cell(pnl, 1, r, str.tostring(upB, format.mintick) + "  ·  " + str.tostring(roomUp, "0.0") + " ATR", text_color=cBear, bgcolor=cBg, text_size=pnlSiz)
        r += 1
        table.cell(pnl, 0, r, tr ? "Alt bant" : "Lower band", text_color=wht, bgcolor=cBg, text_size=pnlSiz)
        table.cell(pnl, 1, r, str.tostring(dnB, format.mintick) + "  ·  " + str.tostring(roomDn, "0.0") + " ATR", text_color=cBull, bgcolor=cBg, text_size=pnlSiz)
        r += 1
        table.cell(pnl, 0, r, tr ? "Uyumsuzluk" : "Divergence", text_color=wht, bgcolor=cBg, text_size=pnlSiz)
        table.cell(pnl, 1, r, divT, text_color=divC, bgcolor=cBg, text_size=pnlSiz)
        r += 1
        table.cell(pnl, 0, r, (tr ? "Ust TF (" : "Higher TF (") + htfN + ")", text_color=wht, bgcolor=cBg, text_size=pnlSiz)
        table.cell(pnl, 1, r, hT + "   " + alT, text_color=hC, bgcolor=cBg, text_size=pnlSiz)
        r += 1
        table.cell(pnl, 0, r, tr ? "Son sinyal" : "Last signal", text_color=wht, bgcolor=cBg, text_size=pnlSiz)
        table.cell(pnl, 1, r, sigT, text_color=sigC, bgcolor=cBg, text_size=pnlSiz)
        if statsOn
            r += 1
            table.cell(pnl, 0, r, (tr ? "Donusler · BE %" : "Flips · BE ") + str.tostring(beFlip, "0") + (tr ? "" : "%") + sfx, text_color=wht, bgcolor=hd, text_size=pnlSiz, tooltip=tipStat)
            table.cell(pnl, 1, r, gTxt(0 + off), text_color=gCol(0 + off), bgcolor=hd, text_size=pnlSiz, tooltip=tipStat)
            r += 1
            table.cell(pnl, 0, r, tr ? "  Ust TF ✓ · ✗" : "  Higher TF ✓ · ✗", text_color=wht, bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
            table.cell(pnl, 1, r, gTxt(3 + off) + "  ·  " + gTxt(4 + off), text_color=color.silver, bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
            r += 1
            table.cell(pnl, 0, r, tr ? "  Trend · Sikisma" : "  Trend · Range", text_color=wht, bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
            table.cell(pnl, 1, r, gTxt(1 + off) + "  ·  " + gTxt(2 + off), text_color=color.silver, bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
            r += 1
            table.cell(pnl, 0, r, (tr ? "Tepe / Dip · BE %" : "Top / Bottom · BE ") + str.tostring(beRev, "0") + (tr ? "" : "%") + sfx, text_color=wht, bgcolor=hd, text_size=pnlSiz, tooltip=tipStat)
            table.cell(pnl, 1, r, gTxt(5 + off), text_color=gCol(5 + off), bgcolor=hd, text_size=pnlSiz, tooltip=tipStat)
            r += 1
            table.cell(pnl, 0, r, tr ? "  Ust TF ✓ · ✗" : "  Higher TF ✓ · ✗", text_color=wht, bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
            table.cell(pnl, 1, r, gTxt(6 + off) + "  ·  " + gTxt(7 + off), text_color=color.silver, bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
            r += 1
            table.cell(pnl, 0, r, tr ? "  Uyumsuzluk ◆ · yok" : "  Divergence ◆ · none", text_color=wht, bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
            table.cell(pnl, 1, r, gTxt(8 + off) + "  ·  " + gTxt(9 + off), text_color=color.silver, bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
            r += 1
            table.cell(pnl, 0, r, tr ? "  ★ ◆ + Ust TF" : "  ★ ◆ + Higher TF", text_color=wht, bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
            table.cell(pnl, 1, r, gTxt(10 + off), text_color=gCol(10 + off), bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
            if statView == "Both"
                r += 1
                table.cell(pnl, 0, r, (tr ? "Baslangictan beri · " : "Since · ") + dT, text_color=wht, bgcolor=hd, text_size=pnlSiz, tooltip=tipStat)
                table.cell(pnl, 1, r, tr ? "yeni veri - durust test" : "out of sample - the honest test", text_color=color.silver, bgcolor=hd, text_size=pnlSiz, tooltip=tipStat)
                r += 1
                table.cell(pnl, 0, r, tr ? "  Donusler · Ust TF ✓" : "  Flips · Higher TF ✓", text_color=wht, bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
                table.cell(pnl, 1, r, gTxt(14), text_color=gCol(14), bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
                r += 1
                table.cell(pnl, 0, r, tr ? "  Tepe / Dip" : "  Top / Bottom", text_color=wht, bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
                table.cell(pnl, 1, r, gTxt(16), text_color=gCol(16), bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
                r += 1
                table.cell(pnl, 0, r, tr ? "  ★ ◆ + Ust TF" : "  ★ ◆ + Higher TF", text_color=wht, bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
                table.cell(pnl, 1, r, gTxt(21), text_color=gCol(21), bgcolor=cBg, text_size=pnlSiz, tooltip=tipStat)
 
// ══════════════ Alerts ══════════════
// Set alerts to "Once Per Bar Close" to match bar-close confirmation.
alertcondition(buySig,  "BULL flip", "Range filter flipped UP | Filtre yukari dondu - {{ticker}} {{interval}}")
alertcondition(sellSig, "BEAR flip", "Range filter flipped DOWN | Filtre asagi dondu - {{ticker}} {{interval}}")
alertcondition(revBot,  "Bottom",    "Reversal at lower band | Alt bantta DIP donusu - {{ticker}} {{interval}}")
alertcondition(revTop,  "Top",       "Reversal at upper band | Ust bantta TEPE donusu - {{ticker}} {{interval}}")
alertcondition(starBot, "★ Bottom",  "Bottom + RSI divergence + higher TF aligned | Guclu DIP - {{ticker}} {{interval}}")
alertcondition(starTop, "★ Top",     "Top + RSI divergence + higher TF aligned | Guclu TEPE - {{ticker}} {{interval}}")

← 返回列表