Squeeze Navigator

onderarslantas107 · study · 1085 行 · 点赞 436 · TradingView 原页

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

Pine Script

//@version=6
indicator("GEZEN | MTF PRO 1.0", shorttitle="GEZEN PRO", overlay=true, dynamic_requests=true, max_labels_count=200)
 
// Indicator with virtual LONG-only accounting. No broker orders.
// Three source entry families retained.
// Confirmed MTF and common protection change results versus the source.
 
//━━━━━━━━━━━━━━━━ GENERAL
string g0 = "01 | Genel / General"
 
lang = input.string("TR", "Dil / Language", options=["TR", "EN"], group=g0)
 
startDate = input.time(
     timestamp("01 Jan 2020 00:00 +0000"),
     "Baslangic / Start",
     group=g0)
 
fee = input.float(
     0.05, "Tek yon komisyon % / Fee per side %",
     minval=0, maxval=5, step=0.01, group=g0)
 
slip = input.int(
     0, "Tek yon kayma tick / Slippage per side",
     minval=0, group=g0)
 
allocation = input.float(
     10, "Sanal sermaye kullanimi % / Virtual allocation %",
     minval=1, maxval=100, group=g0)
 
//━━━━━━━━━━━━━━━━ FRACTAL
string g1 = "02 | Fraktal / Fractal"
 
frLeft = input.int(2, "Sol mum / Left bars", minval=2, maxval=20, group=g1)
frRight = input.int(2, "Sag onay / Right confirmation", minval=1, maxval=15, group=g1)
minAnchorBars = input.int(2, "Capa araligi / Anchor gap", minval=2, maxval=50, group=g1)
minMoveAtr = input.float(0.07, "Capa farki ATR / Anchor move ATR", minval=0.01, step=0.01, group=g1)
maxAgeBars = input.int(180, "Capa omru TF mumu / Anchor age TF bars", minval=10, maxval=1000, group=g1)
atrLen = input.int(14, "ATR", minval=5, maxval=100, group=g1)
 
//━━━━━━━━━━━━━━━━ MTF
string g2 = "03 | MTF"
 
tf1 = input.timeframe("3", "TF1 / FAST", group=g2)
tf2 = input.timeframe("5", "TF2 / FAST", group=g2)
tf3 = input.timeframe("15", "TF3 / FAST", group=g2)
tf4 = input.timeframe("30", "TF4 / STRUCT", group=g2)
tf5 = input.timeframe("60", "TF5 / STRUCT", group=g2)
tf6 = input.timeframe("120", "TF6 / STRUCT", group=g2)
 
needLines = input.int(4, "Kume cizgi sayisi / Cluster lines", minval=3, maxval=6, group=g2)
clusterAtr = input.float(0.30, "Kume acikligi ATR / Cluster width ATR", minval=0.05, step=0.05, group=g2)
insideNeed = input.int(4, "BB ici cizgi / Lines inside BB", minval=3, maxval=6, group=g2)
insideTol = input.float(0.15, "BB esneklik ATR / BB tolerance ATR", minval=0, step=0.05, group=g2)
 
//━━━━━━━━━━━━━━━━ ENTRY
string g3 = "04 | Giris / Entry"
 
useMomentum = input.bool(true, "Momentum AL / Momentum entry", group=g3)
useFlat = input.bool(true, "Duz sikisma AL / Flat squeeze entry", group=g3)
useBreak = input.bool(true, "Bolge kirilim AL / Region breakout entry", group=g3)
 
bbLen = input.int(20, "BB periyot / BB length", minval=5, group=g3)
bbMult = input.float(2, "BB katsayi / BB multiplier", minval=0.5, step=0.1, group=g3)
bbAvgLen = input.int(30, "BB genislik ortalamasi / BB width average", minval=10, group=g3)
squeezeRatio = input.float(0.95, "BB daralma orani / BB squeeze ratio", minval=0.1, step=0.05, group=g3)
maxBbAtr = input.float(3, "BB maksimum genislik ATR / BB max width ATR", minval=0.5, step=0.1, group=g3)
 
memoryBars = input.int(10, "Sikisma hafizasi / Squeeze memory", minval=2, maxval=240, group=g3)
entrySyncMax = input.int(120, "Giris senkron tavani / Entry sync cap", minval=6, maxval=240, group=g3)
 
lookback = input.int(2, "Momentum bakisi / Momentum lookback", minval=1, maxval=20, group=g3)
aggressiveAtr = input.float(0.10, "Guclu hareket ATR / Strong move ATR", minval=0.01, step=0.01, group=g3)
supportAtr = input.float(0.03, "Destek hareket ATR / Supporting move ATR", minval=0.01, step=0.01, group=g3)
strongNeed = input.int(4, "Guclu cizgi sayisi / Strong line count", minval=2, maxval=6, group=g3)
buildNeed = input.int(3, "Building guclu cizgi / Building strong lines", minval=2, maxval=5, group=g3)
protectSyncMax = input.int(18, "Cikis momentum hafizasi / Exit momentum cap", minval=6, maxval=240, group=g3)
 
flatLook = input.int(3, "Duzluk bakisi / Flat lookback", minval=2, maxval=20, group=g3)
flatTol = input.float(0.14, "Duzluk toleransi ATR / Flat tolerance ATR", minval=0.02, step=0.02, group=g3)
flatNeed = input.int(4, "Duz cizgi sayisi / Flat line count", minval=3, maxval=6, group=g3)
 
maxChase = input.float(0.4, "BB ustu AL payi ATR / Entry chase ATR", minval=0, step=0.05, group=g3)
cooldown = input.int(1, "SAT sonrasi tam mum / Full bars after exit", minval=0, maxval=50, group=g3)
 
//━━━━━━━━━━━━━━━━ BALANCE
string g4 = "05 | BAL / Balance"
 
sqzPowerUsePvm = input.bool(true, "PVM katkisi / PVM contribution", group=g4)
sqzPowerPvmWeight = input.float(0.25, "PVM agirligi / PVM weight", minval=0, maxval=0.6, step=0.05, group=g4)
 
