Smart Gaps Pro

Scalp-Alp · study · 646 行 · 点赞 34 · TradingView 原页

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

Pine Script

// This work is licensed under CC BY-NC-SA 4.0  https://creativecommons.org/licenses/by-nc-sa/4.0/
// Original IFVG concept & base code: © LuxAlgo
// Modified work: Smart Gaps Pro [ALP] — Regular FVG + IFVG + MTF, unified zone engine, non-repainting HTF
// v3.0 — full rewrite of v2 ("IFVG + FVG + MTF")
//   • Pine v6
//   • HTF data is taken only from CLOSED HTF candles (no repaint), HTF <= chart TF guard, Auto HTF
//   • One zone life-cycle: FVG -> (broken) -> IFVG -> (broken) -> removed  (no FVG/IFVG overlap)
//   • Confirmed-bar mode for zones, signals and alerts
//   • Fill %, nearest-to-price selection, persistent signal history, JSON webhook alerts
//   • New visuals: single box per zone, accent strip, in-box label, ▲/▼ markers, new palettes
 
//@version=6
indicator("Smart Gaps Pro [ALP]", "Smart Gaps Pro by 🅰🅻🅿 🇹🇷", overlay = true,
     max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
//═════════════════════════════════════════════════════════════════════════════
// INPUTS
//═════════════════════════════════════════════════════════════════════════════
const string G_GEN = "⚙️ General"
const string G_ZON = "◧ Zones"
const string G_MTF = "⏱ Multi-Timeframe"
const string G_SIG = "🎯 Signals"
const string G_STY = "🎨 Style"
const string G_COL = "🖌 Custom Colors (Palette = Custom)"
const string G_ALR = "🔔 Alerts"
 
// ── General ──
lang        = input.string("English", "Language / Dil", options = ["English", "Türkçe"], group = G_GEN,
     tooltip = "EN: Language of on-chart texts (table, warnings, alert messages). Input names stay in English because Pine Script cannot change them at runtime.\nTR: Grafik üzerindeki yazıların dili (tablo, uyarılar, alarm mesajları). Pine Script girdi adlarını çalışma anında değiştiremediği için ayar adları İngilizce kalır.")
confirmOnly = input.bool(true, "Confirmed Bars Only", group = G_GEN,
     tooltip = "EN: Zones, signals and alerts are evaluated only when the bar closes. Prevents repainting and false intrabar alerts. Recommended: ON.\nTR: Bölgeler, sinyaller ve alarmlar sadece bar kapandığında değerlendirilir. Repaint ve bar içi sahte alarmları önler. Önerilen: AÇIK.")
atrMult     = input.float(0.25, "Min Gap Size (× ATR)", minval = 0, step = 0.05, group = G_GEN,
     tooltip = "EN: A gap must be larger than ATR(200) × this value to count as an FVG. 0 = no filter.\nTR: Bir boşluğun FVG sayılması için ATR(200) × bu değerden büyük olması gerekir. 0 = filtre yok.")
 
// ── Zones ──
showFvg  = input.bool(true, "Regular FVG", group = G_ZON, inline = "z1")
showIfvg = input.bool(true, "Inverse FVG (IFVG)", group = G_ZON, inline = "z1",
     tooltip = "EN: Show chart-timeframe FVG zones and/or inverted FVG zones (an FVG that price closed through).\nTR: Grafik zaman dilimindeki FVG bölgelerini ve/veya ters dönmüş FVG (IFVG — fiyatın içinden kapanış yaptığı FVG) bölgelerini göster.")
showN    = input.int(5, "Zones Shown per Type", minval = 1, maxval = 20, group = G_ZON,
     tooltip = "EN: Maximum number of zones drawn for each type (FVG, IFVG, HTF FVG, HTF IFVG).\nTR: Her tür için (FVG, IFVG, HTF FVG, HTF IFVG) çizilecek en fazla bölge sayısı.")
pickMode = input.string("Nearest to Price", "Zone Selection", options = ["Nearest to Price", "Most Recent"], group = G_ZON,
     tooltip = "EN: Nearest to Price = draw the zones closest to the current price. Most Recent = draw the newest zones.\nTR: Nearest to Price = güncel fiyata en yakın bölgeler çizilir. Most Recent = en yeni bölgeler çizilir.")
invSrc   = input.string("Close", "Invalidation Source", options = ["Close", "Wick"], group = G_ZON,
     tooltip = "EN: What breaks a zone. Close = a candle must close beyond the zone. Wick = a wick beyond the zone is enough. A broken FVG becomes an IFVG; a broken IFVG is removed.\nTR: Bölgeyi neyin kırdığı. Close = mumun bölgenin ötesinde kapanması gerekir. Wick = fitilin geçmesi yeterlidir. Kırılan FVG, IFVG'ye dönüşür; kırılan IFVG silinir.")
 
showHist = input.bool(false, "Show Past Zones", group = G_ZON, inline = "z2")
histN    = input.int(10, "Count", minval = 1, maxval = 40, group = G_ZON, inline = "z2",
     tooltip = "EN: Past zones = zones that completed their life (FVG → IFVG → broken). ON draws the most recent ones as faded boxes that end where they were broken, for both chart TF and HTF. OFF = only active zones.\nTR: Geçmiş bölgeler = ömrünü tamamlamış bölgeler (FVG → IFVG → kırıldı). AÇIK iken en son olanlar, kırıldıkları yerde biten soluk kutular olarak çizilir (grafik TF ve HTF). KAPALI = sadece aktif bölgeler.")
 
// ── MTF ──
showHFvg  = input.bool(true, "HTF Regular FVG", group = G_MTF, inline = "m1")
showHIfvg = input.bool(true, "HTF IFVG", group = G_MTF, inline = "m1",
     tooltip = "EN: Show zones from the higher timeframe. Only closed HTF candles are used (non-repainting).\nTR: Üst zaman dilimi bölgelerini göster. Sadece kapanmış HTF mumları kullanılır (repaint yok).")
htfMode   = input.string("Auto", "HTF Mode", options = ["Auto", "Manual"], group = G_MTF,
     tooltip = "EN: Auto picks the HTF from the chart timeframe: ≤1m→15m, ≤5m→1H, ≤15m→4H, ≤1H→1D, ≤1D→1W, 1W→1M, 1M→12M. Manual uses the timeframe below.\nTR: Auto, HTF'yi grafik zaman dilimine göre seçer: ≤1dk→15dk, ≤5dk→1S, ≤15dk→4S, ≤1S→1G, ≤1G→1H, 1H→1A, 1A→12A. Manual aşağıdaki zaman dilimini kullanır.")
htfManual = input.timeframe("240", "Manual HTF", group = G_MTF,
     tooltip = "EN: Used only when HTF Mode = Manual. Must be HIGHER than the chart timeframe, otherwise HTF zones are disabled and a warning is shown in the table.\nTR: Sadece HTF Mode = Manual iken kullanılır. Grafik zaman diliminden BÜYÜK olmalıdır; aksi halde HTF bölgeleri kapatılır ve tabloda uyarı gösterilir.")
htfInvBy  = input.string("HTF Close", "HTF Invalidation By", options = ["HTF Close", "Chart Close"], group = G_MTF,
     tooltip = "EN: HTF Close = an HTF zone is broken only when an HTF candle closes beyond it (stricter, classic). Chart Close = a chart-timeframe candle is enough (faster). Follows 'Invalidation Source' for Close/Wick.\nTR: HTF Close = HTF bölgesi sadece bir HTF mumu ötesinde kapanınca kırılır (daha sıkı, klasik). Chart Close = grafik zaman dilimi mumu yeterlidir (daha hızlı). Close/Wick seçimi 'Invalidation Source' ayarını izler.")
 
// ── Signals ──
showMarks = input.bool(true, "Show Signal Markers", group = G_SIG,
     tooltip = "EN: Draw ▲ (buy) / ▼ (sell) markers when price retests a zone. HTF markers carry the timeframe tag.\nTR: Fiyat bir bölgeyi yeniden test ettiğinde ▲ (al) / ▼ (sat) işaretleri çizilir. HTF işaretlerinde zaman dilimi etiketi bulunur.")
sigSrc    = input.string("Close", "Signal Trigger", options = ["Close", "Wick"], group = G_SIG,
     tooltip = "EN: Close = the retest is measured with candle closes. Wick = with candle wicks (earlier, more signals). FVG signal = price enters the zone; IFVG signal = price enters and closes back out (rejection).\nTR: Close = yeniden test mum kapanışlarıyla ölçülür. Wick = fitillerle ölçülür (daha erken, daha çok sinyal). FVG sinyali = fiyat bölgeye girer; IFVG sinyali = fiyat girer ve dışarıda kapanır (reddedilme).")
maxSig    = input.int(3, "Max Signals per Zone", minval = 1, maxval = 20, group = G_SIG,
     tooltip = "EN: How many signals a single zone may produce. The counter resets when an FVG turns into an IFVG.\nTR: Tek bir bölgenin üretebileceği sinyal sayısı. FVG, IFVG'ye dönüştüğünde sayaç sıfırlanır.")
marksActive = input.bool(true, "Markers Only for Visible Zones", group = G_SIG,
     tooltip = "EN: ON = a marker is shown only while its zone box is on the chart; when the box disappears the marker disappears too. OFF = keep a history of the most recent markers even after their zones are gone.\nTR: AÇIK = işaret sadece bölge kutusu grafikteyken gösterilir; kutu silinince işaret de silinir. KAPALI = bölgeler silinse bile en son işaretlerin geçmişi grafikte tutulur.")
maxMarks  = input.int(30, "Marker History Size", minval = 1, maxval = 200, group = G_SIG,
     tooltip = "EN: Used only when 'Markers Only for Visible Zones' is OFF: number of most recent markers kept on the chart.\nTR: Sadece 'Markers Only for Visible Zones' KAPALI iken kullanılır: grafikte tutulan en son işaret sayısı.")
 
colorBars = input.bool(true, "Color Bars by Last Signal", group = G_SIG,
     tooltip = "EN: Paints all candles with the bullish color after a buy signal and the bearish color after a sell signal; the color is kept until an opposite signal arrives. Uses every enabled signal type (FVG, IFVG, HTF). Before the first signal candles keep their normal color.\nTR: Al sinyalinden sonra tüm mumları boğa rengine, sat sinyalinden sonra ayı rengine boyar; ters yönde sinyal gelene kadar renk korunur. Açık olan tüm sinyal türlerini kullanır (FVG, IFVG, HTF). İlk sinyalden önce mumlar normal renginde kalır.")
 
// ── Style ──
palette   = input.string("Aurora", "Color Palette", options = ["Aurora", "Ocean", "Sunset", "Mono", "Custom"], group = G_STY,
     tooltip = "EN: Ready-made color sets. Choose Custom to use the colors in the 'Custom Colors' section.\nTR: Hazır renk setleri. 'Custom Colors' bölümündeki renkleri kullanmak için Custom seçin.")
fillOp    = input.int(14, "Fill Opacity %", minval = 0, maxval = 60, group = G_STY,
     tooltip = "EN: Opacity of the zone fill. Lower = cleaner chart.\nTR: Bölge dolgusunun opaklığı. Düşük değer = daha temiz grafik.")
borderW   = input.int(1, "Border Width", minval = 1, maxval = 4, group = G_STY, inline = "s1")
accentW   = input.int(3, "Accent Width", minval = 0, maxval = 8, group = G_STY, inline = "s1",
     tooltip = "EN: Border Width = thickness of the zone outline (HTF zones use a dashed outline). Accent Width = thickness of the solid strip on the zone's left edge, 0 hides it.\nTR: Border Width = bölge çerçevesinin kalınlığı (HTF bölgeleri kesikli çerçeve kullanır). Accent Width = bölgenin sol kenarındaki dolu şeridin kalınlığı, 0 gizler.")
extBars   = input.int(30, "Extend Right (bars)", minval = 5, maxval = 300, group = G_STY,
     tooltip = "EN: How many bars the zones extend to the right of the current bar. The zone label sits in this area.\nTR: Bölgelerin güncel barın sağına kaç bar uzayacağı. Bölge etiketi bu alanda durur.")
showTxt   = input.bool(true, "Zone Labels", group = G_STY, inline = "s2")
showFill  = input.bool(true, "Fill %", group = G_STY, inline = "s2")
showMid   = input.bool(true, "Midline", group = G_STY, inline = "s2",
     tooltip = "EN: Zone Labels = type · timeframe · price range inside the zone. Fill % = how much of the zone price has already filled. Midline = dotted 50% (CE) line.\nTR: Zone Labels = bölge içinde tür · zaman dilimi · fiyat aralığı. Fill % = fiyatın bölgenin ne kadarını doldurduğu. Midline = noktalı %50 (CE) çizgisi.")
txtSizeIn = input.string("Small", "Label Size", options = ["Tiny", "Small", "Normal"], group = G_STY,
     tooltip = "EN: Text size of zone labels and signal markers.\nTR: Bölge etiketlerinin ve sinyal işaretlerinin yazı boyutu.")
showTable = input.bool(true, "Info Table", group = G_STY, inline = "s3")
tablePos  = input.string("Bottom Right", "", options = ["Top Left", "Top Right", "Bottom Left", "Bottom Right"], group = G_STY, inline = "s3")
tableSzIn = input.string("Normal", "", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = G_STY, inline = "s3",
     tooltip = "EN: Dashboard on/off, its position and its text size. It lists only the zone types you enabled, the active HTF settings, the current signal bias and the last signal. Counts are ALL active zones of that type, not only the ones drawn.\nTR: Pano aç/kapa, konumu ve yazı boyutu. Sadece açtığın bölge türlerini, kullanılan HTF ayarlarını, güncel sinyal yönünü ve son sinyali listeler. Sayılar o türdeki TÜM aktif bölgelerdir, sadece çizilenler değil.")
 
// ── Custom colors ──
cuBull  = input.color(#2DD4BF, "FVG   Bull", group = G_COL, inline = "c1")
cuBear  = input.color(#FB7185, "Bear", group = G_COL, inline = "c1",
     tooltip = "EN: Regular FVG colors (used only when Palette = Custom).\nTR: Regular FVG renkleri (sadece Palette = Custom iken kullanılır).")
cuIBull = input.color(#60A5FA, "IFVG  Bull", group = G_COL, inline = "c2")
cuIBear = input.color(#FBBF24, "Bear", group = G_COL, inline = "c2",
     tooltip = "EN: Inverse FVG colors (used only when Palette = Custom).\nTR: IFVG renkleri (sadece Palette = Custom iken kullanılır).")
cuHBull = input.color(#A78BFA, "HTF   Bull", group = G_COL, inline = "c3")
cuHBear = input.color(#F472B6, "Bear", group = G_COL, inline = "c3",
     tooltip = "EN: Higher-timeframe zone colors (used only when Palette = Custom).\nTR: Üst zaman dilimi bölge renkleri (sadece Palette = Custom iken kullanılır).")
 
// ── Alerts ──
alFvg   = input.bool(true, "FVG Signals", group = G_ALR, inline = "a1")
alIfvg  = input.bool(true, "IFVG Signals", group = G_ALR, inline = "a1",
     tooltip = "EN: Chart-timeframe retest signals sent through 'Any alert() function call'.\nTR: Grafik zaman dilimi yeniden test sinyalleri; 'Any alert() function call' alarmı üzerinden gönderilir.")
alHFvg  = input.bool(true, "HTF FVG Signals", group = G_ALR, inline = "a2")
alHIfvg = input.bool(true, "HTF IFVG Signals", group = G_ALR, inline = "a2",
     tooltip = "EN: Higher-timeframe retest signals, each with its own switch.\nTR: Üst zaman dilimi yeniden test sinyalleri; her birinin ayrı anahtarı vardır.")
alNew   = input.bool(false, "New FVG Formed", group = G_ALR, inline = "a3")
alInv   = input.bool(false, "FVG → IFVG Inversion", group = G_ALR, inline = "a3",
     tooltip = "EN: Event alerts (chart TF and HTF): a new FVG was created / an FVG was broken and became an IFVG. Can be frequent on low timeframes.\nTR: Olay alarmları (grafik TF ve HTF): yeni FVG oluştu / bir FVG kırılıp IFVG'ye dönüştü. Düşük zaman dilimlerinde sık gelebilir.")
useJson = input.bool(false, "JSON Message (Webhook)", group = G_ALR,
     tooltip = "EN: Send alert() messages as JSON for webhooks/bots: indicator, event, side, type, htf, zone_tf, symbol, tf, price, top, bottom, time. If several events happen on one bar they are sent as a JSON array.\nTR: alert() mesajlarını webhook/bot için JSON olarak gönderir: indicator, event, side, type, htf, zone_tf, symbol, tf, price, top, bottom, time. Aynı barda birden fazla olay olursa JSON dizisi olarak gönderilir.")
 
//═════════════════════════════════════════════════════════════════════════════
// TYPES
//═════════════════════════════════════════════════════════════════════════════
type Sig
    int    t
    int    bi
    float  y
    int    dir
    string kind
    bool   htf
    string tf
 
type Zone
    int   left          // time of the middle candle (left edge)
    int   born          // chart time when the zone was registered
    float top
    float bot
    float mid
    int   dir           // original direction:  1 = bullish FVG, -1 = bearish FVG
    int   invT = na     // chart time of inversion (na = still a regular FVG)
    int   endT = na     // chart time when the IFVG was broken (past zone)
    int   sigs = 0      // signals produced in the current state
    float fill          // deepest price reached inside the zone in the current state
    array<Sig> marks    // signals produced by this zone (removed together with the zone)
 
//═════════════════════════════════════════════════════════════════════════════
// HELPERS
//═════════════════════════════════════════════════════════════════════════════
bool tr       = lang == "Türkçe"
bool live     = not confirmOnly or barstate.isconfirmed
bool wickInv  = invSrc == "Wick"
bool wickSig  = sigSrc == "Wick"
bool byProx   = pickMode == "Nearest to Price"
int  fillT    = 100 - fillOp
int  MAX_ZONES = 120
int  MAX_SIGS  = 300
 
float c1 = close[1]
float h1 = high[1]
float l1 = low[1]
 
f_t(string en, string trTxt) => tr ? trTxt : en
 
f_px(float p) =>
    p >= 1000000 ? str.tostring(p / 1000000, "#.##") + "M" : p >= 10000 ? str.tostring(p / 1000, "#.#") + "K" : str.tostring(p, format.mintick)
 
f_tfLabel(string tf) =>
    int s = timeframe.in_seconds(tf)
    string r = ""
    if s < 60
        r := str.tostring(s) + "s"
    else if s < 3600 or (s < 86400 and s % 3600 != 0)
        r := str.tostring(math.floor(s / 60.0)) + "m"
    else if s < 86400
        r := str.tostring(math.floor(s / 3600.0)) + "H"
    else if s < 604800
        r := str.tostring(math.floor(s / 86400.0)) + "D"
    else if s < 2419200
        r := str.tostring(math.floor(s / 604800.0)) + "W"
    else
        r := str.tostring(math.round(s / 2628003.0)) + "M"
    r
 
f_autoHtf() =>
    int s = timeframe.in_seconds()
    s <= 60 ? "15" : s <= 300 ? "60" : s <= 900 ? "240" : s <= 3600 ? "D" : s <= 86400 ? "W" : s <= 604800 ? "M" : "12M"
 
//═════════════════════════════════════════════════════════════════════════════
// COLORS
//═════════════════════════════════════════════════════════════════════════════
[colBull, colBear, colIBull, colIBear, colHBull, colHBear] = switch palette
    "Aurora" => [#2DD4BF, #FB7185, #60A5FA, #FBBF24, #A78BFA, #F472B6]
    "Ocean"  => [#22D3EE, #F97316, #3B82F6, #EAB308, #14B8A6, #EF4444]
    "Sunset" => [#A3E635, #F43F5E, #FACC15, #C084FC, #4ADE80, #FB923C]
    "Mono"   => [#E5E7EB, #6B7280, #F9FAFB, #9CA3AF, #D1D5DB, #4B5563]
    =>          [cuBull,  cuBear,  cuIBull, cuIBear, cuHBull, cuHBear]
 
string txtSize = switch txtSizeIn
    "Tiny"   => size.tiny
    "Normal" => size.normal
    =>          size.small
 
//═════════════════════════════════════════════════════════════════════════════
// STATE
//═════════════════════════════════════════════════════════════════════════════
var array<Zone> ltfZones = array.new<Zone>()
var array<Zone> htfZones = array.new<Zone>()
var array<Zone> ltfHist  = array.new<Zone>()
var array<Zone> htfHist  = array.new<Zone>()
var array<Sig>  sigLog   = array.new<Sig>()
array<string>   alertBuf = array.new<string>()      // rebuilt on every bar
 
//═════════════════════════════════════════════════════════════════════════════
// ALERT MESSAGE BUILDER
//═════════════════════════════════════════════════════════════════════════════
f_msg(string event, string side, string kind, bool isHtf, string tfTxt, float top, float bot) =>
    string out = ""
    if useJson
        out := '{"indicator":"SmartGapsPro","event":"' + event + '","side":"' + side + '","type":"' + kind + '","htf":' + (isHtf ? "true" : "false") + ',"zone_tf":"' + tfTxt + '","symbol":"' + syminfo.ticker + '","tf":"' + timeframe.period + '","price":' + str.tostring(close) + ',"top":' + str.tostring(top) + ',"bottom":' + str.tostring(bot) + ',"time":' + str.tostring(time) + '}'
    else
        string ev = switch event
            "signal"  => f_t("retest signal", "yeniden test sinyali")
            "new_fvg" => f_t("new zone formed", "yeni bölge oluştu")
            =>           f_t("FVG inverted to IFVG", "FVG, IFVG'ye dönüştü")
        string sd = switch side
            "buy"  => f_t("BUY", "AL")
            "sell" => f_t("SELL", "SAT")
            "bull" => f_t("BULLISH", "BOĞA")
            =>        f_t("BEARISH", "AYI")
        out := "Smart Gaps Pro | " + sd + " | " + (isHtf ? "HTF " : "") + kind + " · " + ev + " | " + syminfo.ticker + " " + timeframe.period + " | " + f_t("zone ", "bölge ") + tfTxt + " " + f_px(bot) + "–" + f_px(top) + " | " + f_t("price ", "fiyat ") + str.tostring(close, format.mintick)
    out
 
//═════════════════════════════════════════════════════════════════════════════
// ZONE ENGINE  — fill tracking, invalidation / inversion, retest signals
//═════════════════════════════════════════════════════════════════════════════
f_manage(array<Zone> zones, array<Zone> hist, bool isHtf, bool doInv, float invHi, float invLo, string tfTxt, bool sigFvgOn, bool sigIfvgOn, bool alertFvg, bool alertIfvg, bool alertInv) =>
    bool fBuy   = false
    bool fSell  = false
    bool iBuy   = false
    bool iSell  = false
    bool newInv = false
    while zones.size() > MAX_ZONES
        zones.shift()
    if zones.size() > 0
        for i = zones.size() - 1 to 0
            Zone z   = zones.get(i)
            bool inv = not na(z.invT)
            int  rd  = inv ? -z.dir : z.dir          // role: 1 = support, -1 = resistance
            int  t0  = inv ? z.invT : z.born
 
            // fill tracking (bars after the zone was born / inverted)
            if time > t0
                if rd == 1
                    z.fill := math.min(z.fill, low)
                else
                    z.fill := math.max(z.fill, high)
 
            // invalidation: FVG -> IFVG, IFVG -> removed
            bool broken = doInv and live and time > z.born and (rd == 1 ? invLo < z.bot : invHi > z.top)
            if broken
                if inv
                    z.endT := time
                    hist.push(z)
                    if hist.size() > 60
                        hist.shift()
                    zones.remove(i)
                else
                    z.invT := time
                    z.sigs := 0
                    z.fill := z.dir == 1 ? z.bot : z.top
                    newInv := true
                    if alertInv
                        alertBuf.push(f_msg("new_ifvg", z.dir == 1 ? "bear" : "bull", "IFVG", isHtf, tfTxt, z.top, z.bot))
                continue
 
            // retest signals
            bool typeOn = inv ? sigIfvgOn : sigFvgOn
            if typeOn and live and z.sigs < maxSig and time > t0
                bool buy  = false
                bool sell = false
                if not inv
                    // regular FVG: price comes back into the zone
                    if rd == 1
                        buy := wickSig ? (l1 >= z.top and low <= z.top and low >= z.bot) : (c1 >= z.top and close <= z.top and close >= z.bot)
                    else
                        sell := wickSig ? (h1 <= z.bot and high >= z.bot and high <= z.top) : (c1 <= z.bot and close >= z.bot and close <= z.top)
                else
                    // IFVG: price enters the zone and closes back out (rejection)
                    if rd == 1
                        float ref = wickSig ? low : c1
                        buy := close > z.top and ref <= z.top and ref > z.bot
                    else
                        float ref = wickSig ? high : c1
                        sell := close < z.bot and ref >= z.bot and ref < z.top
                if buy or sell
                    z.sigs += 1
                    string kind = inv ? "IFVG" : "FVG"
                    Sig s = Sig.new(time, bar_index, buy ? z.bot : z.top, buy ? 1 : -1, kind, isHtf, tfTxt)
                    sigLog.push(s)
                    z.marks.push(s)
                    if (inv and alertIfvg) or (not inv and alertFvg)
                        alertBuf.push(f_msg("signal", buy ? "buy" : "sell", kind, isHtf, tfTxt, z.top, z.bot))
                    if inv
                        iBuy  := iBuy or buy
                        iSell := iSell or sell
                    else
                        fBuy  := fBuy or buy
                        fSell := fSell or sell
    [fBuy, fSell, iBuy, iSell, newInv]
 
//═════════════════════════════════════════════════════════════════════════════
// DATA
//═════════════════════════════════════════════════════════════════════════════
// ATR base (fallback = average range until ATR(200) is available); multiplier applied to both
float atrBase = nz(ta.atr(200), ta.cum(high - low) / (bar_index + 1))
float thr     = atrBase * atrMult
 
// HTF — only CLOSED candles: [1] offset + lookahead_on  (identical on history and realtime)
string htfTf  = htfMode == "Auto" ? f_autoHtf() : htfManual
bool   htfOk  = timeframe.in_seconds(htfTf) > timeframe.in_seconds()
string htfTxt = f_tfLabel(htfTf)
string ltfTxt = f_tfLabel(timeframe.period)
 
[hH1, hH3, hL1, hL3, hC1, hC2, hT1, hT2, hAtr] = request.security(syminfo.tickerid, htfTf,
     [high[1], high[3], low[1], low[3], close[1], close[2], time[1], time[2], atrBase[1]],
     lookahead = barmerge.lookahead_on)
 
bool newHtf = htfOk and not na(hT1) and hT1 != nz(hT1[1], -1)
 
//═════════════════════════════════════════════════════════════════════════════
// PIPELINE  — manage existing zones first, then register new ones
//═════════════════════════════════════════════════════════════════════════════
// chart timeframe
float invHiL = wickInv ? high : close
float invLoL = wickInv ? low  : close
[sFvgBuy, sFvgSell, sIfvgBuy, sIfvgSell, evInv] = f_manage(ltfZones, ltfHist, false, true, invHiL, invLoL, ltfTxt,
     showFvg, showIfvg, alFvg, alIfvg, alInv)
 
// higher timeframe
bool  htfByHtf = htfInvBy == "HTF Close"
bool  htfDoInv = htfByHtf ? newHtf : true
float invHiH   = htfByHtf ? (wickInv ? hH1 : hC1) : invHiL
float invLoH   = htfByHtf ? (wickInv ? hL1 : hC1) : invLoL
[sHFvgBuy, sHFvgSell, sHIfvgBuy, sHIfvgSell, evHInv] = f_manage(htfZones, htfHist, true, htfDoInv, invHiH, invLoH, htfTxt,
     showHFvg and htfOk, showHIfvg and htfOk, alHFvg, alHIfvg, alInv)
 
// new chart-timeframe FVG
bool bullGap = live and low > high[2] and close[1] > high[2] and (low - high[2]) > thr
bool bearGap = live and high < low[2] and close[1] < low[2] and (low[2] - high) > thr
 
if bullGap
    ltfZones.push(Zone.new(left = time[1], born = time, top = low, bot = high[2], mid = math.avg(low, high[2]), dir = 1, fill = low, marks = array.new<Sig>()))
    if alNew
        alertBuf.push(f_msg("new_fvg", "bull", "FVG", false, ltfTxt, low, high[2]))
if bearGap
    ltfZones.push(Zone.new(left = time[1], born = time, top = low[2], bot = high, mid = math.avg(high, low[2]), dir = -1, fill = high, marks = array.new<Sig>()))
    if alNew
        alertBuf.push(f_msg("new_fvg", "bear", "FVG", false, ltfTxt, low[2], high))
 
// new HTF FVG (candles A = [3], B = [2], C = [1] — all closed)
float hThr     = hAtr * atrMult
bool  hBullGap = newHtf and live and hL1 > hH3 and hC2 > hH3 and (hL1 - hH3) > hThr
bool  hBearGap = newHtf and live and hH1 < hL3 and hC2 < hL3 and (hL3 - hH1) > hThr
 
if hBullGap
    htfZones.push(Zone.new(left = hT2, born = time, top = hL1, bot = hH3, mid = math.avg(hL1, hH3), dir = 1, fill = hL1, marks = array.new<Sig>()))
    if alNew
        alertBuf.push(f_msg("new_fvg", "bull", "FVG", true, htfTxt, hL1, hH3))
if hBearGap
    htfZones.push(Zone.new(left = hT2, born = time, top = hL3, bot = hH1, mid = math.avg(hH1, hL3), dir = -1, fill = hH1, marks = array.new<Sig>()))
    if alNew
        alertBuf.push(f_msg("new_fvg", "bear", "FVG", true, htfTxt, hL3, hH1))
 
while sigLog.size() > MAX_SIGS
    sigLog.shift()
 
// signal bias: direction of the last signal, kept until an opposite signal
bool anyBuy  = sFvgBuy or sIfvgBuy or sHFvgBuy or sHIfvgBuy
bool anySell = sFvgSell or sIfvgSell or sHFvgSell or sHIfvgSell
var int bias = 0
if anyBuy and not anySell
    bias := 1
else if anySell and not anyBuy
    bias := -1
 
//═════════════════════════════════════════════════════════════════════════════
// DRAWING
//═════════════════════════════════════════════════════════════════════════════
int extMs = timeframe.in_seconds() * 1000 * extBars
 
// indexes of the zones to draw for one type (regular or inverted)
f_pick(array<Zone> zones, bool wantInv) =>
    array<int>   idx  = array.new<int>()
    array<float> dist = array.new<float>()
    for [i, z] in zones
        if (not na(z.invT)) == wantInv
            idx.push(i)
            dist.push(close >= z.bot and close <= z.top ? 0.0 : math.min(math.abs(close - z.top), math.abs(close - z.bot)))
    array<int> picked = array.new<int>()
    int n = idx.size()
    if n > 0
        if byProx
            array<int> ord = dist.sort_indices(order.ascending)
            for k = 0 to math.min(n, showN) - 1
                picked.push(idx.get(ord.get(k)))
        else
            for k = math.max(0, n - showN) to n - 1
                picked.push(idx.get(k))
    picked
 
f_mark(Sig s) =>
    color  c   = s.htf ? (s.dir == 1 ? colHBull : colHBear) : s.kind == "IFVG" ? (s.dir == 1 ? colIBull : colIBear) : (s.dir == 1 ? colBull : colBear)
    string mk  = s.dir == 1 ? "▲" + (s.htf ? "\n" + s.tf : "") : (s.htf ? s.tf + "\n" : "") + "▼"
    string tip = (s.dir == 1 ? f_t("BUY", "AL") : f_t("SELL", "SAT")) + " · " + (s.htf ? "HTF " : "") + s.kind + " " + s.tf + " · " + str.tostring(s.y, format.mintick)
    label.new(s.t, s.y, mk, xloc = xloc.bar_time,
         style = s.dir == 1 ? label.style_label_up : label.style_label_down,
         color = color.new(c, 100), textcolor = c, size = txtSize, tooltip = tip)
 
// past zones: faded FVG part + faded IFVG part, ending where the zone was broken
f_drawHist(array<Zone> hist, bool isHtf, color cBull, color cBear, color cIBull, color cIBear) =>
    int n = hist.size()
    if n > 0
        for k = math.max(0, n - histN) to n - 1
            Zone  z    = hist.get(k)
            color orig = z.dir == 1 ? cBull : cBear
            color invC = z.dir == 1 ? cIBear : cIBull
            int   ft   = math.min(97, fillT + 8)
            box.new(z.left, z.top, z.invT, z.bot, xloc = xloc.bar_time,
                 bgcolor = color.new(orig, ft), border_color = color.new(orig, 75),
                 border_width = 1, border_style = line.style_dotted)
            box.new(z.invT, z.top, z.endT, z.bot, xloc = xloc.bar_time,
                 bgcolor = color.new(invC, ft), border_color = color.new(invC, 75),
                 border_width = 1, border_style = isHtf ? line.style_dashed : line.style_dotted)
            if showMarks and marksActive
                for s in z.marks
                    f_mark(s)
 
f_draw(Zone z, bool isHtf, color cBull, color cBear, color cIBull, color cIBear, string tfTxt) =>
    bool   inv   = not na(z.invT)
    int    rd    = inv ? -z.dir : z.dir
    color  base  = inv ? (rd == 1 ? cIBull : cIBear) : (rd == 1 ? cBull : cBear)
    int    xs    = inv ? z.invT : z.left
    int    xr    = time + extMs
    string bSty  = isHtf ? line.style_dashed : line.style_solid
    float  h     = z.top - z.bot
    float  pct   = h > 0 ? (rd == 1 ? (z.top - math.max(z.fill, z.bot)) / h : (math.min(z.fill, z.top) - z.bot) / h) * 100 : 0.0
    string txt   = ""
    if showTxt
        txt := (rd == 1 ? "▲ " : "▼ ") + (isHtf ? "HTF " : "") + (inv ? "IFVG" : "FVG") + " · " + tfTxt + " · " + f_px(z.bot) + "–" + f_px(z.top) + (showFill ? " · " + str.tostring(math.round(math.max(0, math.min(100, pct)))) + "%" : "") + "  "
 
    // faded "before inversion" part
    if inv
        color orig = z.dir == 1 ? cBull : cBear
        box.new(z.left, z.top, z.invT, z.bot, xloc = xloc.bar_time,
             bgcolor = color.new(orig, math.min(97, fillT + 8)), border_color = color.new(orig, 75),
             border_width = 1, border_style = line.style_dotted)
 
    // active part
    box.new(xs, z.top, xr, z.bot, xloc = xloc.bar_time,
         bgcolor = color.new(base, fillT), border_color = color.new(base, 45),
         border_width = borderW, border_style = bSty,
         text = txt, text_color = color.new(base, 5), text_size = txtSize,
         text_halign = text.align_right, text_valign = text.align_center)
 
    // accent strip on the left edge
    if accentW > 0
        line.new(xs, z.top, xs, z.bot, xloc = xloc.bar_time, color = base, width = accentW)
 
    // midline (CE) up to the current bar
    if showMid
        line.new(xs, z.mid, time, z.mid, xloc = xloc.bar_time, color = color.new(base, 40), style = line.style_dotted, width = 1)
 
    // markers of this zone — they live and die with the box
    if showMarks and marksActive
        for s in z.marks
            f_mark(s)
 
f_drawSet(array<Zone> zones, bool wantInv, bool isHtf, color cBull, color cBear, color cIBull, color cIBear, string tfTxt) =>
    array<int> picked = f_pick(zones, wantInv)
    for i in picked
        f_draw(zones.get(i), isHtf, cBull, cBear, cIBull, cIBear, tfTxt)
 
f_count(array<Zone> zones, bool wantInv, int role) =>
    int n = 0
    for z in zones
        bool inv = not na(z.invT)
        if inv == wantInv and (inv ? -z.dir : z.dir) == role
            n += 1
    n
 
var table tbl = na
 
if barstate.islast
    for b in box.all
        box.delete(b)
    for l in line.all
        line.delete(l)
    for lb in label.all
        label.delete(lb)
 
    // past zones (underneath everything)
    if showHist
        if htfOk and (showHFvg or showHIfvg)
            f_drawHist(htfHist, true, colHBull, colHBear, colHBull, colHBear)
        if showFvg or showIfvg
            f_drawHist(ltfHist, false, colBull, colBear, colIBull, colIBear)
 
    // HTF first (drawn underneath), then chart timeframe
    if htfOk
        if showHFvg
            f_drawSet(htfZones, false, true, colHBull, colHBear, colHBull, colHBear, htfTxt)
        if showHIfvg
            f_drawSet(htfZones, true, true, colHBull, colHBear, colHBull, colHBear, htfTxt)
    if showFvg
        f_drawSet(ltfZones, false, false, colBull, colBear, colIBull, colIBear, ltfTxt)
    if showIfvg
        f_drawSet(ltfZones, true, false, colBull, colBear, colIBull, colIBear, ltfTxt)
 
    // signal markers
    int nS = sigLog.size()
    if showMarks and not marksActive and nS > 0
        for k = math.max(0, nS - maxMarks) to nS - 1
            f_mark(sigLog.get(k))
 
    //─────────────────────────────────────────────────────────────────────────
    // INFO TABLE
    //─────────────────────────────────────────────────────────────────────────
    if showTable
        if na(tbl)
            string tp = switch tablePos
                "Top Left"    => position.top_left
                "Top Right"   => position.top_right
                "Bottom Left" => position.bottom_left
                =>               position.bottom_right
            tbl := table.new(tp, 3, 10, bgcolor = color.new(#0B0F19, 10),
                 frame_color = color.new(#334155, 20), frame_width = 1,
                 border_color = color.new(#1E293B, 0), border_width = 1)
 
        string ts = switch tableSzIn
            "Tiny"  => size.tiny
            "Small" => size.small
            "Large" => size.large
            "Huge"  => size.huge
            =>         size.normal
        color cHead = #94A3B8
        color cText = #E2E8F0
        bool  htfWanted = showHFvg or showHIfvg
        int   r = 0
 
        // title
        table.cell(tbl, 0, r, "SMART GAPS PRO", text_color = cText, text_size = ts, text_halign = text.align_left)
        table.merge_cells(tbl, 0, r, 2, r)
        r += 1
 
        // column header
        table.cell(tbl, 0, r, f_t("Active zones", "Aktif bölgeler"), text_color = cHead, text_size = ts, text_halign = text.align_left)
        table.cell(tbl, 1, r, "▲", text_color = cHead, text_size = ts)
        table.cell(tbl, 2, r, "▼", text_color = cHead, text_size = ts)
        r += 1
 
        // zone rows — only the enabled types
        if showFvg
            table.cell(tbl, 0, r, "FVG · " + ltfTxt, text_color = cText, text_size = ts, text_halign = text.align_left)
            table.cell(tbl, 1, r, str.tostring(f_count(ltfZones, false, 1)), text_color = colBull, text_size = ts)
            table.cell(tbl, 2, r, str.tostring(f_count(ltfZones, false, -1)), text_color = colBear, text_size = ts)
            r += 1
        if showIfvg
            table.cell(tbl, 0, r, "IFVG · " + ltfTxt, text_color = cText, text_size = ts, text_halign = text.align_left)
            table.cell(tbl, 1, r, str.tostring(f_count(ltfZones, true, 1)), text_color = colIBull, text_size = ts)
            table.cell(tbl, 2, r, str.tostring(f_count(ltfZones, true, -1)), text_color = colIBear, text_size = ts)
            r += 1
        if showHFvg
            table.cell(tbl, 0, r, "HTF FVG · " + htfTxt, text_color = cText, text_size = ts, text_halign = text.align_left)
            table.cell(tbl, 1, r, htfOk ? str.tostring(f_count(htfZones, false, 1)) : "–", text_color = colHBull, text_size = ts)
            table.cell(tbl, 2, r, htfOk ? str.tostring(f_count(htfZones, false, -1)) : "–", text_color = colHBear, text_size = ts)
            r += 1
        if showHIfvg
            table.cell(tbl, 0, r, "HTF IFVG · " + htfTxt, text_color = cText, text_size = ts, text_halign = text.align_left)
            table.cell(tbl, 1, r, htfOk ? str.tostring(f_count(htfZones, true, 1)) : "–", text_color = colHBull, text_size = ts)
            table.cell(tbl, 2, r, htfOk ? str.tostring(f_count(htfZones, true, -1)) : "–", text_color = colHBear, text_size = ts)
            r += 1
 
        // HTF settings in use
        if htfWanted
            string hInfo = htfTxt + " · " + (htfMode == "Auto" ? f_t("Auto", "Otomatik") : f_t("Manual", "Manuel")) + " · " + f_t("break: ", "kırılım: ") + (htfByHtf ? f_t("HTF close", "HTF kapanış") : f_t("chart close", "grafik kapanış"))
            table.cell(tbl, 0, r, "HTF", text_color = cHead, text_size = ts, text_halign = text.align_left)
            table.cell(tbl, 1, r, hInfo, text_color = htfOk ? cText : cHead, text_size = ts)
            table.merge_cells(tbl, 1, r, 2, r)
            r += 1
 
        // signal bias (same state that colors the candles)
        string bTxt = bias == 1 ? "▲ " + f_t("Bullish", "Boğa") : bias == -1 ? "▼ " + f_t("Bearish", "Ayı") : "—"
        color  bCol = bias == 1 ? colBull : bias == -1 ? colBear : cHead
        table.cell(tbl, 0, r, f_t("Bias", "Yön"), text_color = cHead, text_size = ts, text_halign = text.align_left)
        table.cell(tbl, 1, r, bTxt, text_color = bCol, text_size = ts)
        table.merge_cells(tbl, 1, r, 2, r)
        r += 1
 
        // last signal (persistent)
        string lsTxt = "—"
        color  lsCol = cHead
        if nS > 0
            Sig ls  = sigLog.last()
            int ago = bar_index - ls.bi
            lsTxt := (ls.dir == 1 ? "▲ " + f_t("BUY", "AL") : "▼ " + f_t("SELL", "SAT")) + " · " + (ls.htf ? "HTF " : "") + ls.kind + " " + ls.tf + " · " + (ago == 0 ? f_t("this bar", "bu bar") : str.tostring(ago) + f_t(ago == 1 ? " bar ago" : " bars ago", " bar önce"))
            lsCol := ls.htf ? (ls.dir == 1 ? colHBull : colHBear) : ls.kind == "IFVG" ? (ls.dir == 1 ? colIBull : colIBear) : (ls.dir == 1 ? colBull : colBear)
        table.cell(tbl, 0, r, f_t("Last signal", "Son sinyal"), text_color = cHead, text_size = ts, text_halign = text.align_left)
        table.cell(tbl, 1, r, lsTxt, text_color = lsCol, text_size = ts)
        table.merge_cells(tbl, 1, r, 2, r)
        r += 1
 
        // HTF warning — row exists only when needed
        if htfWanted and not htfOk
            table.cell(tbl, 0, r, f_t("⚠ HTF (" + htfTxt + ") must be higher than chart TF — HTF disabled", "⚠ HTF (" + htfTxt + ") grafik TF'inden büyük olmalı — HTF kapalı"),
                 text_color = #FBBF24, text_size = ts, text_halign = text.align_left)
            table.merge_cells(tbl, 0, r, 2, r)
 
//═════════════════════════════════════════════════════════════════════════════
// ALERTS
//═════════════════════════════════════════════════════════════════════════════
// 1) "Any alert() function call" — dynamic messages with zone details (filtered by the Alerts inputs)
if alertBuf.size() > 0
    string m = useJson ? (alertBuf.size() == 1 ? alertBuf.get(0) : "[" + alertBuf.join(",") + "]") : alertBuf.join("\n")
    alert(m, confirmOnly ? alert.freq_once_per_bar_close : alert.freq_once_per_bar)
 
// 2) Classic alert conditions (selectable one by one in the alert dialog)
 
// plotcandle (not barcolor) so that body, border AND wick take the bias color
bool  paint    = colorBars and bias != 0
color biasCol  = bias == 1 ? colBull : colBear
plotcandle(paint ? open : na, paint ? high : na, paint ? low : na, paint ? close : na, title = "Signal Bias Candles",
     color = biasCol, wickcolor = biasCol, bordercolor = biasCol, display = display.pane, editable = false)
 
alertcondition(anyBuy,     "Any Buy Signal",     "Smart Gaps Pro | BUY | {{ticker}} {{interval}} | price {{close}}")
alertcondition(anySell,    "Any Sell Signal",     "Smart Gaps Pro | SELL | {{ticker}} {{interval}} | price {{close}}")
alertcondition(sFvgBuy,    "FVG Buy",             "Smart Gaps Pro | BUY | FVG retest | {{ticker}} {{interval}} | price {{close}}")
alertcondition(sFvgSell,   "FVG Sell",            "Smart Gaps Pro | SELL | FVG retest | {{ticker}} {{interval}} | price {{close}}")
alertcondition(sIfvgBuy,   "IFVG Buy",            "Smart Gaps Pro | BUY | IFVG retest | {{ticker}} {{interval}} | price {{close}}")
alertcondition(sIfvgSell,  "IFVG Sell",           "Smart Gaps Pro | SELL | IFVG retest | {{ticker}} {{interval}} | price {{close}}")
alertcondition(sHFvgBuy,   "HTF FVG Buy",         "Smart Gaps Pro | BUY | HTF FVG retest | {{ticker}} {{interval}} | price {{close}}")
alertcondition(sHFvgSell,  "HTF FVG Sell",        "Smart Gaps Pro | SELL | HTF FVG retest | {{ticker}} {{interval}} | price {{close}}")
alertcondition(sHIfvgBuy,  "HTF IFVG Buy",        "Smart Gaps Pro | BUY | HTF IFVG retest | {{ticker}} {{interval}} | price {{close}}")
alertcondition(sHIfvgSell, "HTF IFVG Sell",       "Smart Gaps Pro | SELL | HTF IFVG retest | {{ticker}} {{interval}} | price {{close}}")
alertcondition(bullGap or hBullGap, "New Bullish FVG", "Smart Gaps Pro | New bullish FVG | {{ticker}} {{interval}} | price {{close}}")
alertcondition(bearGap or hBearGap, "New Bearish FVG", "Smart Gaps Pro | New bearish FVG | {{ticker}} {{interval}} | price {{close}}")
alertcondition(evInv or evHInv,     "FVG → IFVG Inversion", "Smart Gaps Pro | FVG inverted to IFVG | {{ticker}} {{interval}} | price {{close}}")

← 返回列表