w1 = input.float(1.00, "TF1 agirlik / Weight", minval=0.1, group=g4)
w2 = input.float(1.10, "TF2 agirlik / Weight", minval=0.1, group=g4)
w3 = input.float(1.35, "TF3 agirlik / Weight", minval=0.1, group=g4)
w4 = input.float(1.60, "TF4 agirlik / Weight", minval=0.1, group=g4)
w5 = input.float(1.90, "TF5 agirlik / Weight", minval=0.1, group=g4)
w6 = input.float(2.20, "TF6 agirlik / Weight", minval=0.1, group=g4)
 
releaseBars = input.int(10, "Cozulme takibi / Release window", minval=1, maxval=60, group=g4)
balanceTrigger = input.float(-5, "Negatif BAL esigi / Negative BAL threshold", minval=-50, maxval=-0.5, step=0.5, group=g4)
breakWait = input.int(60, "Kirilim bekleme / Breakout wait", minval=5, maxval=300, group=g4)
breakBuffer = input.float(0, "Kirilim payi ATR / Breakout buffer ATR", minval=0, step=0.05, group=g4)
 
//━━━━━━━━━━━━━━━━ PROTECTION
string g5 = "06 | Koruma / Protection"
 
stopAtr = input.float(2.2, "Tum girislerde stop ATR / Common stop ATR", minval=0.5, step=0.1, group=g5)
 
useTrail = input.bool(true, "Kar takip stopu / Profit trailing stop", group=g5)
trailStart = input.float(2, "Takip baslangici ATR / Trail activation ATR", minval=0.5, step=0.1, group=g5)
trailAtr = input.float(3, "Takip mesafesi ATR / Trail distance ATR", minval=0.5, step=0.1, group=g5)
breakEven = input.bool(true, "Takipte giris korumasi / Break-even after activation", group=g5)
 
flatGuard = input.bool(true, "Duz giriste mum dibi / Flat entry candle guard", group=g5)
flatRelease = input.float(2, "Duz koruma bitis ATR / Flat guard release ATR", minval=0.5, step=0.25, group=g5)
 
protectBars = input.int(6, "Dogal cikis bekleme / Native exit delay", minval=1, maxval=100, group=g5)
useFade = input.bool(true, "Momentum sonme cikisi / Momentum fade exit", group=g5)
fadeGain = input.float(0.6, "Sonme cikisi min kar ATR / Fade min gain ATR", minval=0.1, step=0.1, group=g5)
 
useFail = input.bool(true, "Basarisiz kirilim cikisi / Failed breakout exit", group=g5)
failBars = input.int(12, "Basarisizlik min mum / Failure min bars", minval=3, maxval=100, group=g5)
 
//━━━━━━━━━━━━━━━━ APPEARANCE
string g6 = "07 | Gorunum / Appearance"
 
showSignals = input.bool(true, "AL SAT etiketleri / Buy sell labels", group=g6)
showRibbon = input.bool(true, "MTF cizgileri / MTF lines", group=g6)
showBands = input.bool(false, "Bollinger", group=g6)
showLevels = input.bool(true, "Giris ve stop / Entry and stop", group=g6)
showBreak = input.bool(true, "Bekleyen kirilim / Pending breakout", group=g6)
showBars = input.bool(true, "Mum renkleri / Candle colors", group=g6)
showPanel = input.bool(true, "Basari paneli / Performance panel", group=g6)
showAura = input.bool(true, "Takip zemini / Position tint", group=g6)
 
panelSide = input.string("RIGHT", "Panel konumu / Panel side", options=["RIGHT", "LEFT"], group=g6)
labelLimit = input.int(60, "Etiket gecmisi / Label history", minval=10, maxval=180, group=g6)
alertsOn = input.bool(true, "Ayrintili alarmlar / Detailed alerts", group=g6)
 
color buyC = #00E676
color sellC = #FF1744
color neutralC = #8F9AAA
color bgC = #121A27
color rowC = #1B2638
 
//━━━━━━━━━━━━━━━━ LANGUAGE AND HELPERS
t(string tr, string en) =>
    lang == "TR" ? tr : en
 
f_num(float x) =>
    na(x) ? "-" : str.tostring(x, "#.1")
 
f_price(float x) =>
    na(x) ? "-" : str.tostring(x, format.mintick)
 
f_pct(float x) =>
    na(x) ? "-" : str.tostring(x, "#.2") + "%"
 
f_color(float x) =>
    na(x) or x == 0 ? neutralC : x > 0 ? buyC : sellC
 
f_entryText(int id) =>
    id == 1 ? t("MOMENTUM", "MOMENTUM") : id == 2 ? t("DUZ SIKISMA", "FLAT SQUEEZE") : id == 3 ? t("BOLGE KIRILIMI", "REGION BREAK") : "-"
 
f_exitText(int id) =>
    id == 1 ? t("ORTAK STOP", "COMMON STOP") : id == 2 ? t("TAKIP STOP", "TRAILING STOP") : id == 3 ? t("MUM DIBI", "CANDLE GUARD") : id == 4 ? t("MOMENTUM SONDU", "MOMENTUM FADE") : id == 5 ? t("BASARISIZ KIRILIM", "FAILED BREAK") : "-"
 
float chartSec = timeframe.in_seconds()
float sec1 = timeframe.in_seconds(tf1)
float sec2 = timeframe.in_seconds(tf2)
float sec3 = timeframe.in_seconds(tf3)
float sec4 = timeframe.in_seconds(tf4)
float sec5 = timeframe.in_seconds(tf5)
float sec6 = timeframe.in_seconds(tf6)
 
if barstate.isfirst
    if not chart.is_standard or timeframe.isticks
        runtime.error(t("Standart zaman tabanli mum grafigi kullanin.", "Use a standard time-based candle chart."))
 
    if not (sec1 < sec2 and sec2 < sec3 and sec3 < sec4 and sec4 < sec5 and sec5 < sec6)
        runtime.error(t("TF1..TF6 farkli ve kucukten buyuge olmali.", "TF1..TF6 must be distinct and ascending."))
 
    if supportAtr > aggressiveAtr or buildNeed > strongNeed
        runtime.error(t("Destek esigi guclu esigi asamaz; building sayisi guclu sayisini asamaz.", "Support threshold and building count must not exceed their strong equivalents."))
 
//━━━━━━━━━━━━━━━━ SOURCE ENGINES
f_lineAtTime(float olderPrice, int olderTime, float newerPrice, int newerTime, int targetTime) =>
    float out = na
    if not na(olderPrice) and not na(newerPrice) and not na(olderTime) and not na(newerTime) and newerTime > olderTime
        float span = float(newerTime - olderTime)
        float slopePart = float(targetTime - newerTime) / span
        out := newerPrice + (newerPrice - olderPrice) * slopePart
    out
 
gx_sqzZ(float src, int len) =>
    float mean = ta.sma(src, len)
    float dev = ta.stdev(src, len)
    dev != 0 ? (src - mean) / dev : 0.0
 
gx_sqzClamp(float x, float lo, float hi) =>
    math.max(math.min(x, hi), lo)
 
gx_sqzNormalize(float src, int len) =>
    float lo = ta.lowest(src, len)
    float hi = ta.highest(src, len)
    hi != lo ? 100.0 * (src - lo) / (hi - lo) : 50.0
 
gx_sqzAtsScore() =>
    float emaTrend = ta.ema(close, 55)
    float trendRaw = emaTrend - emaTrend[1]
    float momRaw = ta.roc(close, 10)
 
    float obvLocal = ta.cum(close > close[1] ? nz(volume, 0) : close < close[1] ? -nz(volume, 0) : 0)
    float obvRaw = obvLocal - obvLocal[1]
 
    float atrLocal = ta.atr(14)
    float priceDir = close > ta.ema(close, 20) ? 1.0 : -1.0
    float atrRaw = (atrLocal - atrLocal[1]) * priceDir
 
    float trendZ = gx_sqzZ(trendRaw, 34)
    float momZ = gx_sqzZ(momRaw, 34)
    float obvZ = gx_sqzZ(obvRaw, 34)
    float atrZ = gx_sqzZ(atrRaw, 34)
 
    float organRaw = trendZ * 2.0 + momZ * 1.5 + obvZ * 1.0 + atrZ * 0.5
    float organ = ta.ema(organRaw, 8)
    float organPct = gx_sqzClamp(organ / 6.0 * 50.0 + 50.0, 0.0, 100.0)
 
    float src = hl2
    float upper = src * 1.02
    float lower = src * 0.98
    float mid = (upper + lower) / 2.0
    float dist = (upper - lower) / 2.0
 
    float resist = ta.ema(mid + dist * 1.3, 5)
    float support = ta.ema(mid - dist * 1.3, 5)
 
    float matcMid = (resist + support) / 2.0
    float matcRange = math.max(resist - support, syminfo.mintick)
    float matcPctNow = gx_sqzClamp((close - matcMid) / matcRange * 50.0 + 50.0, 0.0, 100.0)
 
    float emaFast = ta.ema(close, 21)
    float emaSlow = ta.ema(close, 55)
    float ribbonPct = emaFast > emaSlow ? 65.0 : emaFast < emaSlow ? 35.0 : 50.0
    float rsiPct = gx_sqzClamp(ta.rsi(close, 14), 0.0, 100.0)
 
    organPct * 0.40 + matcPctNow * 0.25 + ribbonPct * 0.20 + rsiPct * 0.15
 
gx_sqzAtsPvm() =>
    float priceChange = ta.change(close)
    float volumeChange = ta.change(volume)
    float corrRaw = nz(ta.correlation(priceChange, volumeChange, 55), 0)
    float trendEngine = ta.ema((corrRaw + 1.0) * 50.0, 9)
 
    float relVolBase = ta.ema(volume, 34)
    float relVol = volume / math.max(relVolBase, 1.0)
 
    float atrNow = ta.atr(14)
    float atrBase = ta.ema(atrNow, 34)
    float atrExpansion = atrNow / math.max(atrBase, syminfo.mintick)
 
    float impulseRaw = atrExpansion * relVol
    float impulseEngine = ta.ema(gx_sqzNormalize(impulseRaw, 100), 9)
 
    float priceRoc = ta.roc(close, 14)
    float directionEngine = ta.ema(gx_sqzNormalize(priceRoc, 100), 9)
 
    trendEngine * 0.40 + impulseEngine * 0.35 + directionEngine * 0.25
 
gx_sqzTfPower() =>
    float score = gx_sqzAtsScore()
    float pvm = gx_sqzAtsPvm()
    bool volumeOK = not na(volume) and volume > 0 and not na(pvm)
 
    float out = sqzPowerUsePvm and volumeOK ? score * (1.0 - sqzPowerPvmWeight) + pvm * sqzPowerPvmWeight : score
 
    bar_index >= 100 and not na(score) ? gx_sqzClamp(out, 0.0, 100.0) : na
 
f_tfTrendLine() =>
    float a = ta.atr(atrLen)
 
    float highPivot = ta.pivothigh(high, frLeft, frRight)
    bool highEvent = not na(highPivot)
 
    float h0 = ta.valuewhen(highEvent, highPivot, 0)
    int ht0 = ta.valuewhen(highEvent, time[frRight], 0)
    int hb0 = ta.valuewhen(highEvent, bar_index[frRight], 0)
 
    float h1 = ta.valuewhen(highEvent, highPivot, 1)
    int ht1 = ta.valuewhen(highEvent, time[frRight], 1)
    int hb1 = ta.valuewhen(highEvent, bar_index[frRight], 1)
 
    float h2 = ta.valuewhen(highEvent, highPivot, 2)
    int ht2 = ta.valuewhen(highEvent, time[frRight], 2)
    int hb2 = ta.valuewhen(highEvent, bar_index[frRight], 2)
 
    float h3 = ta.valuewhen(highEvent, highPivot, 3)
    int ht3 = ta.valuewhen(highEvent, time[frRight], 3)
    int hb3 = ta.valuewhen(highEvent, bar_index[frRight], 3)
 
    float highAtr = ta.valuewhen(highEvent, a[frRight], 0)
 
    float lowPivot = ta.pivotlow(low, frLeft, frRight)
    bool lowEvent = not na(lowPivot)
 
    float l0 = ta.valuewhen(lowEvent, lowPivot, 0)
    int lt0 = ta.valuewhen(lowEvent, time[frRight], 0)
    int lb0 = ta.valuewhen(lowEvent, bar_index[frRight], 0)
 
    float l1 = ta.valuewhen(lowEvent, lowPivot, 1)
    int lt1 = ta.valuewhen(lowEvent, time[frRight], 1)
    int lb1 = ta.valuewhen(lowEvent, bar_index[frRight], 1)
 
    float l2 = ta.valuewhen(lowEvent, lowPivot, 2)
    int lt2 = ta.valuewhen(lowEvent, time[frRight], 2)
    int lb2 = ta.valuewhen(lowEvent, bar_index[frRight], 2)
 
    float l3 = ta.valuewhen(lowEvent, lowPivot, 3)
    int lt3 = ta.valuewhen(lowEvent, time[frRight], 3)
    int lb3 = ta.valuewhen(lowEvent, bar_index[frRight], 3)
 
    float lowAtr = ta.valuewhen(lowEvent, a[frRight], 0)
 
    bool down1 = not na(h0) and not na(h1) and hb0 - hb1 >= minAnchorBars and h1 > h0 and not na(highAtr) and h1 - h0 >= highAtr * minMoveAtr
    bool down2 = not down1 and not na(h0) and not na(h2) and hb0 - hb2 >= minAnchorBars and h2 > h0 and not na(highAtr) and h2 - h0 >= highAtr * minMoveAtr
    bool down3 = not down1 and not down2 and not na(h0) and not na(h3) and hb0 - hb3 >= minAnchorBars and h3 > h0 and not na(highAtr) and h3 - h0 >= highAtr * minMoveAtr
 
    float downOlderPrice = na
    int downOlderTime = na
    int downOlderBar = na
 
    if down1
        downOlderPrice := h1
        downOlderTime := ht1
        downOlderBar := hb1
    else if down2
        downOlderPrice := h2
        downOlderTime := ht2
        downOlderBar := hb2
    else if down3
        downOlderPrice := h3
        downOlderTime := ht3
        downOlderBar := hb3
 
    bool downPairFound = down1 or down2 or down3
    bool downFresh = downPairFound and not na(hb0) and bar_index - hb0 <= maxAgeBars
 
    float downLine = downFresh ? f_lineAtTime(downOlderPrice, downOlderTime, h0, ht0, time) : na
    float downSlopeAtr = downFresh and not na(downOlderBar) and hb0 > downOlderBar and not na(highAtr) and highAtr > 0 ? (h0 - downOlderPrice) / highAtr / float(hb0 - downOlderBar) : na
 
    bool up1 = not na(l0) and not na(l1) and lb0 - lb1 >= minAnchorBars and l1 < l0 and not na(lowAtr) and l0 - l1 >= lowAtr * minMoveAtr
    bool up2 = not up1 and not na(l0) and not na(l2) and lb0 - lb2 >= minAnchorBars and l2 < l0 and not na(lowAtr) and l0 - l2 >= lowAtr * minMoveAtr
    bool up3 = not up1 and not up2 and not na(l0) and not na(l3) and lb0 - lb3 >= minAnchorBars and l3 < l0 and not na(lowAtr) and l0 - l3 >= lowAtr * minMoveAtr
 
    float upOlderPrice = na
    int upOlderTime = na
    int upOlderBar = na
 
    if up1
        upOlderPrice := l1
        upOlderTime := lt1
        upOlderBar := lb1
    else if up2
        upOlderPrice := l2
        upOlderTime := lt2
        upOlderBar := lb2
    else if up3
        upOlderPrice := l3
        upOlderTime := lt3
        upOlderBar := lb3
 
    bool upPairFound = up1 or up2 or up3
    bool upFresh = upPairFound and not na(lb0) and bar_index - lb0 <= maxAgeBars
 
    float upLine = upFresh ? f_lineAtTime(upOlderPrice, upOlderTime, l0, lt0, time) : na
    float upSlopeAtr = upFresh and not na(upOlderBar) and lb0 > upOlderBar and not na(lowAtr) and lowAtr > 0 ? (l0 - upOlderPrice) / lowAtr / float(lb0 - upOlderBar) : na
 
    float activeLine = na
    int activeDir = 0
    float activeSlopeAtr = na
 
    if downFresh and upFresh
        if ht0 >= lt0
            activeLine := downLine
            activeDir := -1
            activeSlopeAtr := downSlopeAtr
        else
            activeLine := upLine
            activeDir := 1
            activeSlopeAtr := upSlopeAtr
    else if downFresh
        activeLine := downLine
        activeDir := -1
        activeSlopeAtr := downSlopeAtr
    else if upFresh
        activeLine := upLine
        activeDir := 1
        activeSlopeAtr := upSlopeAtr
 
    [activeLine, activeDir, downLine, upLine, activeSlopeAtr]
 
//━━━━━━━━━━━━━━━━ CONFIRMED MTF
f_current() =>
    [level, direction, downLine, upLine, slope] = f_tfTrendLine()
    float strength = gx_sqzTfPower()
    [level, direction, strength, time_close]
 
f_previous() =>
    [level, direction, strength, endTime] = f_current()
    [level[1], direction[1], strength[1], endTime[1]]
 
f_read(simple string tf, float localLine, int localDir, float localPower) =>
    float seconds = timeframe.in_seconds(tf)
 
    if seconds == timeframe.in_seconds()
        [localLine, localDir, localPower]
 
    else if seconds > timeframe.in_seconds()
        [level, direction, strength, endTime] = request.security(syminfo.tickerid, tf, f_previous(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
        [level, direction, strength]
 
    else
        [levels, directions, strengths, ends] = request.security_lower_tf(syminfo.tickerid, tf, f_current())
 
        int k = array.size(levels) - 1
 
        while k >= 0
            if array.get(ends, k) <= time_close
                break
            k -= 1
 
        [k >= 0 ? array.get(levels, k) : na, k >= 0 ? array.get(directions, k) : 0, k >= 0 ? array.get(strengths, k) : na]
 
[localLine, localDir, localPower, localEnd] = f_current()
 
[l1, d1, p1] = f_read(tf1, localLine, localDir, localPower)
[l2, d2, p2] = f_read(tf2, localLine, localDir, localPower)
[l3, d3, p3] = f_read(tf3, localLine, localDir, localPower)
[l4, d4, p4] = f_read(tf4, localLine, localDir, localPower)
[l5, d5, p5] = f_read(tf5, localLine, localDir, localPower)
[l6, d6, p6] = f_read(tf6, localLine, localDir, localPower)
 
array<float> levels = array.from(l1, l2, l3, l4, l5, l6)
array<float> powers = array.from(p1, p2, p3, p4, p5, p6)
array<float> weights = array.from(w1, w2, w3, w4, w5, w6)
array<int> directions = array.from(d1, d2, d3, d4, d5, d6)
 
array<float> rises = array.from(l1-l1[lookback], l2-l2[lookback], l3-l3[lookback], l4-l4[lookback], l5-l5[lookback], l6-l6[lookback])
 
array<float> flats = array.from(math.abs(l1-l1[flatLook]), math.abs(l2-l2[flatLook]), math.abs(l3-l3[flatLook]), math.abs(l4-l4[flatLook]), math.abs(l5-l5[flatLook]), math.abs(l6-l6[flatLook]))
 
//━━━━━━━━━━━━━━━━ CLUSTER
f_cluster(array<float> values, int need, float atrValue) =>
    array<float> valid = array.new<float>()
    array<int> ids = array.new<int>()
 
    for i = 0 to 5
        if not na(array.get(values, i))
            array.push(valid, array.get(values, i))
            array.push(ids, i)
 
    array<int> chosen = array.new<int>()
    float spread = na
    int n = array.size(valid)
 
    if n >= need and not na(atrValue) and atrValue > 0
        array<int> ordered = array.sort_indices(valid, order.ascending)
        int best = 0
        float width = na
 
        for i = 0 to n - need
            float gap = array.get(valid, array.get(ordered, i + need - 1)) - array.get(valid, array.get(ordered, i))
 
            if na(width) or gap < width
                width := gap
                best := i
 
        for i = 0 to need - 1
            array.push(chosen, array.get(ids, array.get(ordered, best + i)))
 
        spread := width / atrValue
 
    [chosen, spread, n]
 
f_groups(array<int> members, array<float> strengths, array<float> wgts) =>
    float fs = 0.0
    float fw = 0.0
    float ss = 0.0
    float sw = 0.0
 
    bool complete = array.size(members) > 0
 
    for id in members
        float p = array.get(strengths, id)
        float w = array.get(wgts, id)
 
        complete := complete and not na(p)
 
        if id < 3
            fs += nz(p) * w
            fw += w
        else
            ss += nz(p) * w
            sw += w
 
    [complete and fw > 0 ? fs/fw : na, complete and sw > 0 ? ss/sw : na, fw, sw, complete]
 
f_recent(int lastBar, int span) =>
    not na(lastBar) and bar_index - lastBar <= span
 
//━━━━━━━━━━━━━━━━ CHART SERIES
float atr = ta.atr(atrLen)
float basis = ta.sma(close, bbLen)
float deviation = ta.stdev(close, bbLen) * bbMult
float upper = basis + deviation
float lower = basis - deviation
 
float widthPct = not na(basis) and basis != 0 ? (upper-lower)/math.abs(basis)*100 : na
float averageWidth = ta.sma(widthPct, bbAvgLen)
float widthRatio = averageWidth > 0 ? widthPct/averageWidth : na
 
[clusterIds, clusterWidth, validLines] = f_cluster(levels, needLines, atr)
 
int insideCount = 0
for i = 0 to 5
    float level = array.get(levels, i)
    if not na(level) and level >= lower-atr*insideTol and level <= upper+atr*insideTol
        insideCount += 1
 
bool bbTight = not na(widthRatio) and widthRatio <= squeezeRatio and atr > 0 and (upper-lower)/atr <= maxBbAtr
 
bool squeeze = bbTight and ((not na(clusterWidth) and clusterWidth <= clusterAtr) or insideCount >= insideNeed)
 
bool dataReady = not na(atr) and atr > 0 and not na(widthRatio) and validLines >= needLines and close > syminfo.mintick
 
int naturalSpan = int(math.ceil(sec6/chartSec))
int entrySpan = math.max(4, math.min(entrySyncMax, naturalSpan))
int protectSpan = math.max(4, math.min(protectSyncMax, naturalSpan))
int compressionMemory = math.max(memoryBars, entrySpan)
 
float riseAtr = not na(atr[lookback]) ? math.min(atr, atr[lookback]) : atr
 
//━━━━━━━━━━━━━━━━ STATE
var array<int> lastStrong = array.new<int>(6, na)
var array<int> lastSupport = array.new<int>(6, na)
var array<int> frozen = array.new<int>()
 
var array<float> publishedLines = array.new<float>(6, na)
var array<int> publishedDirs = array.new<int>(6, 0)
 
var int lastProtect = na
var int lastSqueeze = na
var bool wasSqueeze = false
var bool flatConsumed = false
var int flatReleaseCount = 0
 
var int releaseBar = na
var float startFast = na
var float releaseDelta = na
var float releaseHigh = na
 
var bool regionUsed = false
var bool breakPending = false
var int breakBar = na
var float breakLevel = na
var float breakAtr = na
var float balance = na
 
var bool holding = false
var int entryType = 0
var int entryBar = na
var int lastExit = na
 
var float entryClose = na
var float entryFill = na
var float entryVol = na
var float quantity = na
 
var float stop = na
var float highestClose = na
var bool trailing = false
 
var bool flatActive = false
var float flatFloor = na
 
var int lastEventType = 0
var int lastEventCode = 0
var float lastNetReturn = na
var int sampleStart = na
 
//━━━━━━━━━━━━━━━━ VIRTUAL ACCOUNTING
var float equity = 10000.0
var float peakEquity = 10000.0
var float maxDrawdown = 0.0
 
var int closed = 0
var int wins = 0
var int losses = 0
var int even = 0
 
var float grossProfit = 0.0
var float grossLoss = 0.0
var float returnSum = 0.0
 
var array<int> typeClosed = array.new<int>(3, 0)
var array<int> typeWins = array.new<int>(3, 0)
 
//━━━━━━━━━━━━━━━━ PUBLISHED VALUES
var bool publishedReady = false
var bool publishedSqueeze = false
 
var int publishedStrongCount = 0
var int publishedFlatCount = 0
 
var float publishedBalance = na
var float publishedClose = na
var float publishedBasis = na
var float publishedUpper = na
var float publishedLower = na
var float publishedStop = na
var float publishedBreak = na
var float publishedOpenReturn = na
 
var int publishedTime = na
var array<label> marks = array.new<label>()
 
bool buySignal = false
bool sellSignal = false
bool stopSignal = false
int exitReason = 0
 
//━━━━━━━━━━━━━━━━ MAIN ENGINE
if barstate.isconfirmed
    publishedReady := dataReady
    publishedClose := close
    publishedBasis := basis
    publishedUpper := upper
    publishedLower := lower
    publishedTime := time_close
 
    if time >= startDate and na(sampleStart)
        sampleStart := time
 
    int entryStrong = 0
    int entrySupport = 0
    int protectStrong = 0
    int protectSupport = 0
    int flatCount = 0
 
    for i = 0 to 5
        array.set(publishedLines, i, array.get(levels, i))
        array.set(publishedDirs, i, array.get(directions, i))
 
        float rise = array.get(rises, i)
 
        if not na(rise) and riseAtr > 0
            if rise >= riseAtr * aggressiveAtr
                array.set(lastStrong, i, bar_index)
 
            if rise >= riseAtr * supportAtr
                array.set(lastSupport, i, bar_index)
 
        int a = array.get(lastStrong, i)
        int b = array.get(lastSupport, i)
 
        entryStrong += f_recent(a, entrySpan) ? 1 : 0
        entrySupport += f_recent(b, entrySpan) ? 1 : 0
 
        protectStrong += f_recent(a, protectSpan) ? 1 : 0
        protectSupport += f_recent(b, protectSpan) ? 1 : 0
 
        float move = array.get(flats, i)
        flatCount += not na(move) and move <= atr*flatTol ? 1 : 0
 
    bool entryMomentum = entryStrong >= strongNeed or (entryStrong >= buildNeed and entrySupport >= strongNeed)
 
    bool protectMomentum = protectStrong >= strongNeed or (protectStrong >= buildNeed and protectSupport >= strongNeed)
 
    if protectMomentum
        lastProtect := bar_index
 
    bool protectRecent = f_recent(lastProtect, protectSpan)
 
    publishedStrongCount := entryStrong
    publishedFlatCount := flatCount
 
    //━━━━━━━━━━━━━━━━ SQUEEZE EPISODE
    bool newSqueeze = squeeze and not wasSqueeze
    bool endSqueeze = not squeeze and wasSqueeze
 
    if squeeze
        lastSqueeze := bar_index
 
    flatReleaseCount := squeeze ? 0 : math.min(3, flatReleaseCount+1)
 
    if flatReleaseCount >= 3
        flatConsumed := false
 
    if newSqueeze
        frozen := array.copy(clusterIds)
 
        [initialFast, initialStruct, initialFw, initialSw, initialOK] = f_groups(frozen, powers, weights)
 
        startFast := initialFast
        releaseDelta := 0.0
        releaseBar := na
        releaseHigh := na
 
        regionUsed := false
        breakPending := false
        breakLevel := na
        breakBar := na
        breakAtr := na
 
    [fastNow, structNow, fastWeight, structWeight, completePower] = f_groups(frozen, powers, weights)
 
    if endSqueeze
        releaseBar := bar_index
        releaseHigh := high
        releaseDelta := not na(startFast) and not na(fastNow) ? fastNow-startFast : na
 
    bool releaseWindow = not na(releaseBar) and bar_index-releaseBar <= releaseBars
 
    if releaseWindow and not regionUsed
        releaseHigh := na(releaseHigh) ? high : math.max(releaseHigh, high)
 
    if releaseWindow and not na(startFast) and not na(fastNow)
        float delta = fastNow-startFast
 
        if na(releaseDelta) or math.abs(delta) >= math.abs(releaseDelta)
            releaseDelta := delta
 
    float fastDelta = squeeze and not na(startFast) and not na(fastNow) ? fastNow-startFast : releaseDelta
    float totalWeight = fastWeight+structWeight
 
    balance := completePower and totalWeight > 0 ? (nz(fastDelta)*fastWeight + (nz(structNow, 50)-50)*structWeight)/totalWeight : na
 
    //━━━━━━━━━━━━━━━━ REGION BREAKOUT
    if useBreak and releaseWindow and not regionUsed and fastWeight > 0 and not na(startFast) and not na(fastNow) and not na(balance) and balance <= balanceTrigger and not na(releaseHigh) and atr > 0
        regionUsed := true
        breakPending := true
        breakBar := bar_index
        breakLevel := releaseHigh
        breakAtr := atr
 
    if breakPending and bar_index-breakBar > breakWait
        breakPending := false
 
    float breakTrigger = breakPending ? breakLevel+breakAtr*breakBuffer : na
 
    bool breakCross = breakPending and bar_index > breakBar and close > breakTrigger and close[1] <= breakTrigger
 
    wasSqueeze := squeeze
    publishedSqueeze := squeeze
    publishedBalance := balance
 
    // Snapshot prevents an exit and re-entry on the same candle.
    bool wasHolding = holding
 
    //━━━━━━━━━━━━━━━━ EXITS
    // Common protection does not depend on MTF availability.
    if wasHolding and bar_index > entryBar and not na(close)
        bool commonHit = close <= stop
        bool flatHit = flatActive and close < flatFloor
        bool delayOver = bar_index-entryBar > protectBars
 
        float gainAtr = (close-entryClose)/entryVol
 
        bool fadeHit = useFade and delayOver and not protectMomentum and gainAtr >= fadeGain and basis <= basis[1] and close < basis
 
        bool failHit = useFail and delayOver and not protectRecent and bar_index-entryBar >= failBars and basis <= basis[1] and close < lower
 
        exitReason := commonHit ? (trailing ? 2 : 1) : flatHit ? 3 : fadeHit ? 4 : failHit ? 5 : 0
 
        if exitReason > 0
            sellSignal := true
            stopSignal := exitReason <= 3
 
            float exitFill = math.max(syminfo.mintick, close-slip*syminfo.mintick)
 
            float pnl = quantity*(exitFill-entryFill) - quantity*(entryFill+exitFill)*fee/100
 
            float netReturn = 100*(exitFill/entryFill-1) - fee*(1+exitFill/entryFill)
 
            equity += pnl
            closed += 1
            returnSum += netReturn
 
            if netReturn > 0.00000001
                wins += 1
                grossProfit += pnl
                array.set(typeWins, entryType-1, array.get(typeWins, entryType-1)+1)
 
            else if netReturn < -0.00000001
                losses += 1
                grossLoss += math.abs(pnl)
 
            else
                even += 1
 
            array.set(typeClosed, entryType-1, array.get(typeClosed, entryType-1)+1)
 
            lastNetReturn := netReturn
            lastEventType := 2
            lastEventCode := exitReason
            lastExit := bar_index
 
            holding := false
            stop := na
            flatActive := false
            trailing := false
 
        else
            if flatActive and high >= entryClose+entryVol*flatRelease
                // Keep the effective floor when the special guard expires.
                stop := math.max(stop, flatFloor)
                flatActive := false
 
            highestClose := math.max(highestClose, close)
 
            if useTrail and highestClose >= entryClose+entryVol*trailStart
                trailing := true
 
            if trailing and not na(atr) and atr > 0
                float candidate = highestClose-atr*trailAtr
 
                if breakEven
                    candidate := math.max(candidate, entryClose)
 
                candidate := math.min(candidate, close-syminfo.mintick)
 
                // Never loosen the stop.
                stop := math.max(stop, math.round_to_mintick(candidate))
 
    //━━━━━━━━━━━━━━━━ ENTRIES
    if not wasHolding and dataReady and time >= startDate and equity > 0
        bool waitDone = na(lastExit) ? true : bar_index-lastExit > cooldown
 
        bool priceConfirm = close > basis and close > open and basis >= basis[1]
        bool notChasing = close <= upper+atr*maxChase
 
        bool momentumEntry = useMomentum and f_recent(lastSqueeze, compressionMemory) and entryMomentum and priceConfirm and notChasing
 
        bool flatEntry = useFlat and not flatConsumed and squeeze and flatCount >= flatNeed and priceConfirm and notChasing
 
        // Original priority: Momentum -> Flat -> Region breakout.
        int wanted = momentumEntry ? 1 : flatEntry ? 2 : useBreak and breakCross ? 3 : 0
 
        if waitDone and wanted > 0
            holding := true
            buySignal := true
 
            entryType := wanted
            entryBar := bar_index
            entryClose := close
            entryFill := close+slip*syminfo.mintick
            entryVol := atr
 
            // Allocation includes the entry commission.
            quantity := equity*allocation/100/(entryFill*(1+fee/100))
 
            stop := math.max(syminfo.mintick, math.min(close-syminfo.mintick, math.round_to_mintick(close-atr*stopAtr)))
 
            highestClose := close
            trailing := false
 
            flatActive := wanted == 2 and flatGuard
            flatFloor := flatActive ? low : na
 
            if wanted == 2
                flatConsumed := true
 
            if breakCross
                breakPending := false
 
            lastEventType := 1
            lastEventCode := wanted
 
    //━━━━━━━━━━━━━━━━ MARKED EQUITY
    publishedStop := holding ? stop : na
    publishedBreak := breakPending ? breakLevel+breakAtr*breakBuffer : na
    publishedOpenReturn := na
 
    if not na(sampleStart)
        float markedEquity = equity
 
        if holding
            float hypotheticalExit = math.max(syminfo.mintick, close-slip*syminfo.mintick)
 
            float openPnl = quantity*(hypotheticalExit-entryFill) - quantity*(entryFill+hypotheticalExit)*fee/100
 
            markedEquity += openPnl
 
            publishedOpenReturn := 100*(hypotheticalExit/entryFill-1) - fee*(1+hypotheticalExit/entryFill)
 
        peakEquity := math.max(peakEquity, markedEquity)
 
        maxDrawdown := math.max(maxDrawdown, 100*(peakEquity-markedEquity)/peakEquity)
 
    //━━━━━━━━━━━━━━━━ LABELS
    if showSignals and (buySignal or sellSignal)
        string word = buySignal ? t("AL", "BUY") : t("SAT", "EXIT")
        string reason = buySignal ? f_entryText(entryType) : f_exitText(exitReason)
 
        string detail = reason + "\n" + t("Kapanis: ", "Close: ") + f_price(close)
 
        if sellSignal
            detail += "\n" + t("Net sinyal sonucu: ", "Net signal return: ") + f_pct(lastNetReturn)
 
        label mark = label.new(
             bar_index,
             buySignal ? low : high,
             word,
             style=buySignal ? label.style_label_up : label.style_label_down,
             color=buySignal ? buyC : sellC,
             textcolor=buySignal ? color.black : color.white,
             size=size.small,
             tooltip=detail)
 
        array.push(marks, mark)
 
        if array.size(marks) > labelLimit
            label.delete(array.shift(marks))
 
    //━━━━━━━━━━━━━━━━ DYNAMIC ALERTS
    if alertsOn and (buySignal or sellSignal)
        string reason = buySignal ? f_entryText(entryType) : f_exitText(exitReason)
 
        alert(
             "GEZEN PRO | " + syminfo.ticker +
             " | " + timeframe.period +
             " | " + (buySignal ? t("AL", "BUY") : t("SAT", "EXIT")) +
             " | " + reason +
             " | " + f_price(close),
             alert.freq_once_per_bar_close)
 
//━━━━━━━━━━━━━━━━ CHART
// Plot the protection valid during the candle.
// The newly calculated stop becomes valid on the next candle.
float validStop = holding[1] ? publishedStop[1] : buySignal ? publishedStop : na
 
float guardForBar = holding[1] and flatActive[1] ? flatFloor[1] : buySignal and flatActive ? flatFloor : na
 
float visibleStop = na(validStop) ? guardForBar : na(guardForBar) ? validStop : math.max(validStop, guardForBar)
 
f_lineColor(int i) =>
    int dir = array.get(publishedDirs, i)
    color.new(dir == 1 ? buyC : dir == -1 ? sellC : neutralC, 25)
 
plot(showRibbon ? array.get(publishedLines, 0) : na, "TF1", color=f_lineColor(0), linewidth=2, style=plot.style_linebr)
plot(showRibbon ? array.get(publishedLines, 1) : na, "TF2", color=f_lineColor(1), linewidth=2, style=plot.style_linebr)
plot(showRibbon ? array.get(publishedLines, 2) : na, "TF3", color=f_lineColor(2), linewidth=2, style=plot.style_linebr)
plot(showRibbon ? array.get(publishedLines, 3) : na, "TF4", color=f_lineColor(3), linewidth=2, style=plot.style_linebr)
plot(showRibbon ? array.get(publishedLines, 4) : na, "TF5", color=f_lineColor(4), linewidth=3, style=plot.style_linebr)
plot(showRibbon ? array.get(publishedLines, 5) : na, "TF6", color=f_lineColor(5), linewidth=3, style=plot.style_linebr)
 
pU = plot(showBands ? publishedUpper : na, "BB ust / Upper", color=color.new(neutralC, 65))
pL = plot(showBands ? publishedLower : na, "BB alt / Lower", color=color.new(neutralC, 65))
 
plot(showBands ? publishedBasis : na, "BB orta / Basis", color=color.new(neutralC, 45))
 
fill(pU, pL, color=showBands ? color.new(neutralC, 96) : na)
 
plot(
     showLevels and (holding or sellSignal) ? entryClose : na,
     "Giris / Entry",
     color=color.new(buyC, 35),
     linewidth=2,
     style=plot.style_linebr)
 
plot(
     showLevels ? visibleStop : na,
     "Gecerli koruma / Valid protection",
     color=sellC,
     linewidth=3,
     style=plot.style_linebr)
 
plot(
     showBreak ? publishedBreak : na,
     "Bekleyen kirilim / Pending break",
     color=chart.fg_color,
     linewidth=2,
     style=plot.style_linebr)
 
barcolor(showBars ? (sellSignal ? sellC : holding ? buyC : color.new(neutralC, 65)) : na)
 
bgcolor(showAura and holding ? color.new(buyC, 96) : na)
 
//━━━━━━━━━━━━━━━━ DATA WINDOW
plot(buySignal ? 1 : 0, "SCAN BUY", display=display.data_window)
plot(sellSignal ? 1 : 0, "SCAN EXIT", display=display.data_window)
plot(holding ? 1 : 0, "SCAN HOLD", display=display.data_window)
plot(publishedBalance, "BAL", display=display.data_window)
plot(publishedStop, "Sonraki mum stop / Next bar stop", display=display.data_window)
 
//━━━━━━━━━━━━━━━━ COMPACT PERFORMANCE PANEL
var table panel = table.new(
     panelSide == "RIGHT" ? position.top_right : position.top_left,
     2, 7,
     bgcolor=color.new(bgC, 15),
     frame_color=color.new(neutralC, 80),
     frame_width=1,
     border_width=0)
 
f_row(int row, string title, string value, color valueColor) =>
    table.cell(
         panel, 0, row, title,
         bgcolor=color.new(bgC, 15),
         text_color=neutralC,
         text_size=size.tiny,
         text_halign=text.align_left)
 
    table.cell(
         panel, 1, row, value,
         bgcolor=color.new(bgC, 15),
         text_color=valueColor,
         text_size=size.tiny,
         text_halign=text.align_right)
 
if barstate.islast
    if showPanel
        float winRate = closed > 0 ? 100.0*wins/closed : na
        float netPct = 100*(equity/10000-1)
 
        string status =
             holding ? t("ELDE TUT", "HOLD") :
             not publishedReady ? t("VERI BEKLE", "WAIT DATA") :
             t("BEKLE", "WAIT")
 
        string pf =
             closed == 0 ? "-" :
             grossLoss > 0 ? str.tostring(grossProfit/grossLoss, "#.2") :
             grossProfit > 0 ? "∞" : "-"
 
        f_row(
             0, "GEZEN",
             status,
             holding ? buyC : neutralC)
 
        f_row(
             1, t("Basari", "Win rate"),
             f_pct(winRate),
             closed == 0 ? neutralC : winRate >= 50 ? buyC : sellC)
 
        f_row(
             2, t("Kapali / Kazanan", "Closed / Wins"),
             str.tostring(closed)+" / "+str.tostring(wins),
             neutralC)
 
        f_row(
             3, t("Net sermaye", "Net equity"),
             f_pct(netPct),
             f_color(netPct))
 
        f_row(
             4, t("Kar faktoru", "Profit factor"),
             pf,
             grossProfit > grossLoss ? buyC : neutralC)
 
        f_row(
             5, t("Maks. dusus", "Max drawdown"),
             f_pct(maxDrawdown),
             maxDrawdown > 0 ? sellC : neutralC)
 
        f_row(
             6, t("Acik net", "Open net"),
             f_pct(publishedOpenReturn),
             f_color(publishedOpenReturn))
    else
        table.clear(panel, 0, 0, 1, 6)
 
//━━━━━━━━━━━━━━━━ ALERT CONDITIONS
alertcondition(
     buySignal,
     "GEZEN AL / BUY",
     "GEZEN BUY | {{ticker}} | {{interval}} | {{close}}")
 
alertcondition(
     sellSignal,
     "GEZEN SAT / EXIT",
     "GEZEN EXIT | {{ticker}} | {{interval}} | {{close}}")
 
alertcondition(
     stopSignal,
     "GEZEN KORUMA / PROTECTION",
     "GEZEN PROTECTION | {{ticker}} | {{interval}} | {{close}}")

← 返回列表