本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ezfied
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ZEIFVG – HTF FVG + inversion fair value gap (iFVG)
//
// 1. Price taps a higher-timeframe FVG (chosen timeframe and anything above it).
// 2. On the move into it, a 3-candle FVG forms on the chart timeframe.
// 3. A candle BODY closes back through that gap = inversion (wicks never count).
// 4. Confirmed when the next candle leaves the gap open. Box drawn on the gap.
// Optional extras: liquidity sweep, trend filter, trading times, alerts.
//@version=6
indicator("ZEIFVG", shorttitle = "ZEIFVG", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// INPUTS
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
string G_FVG = "1 · FVG detection"
float minGapATR = 0.05
int minGapTicks = 1
int maxAge = 60
int maxTracked = 30
string mergeMode = "Keep separate"
int mergeTol = 2
string qualifyMode = "Any active FVG"
string stackZone = "Union"
bool killWeak = true
bool showRaw = true
string cleanMode = input.string("Off", "Gap must stay clean until it is inverted", options = ["Off", "No more than half filled", "Wicks only, no bodies"], group = "1 · Setup", tooltip = "Off (recommended): price may trade back into the gap, wicks or bodies, before the candle that closes through it. Retraces into the gap only lower its grade.\nNo more than half filled: the gap is dropped once price has filled more than half of it.\nWicks only: the gap is also dropped if any candle body closes inside it.")
float maxFill = 50
bool useImpl = input.bool(false, "Include implied gaps (wicks overlap slightly)", group = "1 · Setup", tooltip = "Off: only true 3-candle gaps count (wicks of candle 1 and 3 do not touch).\nOn: also counts gaps where those wicks overlap a little but the bodies leave clear space.")
float implTol = 25
string velMode = "Grade only"
float velMult = 1.3
float velBody = 50
string minGapGr = input.string("D", "Minimum gap grade", options = ["A+", "A", "B", "C", "D"], group = "1 · Setup", tooltip = "Gap grade out of 6: wicks at formation, stayed empty, speed of the candle that left it. D = show everything.")
float wickMax = 100
bool showGapGr = true
string G_INV = "2 · Inversion & risk"
string dispMode = input.string("Off", "Inversion candle must show displacement", options = ["Off", "Auto (calibrated on chart)", "Dhesi strict"], group = "1 · Setup", tooltip = "Off: any body close through the gap counts (anatomy only).\nAuto: the inversion impulse must beat the median of recent inversions on this chart.\nStrict: body >= 70% of range and range >= 1.5x the average candle.")
int dispWin = 3
float dispBodyMin = 70
float dispRngMult = 1.5
float dispAutoPct = 50
bool dispLog = true
string C_GAP = "Next candle closes and leaves the gap open"
string C_CLS = "Next candle closes beyond the gap"
string C_NOW = "Inversion candle close (no wait)"
string confMode = input.string(C_GAP, "Setup confirmed when", options = [C_GAP, C_CLS], group = "1 · Setup", tooltip = "The setup is only drawn after the candle that follows the inversion candle has closed.\nLeaves the gap open: that candle must not trade back through the space, so a real gap is left (strict, recommended).\nCloses beyond: it only has to close beyond the old gap.")
int atrLen = 14
string slMode = "Leg extreme"
int slBuf = 2
bool obRule = false
float closeMgn = 0
int maxInvN = input.int(0, "Inversion within N candles of the gap (0 = no limit)", minval = 0, group = "1 · Setup", tooltip = "How quickly the gap must be inverted. 0 = any time while the gap is still alive (up to 60 candles). Example: 10 = the close through the gap must come within 10 candles of the gap forming.")
int ifvgLife = 0
string G_CTX = "3 · Confluence filters"
string htfMode = input.string("Required", "HTF FVG tap", options = ["Required", "Off"], group = "2 · Filters", tooltip = "Required: the move that makes the gap must be inside a higher-timeframe FVG.")
string sweepMode = input.string("Off", "Liquidity sweep", options = ["Off", "Required"], group = "2 · Filters", tooltip = "Required: a high or low must also be swept on the move that makes the gap.")
string smtMode = "Off"
int ctxLook = 40
int sweepLegN = 10
float htfTol = 0
string minHtf = input.string("5m", "Smallest HTF timeframe that counts (and anything higher)", options = ["5m", "15m", "30m", "1H", "4H", "D", "W", "M"], group = "2 · Filters", tooltip = "HTF arrays are taken from this timeframe and every timeframe above it. Only timeframes HIGHER than the chart are ever used, so on a 15m chart a 5m setting behaves like 30m and up.")
bool htfEnter = input.bool(true, "Price must be in the HTF array on the move that leaves the gap", group = "2 · Filters", tooltip = "On: price must be trading inside the HTF box on the same move that makes the small gap.\nOff: a touch of the HTF box any time in the last 40 candles is enough.")
bool showFilt = false
string G_TRD = "3b · Trend & signal filters"
string sigSide = input.string("Both", "Signal direction", options = ["Both", "Longs only", "Shorts only"], group = "2 · Filters", tooltip = "Show both directions, only bullish setups (longs) or only bearish setups (shorts).")
string trendMode = input.string("Off", "Trend filter (CISD)", options = ["Off", "Only WITH trend", "Only AGAINST trend (reversals)"], group = "2 · Filters", tooltip = "Off: trend is ignored.\nOnly WITH trend: setups must agree with the higher-timeframe trend.\nOnly AGAINST trend: reversal setups only.\nTrend = last change in state of delivery on 15m (1m chart) or 1H (5m chart).")
string trendSrc = "HTF CISD (fadi-style)"
string trendTFi = "Auto (1m→15m, 5m→1H)"
bool showBias = false
string biasPos = "Bottom Left"
int structLen = 5
string S_ANY = "Any time"
string S_KZ = "Kill zones (09:30-11:00 and 13:20-14:00)"
string S_LDN = "London session (03:00-08:00)"
string S_NY = "New York session (09:30-16:00)"
string S_LNY = "London + New York"
string S_CUS = "Custom window"
string sessMode = input.string(S_ANY, "Trading times (New York time)", options = [S_ANY, S_KZ, S_LDN, S_NY, S_LNY, S_CUS], group = "3 · Times", tooltip = "When setups / alerts are allowed. All times are New York time.\nKill zones = 09:30-11:00 and 13:20-14:00. Custom window uses the times in the box below.")
string sessCus = input.session("0930-1100", "Custom window", group = "3 · Times", tooltip = "Only used when Trading times is set to Custom window. New York time.")
string sessScope = input.string("Setups and alerts", "Times apply to", options = ["Setups and alerts", "Alerts only"], group = "3 · Times", tooltip = "Alerts only: every setup is still drawn, but alerts only go out inside the chosen times.")
bool useKz = sessMode != S_ANY and sessScope == "Setups and alerts"
string kzSess1 = "0930-1100"
string kzSess2 = "1320-1400"
bool useKz3 = false
string kzSess3 = "0200-0500"
bool showTrendBg = false
string A_CONF = "Confirmed setup"
string A_EARLY = "Inversion candle close (early heads-up)"
string A_BOTH = "Both"
bool alertOn = input.bool(true, "Alerts on", group = "4 · Alerts", tooltip = "Create the alert once in TradingView: Alert -> Condition: ZEIFVG -> Any alert() function call. App push, email, sound or webhook is chosen in that window under Notifications.")
string alertWhen = input.string(A_CONF, "Alert me on", options = [A_CONF, A_EARLY, A_BOTH], group = "4 · Alerts", tooltip = "Confirmed setup: alert when the box is drawn.\nInversion candle close: an earlier heads-up, one candle before confirmation (it can still fail).\nBoth: you get the two alerts.")
string alertFmt = input.string("Short", "Alert message", options = ["Short", "Full details", "JSON (for webhooks)"], group = "4 · Alerts", tooltip = "Short: one line (direction, symbol, price, HTF box, grade).\nFull details: adds gap and inversion times and prices.\nJSON: machine-readable text for webhooks / bots.")
bool dbgLog = input.bool(false, "Diagnostics: log why candidates were rejected (Pine Logs)", group = "5 · Display", tooltip = "For checking only. Writes to Pine Logs every gap that was closed through and which rule stopped it from showing. Leave off normally.")
string G_HTF = "4 · HTF PD arrays"
int minHtfSec = minHtf == "5m" ? 300 : minHtf == "15m" ? 900 : minHtf == "30m" ? 1800 : minHtf == "1H" ? 3600 : minHtf == "4H" ? 14400 : minHtf == "D" ? 86400 : minHtf == "W" ? 604800 : 2592000
hOn(string tf) => timeframe.in_seconds(tf) >= minHtfSec
string h1TF = "60"
bool h1On = hOn(h1TF)
string h2TF = "240"
bool h2On = hOn(h2TF)
string h3TF = "D"
bool h3On = hOn(h3TF)
string h4TF = "W"
bool h4On = hOn(h4TF)
string h0TF = "15"
bool h0On = hOn(h0TF)
string h5TF = "5"
bool h5On = hOn(h5TF)
string h6TF = "30"
bool h6On = hOn(h6TF)
bool useHFvg = true
bool useHOb = input.bool(true, "Also count HTF order blocks", group = "2 · Filters", tooltip = "On: a higher-timeframe order block counts the same as an HTF FVG.\nOff: HTF FVGs only.\nOrder block = the last opposite candle before a candle that closes beyond it, on the HTF.")
int htfMax = 40
bool showHtf = true
string G_LIQ = "5 · Liquidity levels"
bool usePD = true
bool usePW = true
bool useAs = true
string asSess = "2000-0000"
bool useLo = true
string loSess = "0200-0500"
bool useNy = true
string nySess = "0930-1130"
string tz = "America/New_York"
bool useEq = true
int eqTol = 4
int pivLen = 3
bool useSw = true
int swLen = 3
int liqMax = 100
bool useSwH = true
string swTf1 = "5"
string swTf2 = "15"
int swHLen = 3
bool showLiq = true
string G_SMT = "6 · SMT divergence"
string smtSymIn = ""
string smtType = "Either"
string smtSym2In = ""
int smtWin = 20
int smtPiv = 3
string smtDepthI = "Medium"
int smtDepth = smtDepthI == "Small" ? 5 : smtDepthI == "Large" ? 30 : 15
bool showSmt = true
bool showSmtLn = true
int smtMaxN = 5
bool smtDelInv = true
int smtLnW = 1
color cSmtBu = color.rgb(0, 128, 0)
color cSmtBe = color.rgb(204, 0, 0)
string G_VIS = "7 · Display"
color cBull = input.color(color.new(#089981, 75), "Bullish iFVG", inline = "c1", group = "5 · Display")
color cBear = input.color(color.new(#F23645, 75), "Bearish iFVG", inline = "c1", group = "5 · Display", tooltip = "Box colours for bullish and bearish setups.")
color cRawBu = color.new(#089981, 92)
color cRawBe = color.new(#F23645, 92)
color cHtfBu = color.new(#2962FF, 90)
color cHtfBe = color.new(#FF9800, 90)
bool showTbl = true
string tblPos = "Top Right"
string G_Q = "8 · Inversion quality grading (A+ → F)"
string dispStyle = "Clean graded boxes"
string minGrade = "F (invalid)"
int spd3 = 3
int spd2 = 8
int spd1 = 20
float rr3 = 0.25
float rr2 = 0.6
float rr1 = 1.0
string G_TFV = "9 · iFVG timeframe & box"
string ifvgTF = "1m and 5m"
int bdrW = 1
int bdrT = 0
int showN = input.int(20, "Number of past setups to show", minval = 1, maxval = 50, group = "5 · Display", tooltip = "How many of the most recent setups stay drawn on the chart (1-50). Older ones are removed.")
bool showTap = input.bool(true, "Show the HTF array that was tapped (grey box)", group = "5 · Display", tooltip = "Draws the higher-timeframe FVG / order block that price traded into as a grey box, with its name and timeframe written inside.")
bool showBT = false
float btRR = 2.0
bool showTapTxt = true
color cTap = color.new(color.gray, 85)
int chartSec = timeframe.in_seconds()
bool tfOk = true
bool clean = dispStyle == "Clean graded boxes"
bool showRawE = showRaw and not clean and tfOk
bool showLiqE = showLiq and not clean and tfOk
bool showHtfE = showHtf and not clean and tfOk
bool showSmtE = showSmt and not clean and tfOk
bool showTblE = showTbl and not clean and tfOk
bool useDispE = dispMode != "Off"
bool killWeakE = killWeak
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// TYPES
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
type FVG
float top
float bot
int dir // 1 = bullish FVG (gap up), -1 = bearish FVG (gap down)
int c1Bar
int c1Time
int c3Bar
float legExt // extreme since formation (lowest low for bearish FVG, highest high for bullish)
int parts = 1 // number of gaps merged into this block
box bx
int legBar = na // bar of that extreme (for inversion speed)
float cTop = na // remaining clean (unfilled) part of the gap
float cBot = na
bool bodyIn = false
bool impl = false // implied gap (wicks overlap)
float wickSh = 0.0 // share of the body-to-body space taken by C1/C3 wicks at formation
float vRm = 0.0 // candle 2 range / avg range
float vBr = 0.0 // candle 2 body / range
float obExt = na // candle 1 extreme when candle 1 is an opposite-colour candle (order block stacked with the gap)
type Zone
float top
float bot
int dir
string name
box bx
int leftT = na
bool flipped = false
int tfS = 0
type Liq
float price
bool isHigh
string name
int bornBar
bool swept = false
line ln
label lb
type Sig
float top
float bot
float sl
int dir
int bornBar
box bx
line slLn
bool live = true
label lb
label lb2
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// HELPERS
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
float atr = ta.atr(atrLen)
float tick = syminfo.mintick
float minGap = math.max(minGapATR * nz(atr), minGapTicks * tick)
fmtT(int t) => str.format_time(t, "yyyy-MM-dd HH:mm", tz)
px(float p) => str.tostring(p, format.mintick)
within(int lastBar) => not na(lastBar) and bar_index - lastBar <= ctxLook
tfLabel(string tf) =>
int s = timeframe.in_seconds(tf)
s >= 2419200 ? "M" : s >= 604800 ? "W" : s >= 86400 ? "D" : s >= 3600 ? str.tostring(s / 3600) + "H" : str.tostring(s / 60) + "m"
// Displacement impulse: up to dispWin consecutive candles in direction d ending on this bar
float rngAvg = ta.sma(high - low, 14)
float c2RngN = nz(rngAvg[2]) // average candle range BEFORE candle 2 (velocity reference)
impulse(int d) =>
int n = 0
float hh = na
float ll = na
float bodySum = 0.0
for k = 0 to dispWin - 1
bool same = d == 1 ? close[k] > open[k] : close[k] < open[k]
if not same
break
n += 1
hh := na(hh) ? high[k] : math.max(hh, high[k])
ll := na(ll) ? low[k] : math.min(ll, low[k])
bodySum += math.abs(close[k] - open[k])
float rng = n > 0 ? hh - ll : 0.0
float base = nz(rngAvg[math.max(n, 1)], nz(rngAvg, rng))
float br = rng > 0 ? bodySum / rng : 0.0
float rm = base > 0 ? rng / base : 0.0
[n, br, rm, br * rm]
[impNU, impBRU, impRMU, impSCU] = impulse(1)
[impND, impBRD, impRMD, impSCD] = impulse(-1)
var array<float> dispCand = array.new<float>() // scores of every body close through an opposing FVG
float dispThr = dispCand.size() >= 20 ? dispCand.percentile_linear_interpolation(dispAutoPct) : na
dispOk(int d) =>
int n = d == 1 ? impNU : impND
float br = d == 1 ? impBRU : impBRD
float rm = d == 1 ? impRMU : impRMD
float sc = d == 1 ? impSCU : impSCD
bool strict = br >= 0.70 and rm >= 1.5
n == 0 ? false : dispMode == "Off" ? true : dispMode == "Dhesi strict" ? strict : dispMode == "Custom" ? (br * 100 >= dispBodyMin and rm >= dispRngMult) : (na(dispThr) ? strict : sc >= dispThr)
dirOk(int d) => d == 1 ? close > open : close < open
gradeRank(string g) => g == "A+" ? 7 : g == "A" ? 6 : g == "A-" ? 5 : g == "B+" ? 4 : g == "B" ? 3 : g == "B-" ? 2 : g == "C" ? 1 : 0
int minRank = gradeRank(minGrade == "F (invalid)" ? "F" : minGrade)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// LIQUIDITY LEVELS & SWEEPS
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
var array<Liq> liqs = array.new<Liq>()
var int lastSSL = na // last sell-side (low) sweep bar -> bullish context
var int lastBSL = na // last buy-side (high) sweep bar -> bearish context
var string lastSSLName = ""
var string lastBSLName = ""
addLiq(array<Liq> arr, float p, bool hi, string nm, int born) =>
if not na(p)
Liq l = Liq.new(p, hi, nm, born)
if showLiqE
color c = hi ? color.new(#F23645, 40) : color.new(#089981, 40)
l.ln := line.new(born, p, bar_index, p, color = c, style = line.style_dotted, width = 1)
l.lb := label.new(bar_index, p, nm, style = label.style_none, textcolor = c, size = size.tiny)
arr.push(l)
if arr.size() > liqMax
Liq o = arr.shift()
line.delete(o.ln)
label.delete(o.lb)
sessHL(string sess) =>
bool inS = not na(time(timeframe.period, sess, tz))
var float h = na
var float l = na
var int sb = na
if inS and not inS[1]
h := high
l := low
sb := bar_index
else if inS
h := math.max(h, high)
l := math.min(l, low)
bool ended = not inS and inS[1]
[ended, h, l, sb]
bool intraday = timeframe.in_seconds() < 86400
[pdh, pdl] = request.security(syminfo.tickerid, "D", [high[1], low[1]], lookahead = barmerge.lookahead_on)
[pwh, pwl] = request.security(syminfo.tickerid, "W", [high[1], low[1]], lookahead = barmerge.lookahead_on)
if intraday and usePD and timeframe.change("D")
addLiq(liqs, pdh, true, "PDH", bar_index)
addLiq(liqs, pdl, false, "PDL", bar_index)
if usePW and timeframe.change("W") and timeframe.in_seconds() < 604800
addLiq(liqs, pwh, true, "PWH", bar_index)
addLiq(liqs, pwl, false, "PWL", bar_index)
[p1h, p1l] = request.security(syminfo.tickerid, "60", [high[1], low[1]], lookahead = barmerge.lookahead_on)
[p4h, p4l] = request.security(syminfo.tickerid, "240", [high[1], low[1]], lookahead = barmerge.lookahead_on)
if timeframe.in_seconds() < 3600 and timeframe.change("60")
addLiq(liqs, p1h, true, "1H High", bar_index)
addLiq(liqs, p1l, false, "1H Low", bar_index)
if timeframe.in_seconds() < 14400 and timeframe.change("240")
addLiq(liqs, p4h, true, "4H High", bar_index)
addLiq(liqs, p4l, false, "4H Low", bar_index)
[asEnd, asH, asL, asB] = sessHL(asSess)
[loEnd, loH, loL, loB] = sessHL(loSess)
[nyEnd, nyH, nyL, nyB] = sessHL(nySess)
if intraday and useAs and asEnd
addLiq(liqs, asH, true, "Asia H", asB)
addLiq(liqs, asL, false, "Asia L", asB)
if intraday and useLo and loEnd
addLiq(liqs, loH, true, "London H", loB)
addLiq(liqs, loL, false, "London L", loB)
if intraday and useNy and nyEnd
addLiq(liqs, nyH, true, "NY AM H", nyB)
addLiq(liqs, nyL, false, "NY AM L", nyB)
// Equal highs / lows
float ph = ta.pivothigh(high, pivLen, pivLen)
float pl = ta.pivotlow(low, pivLen, pivLen)
var float lastPH = na
var int lastPHBar = na
var float lastPL = na
var int lastPLBar = na
if not na(ph)
if useEq and not na(lastPH) and math.abs(ph - lastPH) <= eqTol * tick
addLiq(liqs, math.max(ph, lastPH), true, "EQH", lastPHBar)
lastPH := ph
lastPHBar := bar_index - pivLen
if not na(pl)
if useEq and not na(lastPL) and math.abs(pl - lastPL) <= eqTol * tick
addLiq(liqs, math.min(pl, lastPL), false, "EQL", lastPLBar)
lastPL := pl
lastPLBar := bar_index - pivLen
// Internal liquidity: previous swing highs / lows
float swH = ta.pivothigh(high, swLen, swLen)
float swL = ta.pivotlow(low, swLen, swLen)
if useSw and not na(swH)
addLiq(liqs, swH, true, "Swing H", bar_index - swLen)
if useSw and not na(swL)
addLiq(liqs, swL, false, "Swing L", bar_index - swLen)
// Short-term swing highs / lows from timeframes above the chart (confirmed HTF candles only)
htfSw(string tf) =>
request.security(syminfo.tickerid, tf, [ta.pivothigh(high, swHLen, swHLen)[1], ta.pivotlow(low, swHLen, swHLen)[1]], lookahead = barmerge.lookahead_on)
[swH1, swL1] = htfSw(swTf1)
[swH2, swL2] = htfSw(swTf2)
if useSwH and timeframe.in_seconds(swTf1) > timeframe.in_seconds() and timeframe.change(swTf1)
if not na(swH1)
addLiq(liqs, swH1, true, tfLabel(swTf1) + " Swing H", bar_index)
if not na(swL1)
addLiq(liqs, swL1, false, tfLabel(swTf1) + " Swing L", bar_index)
if useSwH and timeframe.in_seconds(swTf2) > timeframe.in_seconds() and timeframe.change(swTf2)
if not na(swH2)
addLiq(liqs, swH2, true, tfLabel(swTf2) + " Swing H", bar_index)
if not na(swL2)
addLiq(liqs, swL2, false, tfLabel(swTf2) + " Swing L", bar_index)
// Sweep detection
bool bslNow = false // a buy-side level was taken on THIS bar
bool sslNow = false // a sell-side level was taken on THIS bar
if liqs.size() > 0
for i = 0 to liqs.size() - 1
Liq l = liqs.get(i)
if not l.swept
bool hit = l.isHigh ? high > l.price : low < l.price
if hit
l.swept := true
if l.isHigh
lastBSL := bar_index
bslNow := bslNow or not str.contains(l.name, "Swing")
lastBSLName := l.name
else
lastSSL := bar_index
sslNow := sslNow or not str.contains(l.name, "Swing")
lastSSLName := l.name
if showLiqE and not na(l.ln)
l.ln.set_x2(bar_index)
l.lb.set_x(bar_index)
if hit
l.ln.set_style(line.style_dashed)
l.lb.set_text(l.name + " ✕")
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// short-term liquidity: the leg takes out the low / high of the last 8 candles
float stLo = ta.lowest(low, 8)[1]
float stHi = ta.highest(high, 8)[1]
if low < stLo and lastSSL != bar_index
lastSSL := bar_index
lastSSLName := "Short-term low"
if high > stHi and lastBSL != bar_index
lastBSL := bar_index
lastBSLName := "Short-term high"
// HTF PD ARRAYS (FVGs + order blocks) – confirmed HTF candles only, no repaint
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
var array<Zone> zones = array.new<Zone>()
var int lastBullTap = na
var int lastBearTap = na
var int lastBullEnt = na // bar on which price ENTERED a bullish array from above
var int lastBearEnt = na // bar on which price ENTERED a bearish array from below
var string lastBullTapName = ""
var string lastBearTapName = ""
var float bullTapT = na
var float bullTapB = na
var int bullTapL = na
var float bearTapT = na
var float bearTapB = na
var int bearTapL = na
htfReq(string tf) =>
request.security(syminfo.tickerid, tf, [high[3] < low[1], high[3], low[1], low[3] > high[1], high[1], low[3], close[1] > high[2] and close[2] < open[2], close[1] < low[2] and close[2] > open[2], low[2], high[2], time[3], time[2], time[1]], lookahead = barmerge.lookahead_on)
addZone(array<Zone> zs, float t, float b, int d, string nm, int leftT, int tfS) =>
Zone z = Zone.new(t, b, d, nm, na, leftT, false, tfS)
if showHtfE
z.bx := box.new(leftT, t, time, b, xloc = xloc.bar_time, extend = extend.right, border_color = na, bgcolor = d == 1 ? cHtfBu : cHtfBe, text = nm, text_size = size.tiny, text_color = color.gray, text_halign = text.align_right, text_valign = text.align_center)
zs.push(z)
if zs.size() > htfMax
Zone o = zs.shift()
box.delete(o.bx)
procHTF(array<Zone> zs, bool on, string tf, bool buF, float buB, float buT, bool beF, float beB, float beT, bool obU, bool obD, float obL, float obH, int t3, int t2, int t1) =>
bool valid = on and timeframe.in_seconds(tf) > timeframe.in_seconds(timeframe.period)
bool isNew = t1 != t1[1]
if valid and isNew
string n = tfLabel(tf)
if useHFvg and buF
addZone(zs, buT, buB, 1, "HTF FVG " + n, t3, timeframe.in_seconds(tf))
if useHFvg and beF
addZone(zs, beT, beB, -1, "HTF FVG " + n, t3, timeframe.in_seconds(tf))
if useHOb and obU
addZone(zs, obH, obL, 1, "HTF OB " + n, t2, timeframe.in_seconds(tf))
if useHOb and obD
addZone(zs, obH, obL, -1, "HTF OB " + n, t2, timeframe.in_seconds(tf))
[a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13] = htfReq(h1TF)
[b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13] = htfReq(h2TF)
[c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13] = htfReq(h3TF)
[d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13] = htfReq(h4TF)
[e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13] = htfReq(h0TF)
procHTF(zones, h1On and htfMode != "Off", h1TF, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13)
procHTF(zones, h2On and htfMode != "Off", h2TF, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13)
procHTF(zones, h3On and htfMode != "Off", h3TF, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13)
procHTF(zones, h4On and htfMode != "Off", h4TF, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13)
procHTF(zones, h0On and htfMode != "Off", h0TF, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13)
[f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13] = htfReq(h5TF)
[g1, g2, g3, g4, g5, g6, g7, g8, g9, g10, g11, g12, g13] = htfReq(h6TF)
procHTF(zones, h5On and htfMode != "Off", h5TF, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13)
procHTF(zones, h6On and htfMode != "Off", h6TF, g1, g2, g3, g4, g5, g6, g7, g8, g9, g10, g11, g12, g13)
[m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13] = htfReq("M")
procHTF(zones, htfMode != "Off", "M", m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13)
// Tap / invalidation (a body close through the far side kills the array)
int bestBu = -1
int bestBe = -1
if zones.size() > 0
for i = zones.size() - 1 to 0
Zone z = zones.get(i)
bool dead = z.dir == 1 ? close < z.bot : close > z.top
float tl = htfTol / 100 * (z.top - z.bot)
bool tap = z.dir == 1 ? (low <= z.top + tl and high >= z.bot) : (high >= z.bot - tl and low <= z.top)
if tap and z.dir == 1 and z.tfS > bestBu
bestBu := z.tfS
lastBullTap := bar_index
lastBullTapName := z.name
bullTapT := z.top
bullTapB := z.bot
bullTapL := z.leftT
if low[1] > z.top + tl
lastBullEnt := bar_index
if tap and z.dir == -1 and z.tfS > bestBe
bestBe := z.tfS
lastBearTap := bar_index
lastBearTapName := z.name
bearTapT := z.top
bearTapB := z.bot
bearTapL := z.leftT
if high[1] < z.bot - tl
lastBearEnt := bar_index
if dead and not z.flipped
z.flipped := true
z.dir := -z.dir
z.name := str.contains(z.name, "FVG") ? str.replace(z.name, "HTF FVG", "HTF iFVG") : str.replace(z.name, "HTF OB", "HTF breaker")
else if dead
box.delete(z.bx)
zones.remove(i)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// SMT DIVERGENCE
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
autoComp() =>
string r = syminfo.root
r == "NQ" ? "CME_MINI:ES1!" : r == "ES" ? "CME_MINI:NQ1!" : r == "MNQ" ? "CME_MINI:MES1!" : r == "MES" ? "CME_MINI:MNQ1!" : r == "YM" or r == "RTY" ? "CME_MINI:ES1!" : r == "MYM" or r == "M2K" ? "CME_MINI:MES1!" : ""
string compSym = smtSymIn != "" ? smtSymIn : autoComp()
bool smtAvail = smtMode != "Off" and compSym != ""
autoComp2() =>
string r = syminfo.root
r == "NQ" or r == "ES" ? "CBOT_MINI:YM1!" : r == "MNQ" or r == "MES" ? "CBOT_MINI:MYM1!" : ""
string compSym2 = str.lower(smtSym2In) == "off" ? "" : smtSym2In != "" ? smtSym2In : autoComp2()
bool smtAvail2 = smtAvail and compSym2 != ""
[cH, cL] = request.security(smtAvail ? compSym : syminfo.tickerid, timeframe.period, [high, low], ignore_invalid_symbol = true)
[cH2, cL2] = request.security(smtAvail2 ? compSym2 : syminfo.tickerid, timeframe.period, [high, low], ignore_invalid_symbol = true)
// SMT vs one correlated market.
// Rolling window: one market takes the N-bar extreme, the other fails to.
// Swing pivots: consecutive swing lows / highs disagree between the two markets.
smtCalc(float oH, float oL, bool on) =>
float loPrev = ta.lowest(low, smtWin)[1]
float hiPrev = ta.highest(high, smtWin)[1]
float oLoPrev = ta.lowest(oL, smtWin)[1]
float oHiPrev = ta.highest(oH, smtWin)[1]
bool rollBull = on and ((low < loPrev and oL >= oLoPrev) or (oL < oLoPrev and low >= loPrev))
bool rollBear = on and ((high > hiPrev and oH <= oHiPrev) or (oH > oHiPrev and high <= hiPrev))
float spl = ta.pivotlow(low, smtPiv, smtPiv)
float sph = ta.pivothigh(high, smtPiv, smtPiv)
float oLw = ta.lowest(oL, 2 * smtPiv + 1)
float oHw = ta.highest(oH, 2 * smtPiv + 1)
float lowD = low[2 * smtPiv + 1]
float highD = high[2 * smtPiv + 1]
float oLD = oL[2 * smtPiv + 1]
float oHD = oH[2 * smtPiv + 1]
// stored swing points ("logical levels"): price, other market's price, bar, and whether each was taken since
var array<float> lP = array.new<float>()
var array<float> lO = array.new<float>()
var array<int> lB = array.new<int>()
var array<float> lM = array.new<float>()
var array<float> lN = array.new<float>()
var array<float> hP = array.new<float>()
var array<float> hO = array.new<float>()
var array<int> hB = array.new<int>()
var array<float> hM = array.new<float>()
var array<float> hN = array.new<float>()
int curB = bar_index - smtPiv
if lP.size() > 0
for k = lP.size() - 1 to 0
if curB - smtPiv - 1 > lB.get(k)
lM.set(k, math.min(lM.get(k), nz(lowD, lM.get(k))))
lN.set(k, math.min(lN.get(k), nz(oLD, lN.get(k))))
if lM.get(k) < lP.get(k) or lN.get(k) < lO.get(k)
lP.remove(k)
lO.remove(k)
lB.remove(k)
lM.remove(k)
lN.remove(k)
if hP.size() > 0
for k = hP.size() - 1 to 0
if curB - smtPiv - 1 > hB.get(k)
hM.set(k, math.max(hM.get(k), nz(highD, hM.get(k))))
hN.set(k, math.max(hN.get(k), nz(oHD, hN.get(k))))
if hM.get(k) > hP.get(k) or hN.get(k) > hO.get(k)
hP.remove(k)
hO.remove(k)
hB.remove(k)
hM.remove(k)
hN.remove(k)
bool pivBull = false
bool pivBear = false
int bx1 = na
float by1 = na
int sx1 = na
float sy1 = na
if not na(spl)
if on and not na(oLw) and lP.size() > 0
for k = lP.size() - 1 to 0
float plv = lP.get(k)
float ol = lO.get(k)
bool mHeld = lM.get(k) >= plv
bool oHeld = lN.get(k) >= ol
bool sweepMain = spl < plv and oLw >= ol
bool sweepOther = spl >= plv and oLw < ol
if mHeld and oHeld and (sweepMain or sweepOther)
pivBull := true
bx1 := lB.get(k)
by1 := plv
break
lP.push(spl)
lO.push(nz(oLw, spl))
lB.push(curB)
lM.push(1e12)
lN.push(1e12)
while lP.size() > smtDepth
lP.shift()
lO.shift()
lB.shift()
lM.shift()
lN.shift()
if not na(sph)
if on and not na(oHw) and hP.size() > 0
for k = hP.size() - 1 to 0
float ph0 = hP.get(k)
float oh = hO.get(k)
bool mHeld = hM.get(k) <= ph0
bool oHeld = hN.get(k) <= oh
bool sweepMain = sph > ph0 and oHw <= oh
bool sweepOther = sph <= ph0 and oHw > oh
if mHeld and oHeld and (sweepMain or sweepOther)
pivBear := true
sx1 := hB.get(k)
sy1 := ph0
break
hP.push(sph)
hO.push(nz(oHw, sph))
hB.push(curB)
hM.push(-1e12)
hN.push(-1e12)
while hP.size() > smtDepth
hP.shift()
hO.shift()
hB.shift()
hM.shift()
hN.shift()
bool bull = smtType == "Swing pivots" ? pivBull : smtType == "Rolling window" ? rollBull : (pivBull or rollBull)
bool bear = smtType == "Swing pivots" ? pivBear : smtType == "Rolling window" ? rollBear : (pivBear or rollBear)
[bull, bear, pivBull, bx1, by1, pivBear, sx1, sy1]
[smtBullA, smtBearA, pbA, bxA, byA, psA, sxA, syA] = smtCalc(cH, cL, smtAvail)
[smtBullB, smtBearB, pbB, bxB, byB, psB, sxB, syB] = smtCalc(cH2, cL2, smtAvail2)
bool smtBull = smtBullA or smtBullB
bool smtBear = smtBearA or smtBearB
// fadi-style SMT link lines: one per pivot, capped count, removed once invalidated
type SmtLn
line ln
label lb
float lvl
int dir
var array<SmtLn> smtLns = array.new<SmtLn>()
float smtPL = ta.pivotlow(low, smtPiv, smtPiv)
float smtPH = ta.pivothigh(high, smtPiv, smtPiv)
shortSym(string t) =>
array<string> parts = str.split(t, ":")
string base = parts.size() > 1 ? parts.get(1) : t
str.replace(base, "1!", "")
addSmtLn(int x1, float y1, int x2, float y2, int d, string who) =>
if bar_index - x1 <= 500 and bar_index - x2 <= 500
color c = d == 1 ? cSmtBu : cSmtBe
line l = line.new(x1, y1, x2, y2, color = c, width = smtLnW)
label lb = label.new(int(math.round((x1 + x2) / 2)), (y1 + y2) / 2, who, style = d == 1 ? label.style_label_up : label.style_label_down, color = color.new(c, 100), textcolor = c, size = size.tiny, tooltip = "SMT vs " + who)
smtLns.push(SmtLn.new(l, lb, d == 1 ? math.min(y1, y2) : math.max(y1, y2), d))
if smtLns.size() > smtMaxN
SmtLn o = smtLns.shift()
line.delete(o.ln)
label.delete(o.lb)
if showSmtLn and tfOk and smtMode != "Off"
if smtDelInv and smtLns.size() > 0
for i = smtLns.size() - 1 to 0
SmtLn z = smtLns.get(i)
if (z.dir == 1 and low < z.lvl) or (z.dir == -1 and high > z.lvl)
line.delete(z.ln)
label.delete(z.lb)
smtLns.remove(i)
if pbA or pbB
addSmtLn(pbA ? bxA : bxB, pbA ? byA : byB, bar_index - smtPiv, smtPL, 1, pbA and pbB ? shortSym(compSym) + " " + shortSym(compSym2) : pbA ? shortSym(compSym) : shortSym(compSym2))
if psA or psB
addSmtLn(psA ? sxA : sxB, psA ? syA : syB, bar_index - smtPiv, smtPH, -1, psA and psB ? shortSym(compSym) + " " + shortSym(compSym2) : psA ? shortSym(compSym) : shortSym(compSym2))
// SMT swing: if price trades through it before the inversion, the setup is void
float smtLoRef = ta.lowest(low, smtPiv + 1)
float smtHiRef = ta.highest(high, smtPiv + 1)
var int lastBullSMT = na
var int lastBearSMT = na
var float bullSMTLow = na
var float bearSMTHigh = na
if not na(bullSMTLow) and low < bullSMTLow
lastBullSMT := na
bullSMTLow := na
if not na(bearSMTHigh) and high > bearSMTHigh
lastBearSMT := na
bearSMTHigh := na
if smtBull
lastBullSMT := bar_index
bullSMTLow := smtLoRef
if smtBear
lastBearSMT := bar_index
bearSMTHigh := smtHiRef
plotshape(showSmtE and smtBull, "Bullish SMT", shape.triangleup, location.belowbar, color.new(#2962FF, 30), size = size.tiny, text = "SMT", textcolor = color.new(#2962FF, 30))
plotshape(showSmtE and smtBear, "Bearish SMT", shape.triangledown, location.abovebar, color.new(#FF9800, 30), size = size.tiny, text = "SMT", textcolor = color.new(#FF9800, 30))
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// TREND & KILLZONE FILTERS
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Market structure: close beyond the last swing high = 1, beyond the last swing low = -1
msCalc(int len) =>
float sPH = ta.pivothigh(high, len, len)
float sPL = ta.pivotlow(low, len, len)
var float lastSH = na
var float lastSL = na
var int ms = 0
if not na(sPH)
lastSH := sPH
if not na(sPL)
lastSL := sPL
if not na(lastSH) and close > lastSH
ms := 1
lastSH := na
if not na(lastSL) and close < lastSL
ms := -1
lastSL := na
ms
// CISD trend (change in state of delivery), fadi-style:
// bullish = close above the OPEN of the down-candle series that made the leg low
// bearish = close below the OPEN of the up-candle series that made the leg high
cisdCalc() =>
var int tr = 0
var float serDn = na
var float serUp = na
var float legLo = na
var float legHi = na
var float bullLvl = na
var float bearLvl = na
bool up = close > open
bool dn = close < open
if dn and not (close[1] < open[1])
serDn := open
if up and not (close[1] > open[1])
serUp := open
if na(legLo) or low < legLo
legLo := low
if dn
bullLvl := serDn
if na(legHi) or high > legHi
legHi := high
if up
bearLvl := serUp
if tr != 1 and not na(bullLvl) and close > bullLvl
tr := 1
legHi := high
bearLvl := up ? serUp : na
else if tr != -1 and not na(bearLvl) and close < bearLvl
tr := -1
legLo := low
bullLvl := dn ? serDn : na
tr
string trendTF = trendTFi == "5m" ? "5" : trendTFi == "15m" ? "15" : trendTFi == "1H" ? "60" : trendTFi == "4H" ? "240" : trendTFi == "Daily" ? "D" : timeframe.in_seconds() <= 60 ? "15" : timeframe.in_seconds() <= 300 ? "60" : "240"
bool trendHigher = timeframe.in_seconds(trendTF) > timeframe.in_seconds(timeframe.period)
int msTrend = msCalc(structLen)
int htfMsRaw = request.security(syminfo.tickerid, trendTF, msCalc(structLen)[1], lookahead = barmerge.lookahead_on)
int htfTrend = trendHigher ? nz(htfMsRaw) : msTrend
int cisdRaw = request.security(syminfo.tickerid, trendTF, cisdCalc()[1], lookahead = barmerge.lookahead_on)
int cisdLocal = cisdCalc()
int cisdTrend = trendHigher ? nz(cisdRaw) : cisdLocal
// Bias table: CISD trend on each timeframe (closed candles only)
int bz5 = request.security(syminfo.tickerid, "5", cisdCalc()[1], lookahead = barmerge.lookahead_on)
int bz15 = request.security(syminfo.tickerid, "15", cisdCalc()[1], lookahead = barmerge.lookahead_on)
int bz60 = request.security(syminfo.tickerid, "60", cisdCalc()[1], lookahead = barmerge.lookahead_on)
int bz4h = request.security(syminfo.tickerid, "240", cisdCalc()[1], lookahead = barmerge.lookahead_on)
int bz1d = request.security(syminfo.tickerid, "D", cisdCalc()[1], lookahead = barmerge.lookahead_on)
float dOpen = request.security(syminfo.tickerid, "D", open, lookahead = barmerge.lookahead_on)
int doTrend = close > dOpen ? 1 : close < dOpen ? -1 : 0
int trend = trendSrc == "HTF CISD (fadi-style)" ? cisdTrend : trendSrc == "HTF structure" ? htfTrend : trendSrc == "Chart structure" ? msTrend : trendSrc == "Daily open" ? doTrend : (htfTrend == msTrend ? htfTrend : 0)
string trendTxt = trend == 1 ? "Up" : trend == -1 ? "Down" : "Neutral"
inS(string ss) => not na(time(timeframe.period, ss, tz))
bool inKz = sessMode == S_ANY ? true : sessMode == S_KZ ? (inS(kzSess1) or inS(kzSess2)) : sessMode == S_LDN ? inS("0300-0800") : sessMode == S_NY ? inS("0930-1600") : sessMode == S_LNY ? (inS("0300-0800") or inS("0930-1600")) : inS(sessCus)
trendOk(int d) =>
trendMode == "Off" ? true : trendMode == "Only WITH trend" ? trend == d : trend == -d
sideOk(int d) =>
sigSide == "Both" or (sigSide == "Longs only" and d == 1) or (sigSide == "Shorts only" and d == -1)
bgcolor(showTrendBg ? (trend == 1 ? color.new(#089981, 94) : trend == -1 ? color.new(#F23645, 94) : na) : na, title = "Trend tint")
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// iFVG SIGNAL TRACKING (extend / invalidate earlier signals)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
var array<Sig> sigs = array.new<Sig>()
if sigs.size() > 0
for i = sigs.size() - 1 to 0
Sig s = sigs.get(i)
if s.live
bool fail = s.dir == 1 ? close < s.bot : close > s.top
bool stop = s.dir == 1 ? low <= s.sl : high >= s.sl
bool old = bar_index - s.bornBar > ifvgLife
if not old
s.bx.set_right(bar_index)
if not old and not na(s.slLn)
s.slLn.set_x2(bar_index)
if fail or stop or old
s.live := false
if (fail or stop) and not clean
s.bx.set_bgcolor(color.new(color.gray, 85))
s.bx.set_border_color(color.new(color.gray, 60))
s.bx.set_text(stop ? "iFVG · SL hit" : "iFVG · invalidated")
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// INVERSION CHECK on pending FVGs
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
var array<FVG> bearF = array.new<FVG>() // gaps DOWN -> candidates for BULLISH inversion
var array<FVG> bullF = array.new<FVG>() // gaps UP -> candidates for BEARISH inversion
array<FVG> invUp = array.new<FVG>()
array<FVG> invDn = array.new<FVG>()
bool upDisp = dispOk(1)
bool dnDisp = dispOk(-1)
// record every body close through an opposing FVG, for the Auto calibration
bool candUp = false
bool candDn = false
if bearF.size() > 0
for f in bearF
if close > f.top and close > open
candUp := true
if bullF.size() > 0
for f in bullF
if close < f.bot and close < open
candDn := true
if candUp
dispCand.push(impSCU)
if candDn
dispCand.push(impSCD)
while dispCand.size() > 100
dispCand.shift()
// Gap cleanliness: shrink the clean part of the gap as wicks poke in; flag bodies inside
cleanUpdate(FVG f) =>
bool invLeg = (f.dir == -1 and close > open) or (f.dir == 1 and close < open) // candles of the reversal itself never make the gap dirty
if bar_index > f.c3Bar and not invLeg and low < f.cTop and high > f.cBot
float bT = math.max(open, close)
float bB = math.min(open, close)
if bT > f.bot and bB < f.top
f.bodyIn := true
if (high + low) / 2 < (f.cTop + f.cBot) / 2
f.cBot := math.min(f.cTop, math.max(f.cBot, high))
else
f.cTop := math.max(f.cBot, math.min(f.cTop, low))
cleanBad(FVG f) =>
float h = f.top - f.bot
float fill = h > 0 ? 1 - (f.cTop - f.cBot) / h : 1.0
cleanMode == "Off" ? false : (cleanMode == "Wicks only, no bodies" and f.bodyIn) or fill * 100 > maxFill
gapFill(FVG f) =>
float h = f.top - f.bot
h > 0 ? 1 - (f.cTop - f.cBot) / h : 1.0
velOk(FVG f) => f.vRm >= velMult and f.vBr * 100 >= velBody
gapPts(FVG f) =>
int pw = f.impl ? 0 : f.wickSh <= 0.25 ? 2 : f.wickSh <= wickMax / 100 ? 1 : 0
float fl = gapFill(f)
int pf = fl <= 0.05 ? 2 : fl <= 0.20 ? 1 : 0
int pv = f.vRm >= 2.0 and f.vBr >= 0.7 ? 2 : velOk(f) ? 1 : 0
pw + (f.bodyIn ? 0 : pf) + pv
gapGrade(int p) => p < 0 ? "F" : p >= 6 ? "A+" : p == 5 ? "A" : p == 4 ? "B" : p == 3 ? "C" : "D"
gapRank(string g) => g == "A+" ? 5 : g == "A" ? 4 : g == "B" ? 3 : g == "C" ? 2 : g == "D" ? 1 : 0
int minGapRank = gapRank(minGapGr)
gapOk(FVG f) => (velMode != "Required" or velOk(f)) and gapRank(gapGrade(gapPts(f))) >= minGapRank
// displacement of setups that pass every OTHER rule (for the stats log)
var array<float> setBR = array.new<float>()
var array<float> setRM = array.new<float>()
var array<float> setSC = array.new<float>()
var array<bool> setOK = array.new<bool>()
if bearF.size() > 0
int n = bearF.size()
for i = n - 1 to 0
FVG f = bearF.get(i)
if low < f.legExt
f.legExt := low
f.legBar := bar_index
float mg = closeMgn / 100 * (f.top - f.bot)
bool obBlock = obRule and not na(f.obExt) and close <= f.obExt
bool slowInv = maxInvN > 0 and bar_index - f.c3Bar > maxInvN
bool through = close > f.top + mg and not obBlock and not slowInv
bool eligible = qualifyMode == "Any active FVG" or i == n - 1
if dbgLog and through and close > open and barstate.isconfirmed
log.info("CAND BULL " + fmtT(time) + " gap " + px(f.top) + "-" + px(f.bot) + " | eligible " + str.tostring(eligible) + " | disp " + str.tostring(upDisp) + " | clean " + str.tostring(not cleanBad(f)) + " | gapGrade " + gapGrade(gapPts(f)) + " | gapOk " + str.tostring(gapOk(f)))
if through and eligible and dirOk(1) and (upDisp or killWeakE) and not cleanBad(f) and gapOk(f)
invUp.push(f)
box.delete(f.bx)
bearF.remove(i)
else if bar_index - f.c3Bar > maxAge or (through and (killWeakE or cleanBad(f) or not gapOk(f)))
box.delete(f.bx)
bearF.remove(i)
else
cleanUpdate(f)
if cleanBad(f)
box.delete(f.bx)
bearF.remove(i)
else if not na(f.bx)
f.bx.set_right(bar_index)
if bullF.size() > 0
int n = bullF.size()
for i = n - 1 to 0
FVG f = bullF.get(i)
if high > f.legExt
f.legExt := high
f.legBar := bar_index
float mg = closeMgn / 100 * (f.top - f.bot)
bool obBlock = obRule and not na(f.obExt) and close >= f.obExt
bool slowInv = maxInvN > 0 and bar_index - f.c3Bar > maxInvN
bool through = close < f.bot - mg and not obBlock and not slowInv
bool eligible = qualifyMode == "Any active FVG" or i == n - 1
if dbgLog and through and close < open and barstate.isconfirmed
log.info("CAND BEAR " + fmtT(time) + " gap " + px(f.top) + "-" + px(f.bot) + " | eligible " + str.tostring(eligible) + " | disp " + str.tostring(dnDisp) + " | clean " + str.tostring(not cleanBad(f)) + " | gapGrade " + gapGrade(gapPts(f)) + " | gapOk " + str.tostring(gapOk(f)))
if through and eligible and dirOk(-1) and (dnDisp or killWeakE) and not cleanBad(f) and gapOk(f)
invDn.push(f)
box.delete(f.bx)
bullF.remove(i)
else if bar_index - f.c3Bar > maxAge or (through and (killWeakE or cleanBad(f) or not gapOk(f)))
box.delete(f.bx)
bullF.remove(i)
else
cleanUpdate(f)
if cleanBad(f)
box.delete(f.bx)
bullF.remove(i)
else if not na(f.bx)
f.bx.set_right(bar_index)
// Resolve the zone when one candle inverts one or several gaps
pickZone(array<FVG> inv, int dir) =>
FVG latest = inv.get(0)
float uTop = na
float uBot = na
float oTop = na
float oBot = na
float leg = na
int c1b = na
int c1t = na
int parts = 0
int legB = na
int gP = -2
FVG gF = inv.get(0)
for f in inv
int pp = gapPts(f)
if pp > gP
gP := pp
gF := f
uTop := na(uTop) ? f.top : math.max(uTop, f.top)
uBot := na(uBot) ? f.bot : math.min(uBot, f.bot)
oTop := na(oTop) ? f.top : math.min(oTop, f.top)
oBot := na(oBot) ? f.bot : math.max(oBot, f.bot)
bool better = na(leg) or (dir == 1 ? f.legExt < leg : f.legExt > leg)
if better
leg := f.legExt
legB := f.legBar
c1b := na(c1b) ? f.c1Bar : math.min(c1b, f.c1Bar)
c1t := na(c1t) ? f.c1Time : math.min(c1t, f.c1Time)
parts += f.parts
if f.c3Bar > latest.c3Bar
latest := f
float t = latest.top
float b = latest.bot
int lb = latest.c1Bar
int lt = latest.c1Time
if stackZone == "Union"
t := uTop
b := uBot
lb := c1b
lt := c1t
else if stackZone == "Overlap only" and oTop > oBot
t := oTop
b := oBot
[t, b, lb, lt, leg, parts, legB, gP, gF.impl, gF.wickSh, gapFill(gF), gF.vRm]
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// SIGNAL BUILD + CONFLUENCE GRADING
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
var string sDir = "—"
var string sFvgT = "—"
var string sTop = "—"
var string sBot = "—"
var string sInvT = "—"
var string sClose = "—"
var string sSL = "—"
var string sHtf = "—"
var string sSwp = "—"
var string sSmt = "—"
var string sGrade = "—"
bool bullSig = false
bool bearSig = false
string alertMsg = ""
string earlyMsg = ""
var array<box> tapBoxes = array.new<box>()
var array<int> tapUse = array.new<int>()
var int lastTapDrawnBull = na
var int lastTapDrawnBear = na
type Pend
float zT
float zB
int zL
float sl
int qRank
string qGr
int qTot
int csSc
int spSc
int rrSc
bool htfOk
string tapNm
string gGr
string gTxt
string out
string grade
string htfTxt
string swpTxt
string smtTxt
string fvgT
string invT
string invC
int parts
var Pend pendU = na
var Pend pendD = na
Pend newU = na
Pend newD = na
for d in array.from(1, -1)
array<FVG> inv = d == 1 ? invUp : invDn
if inv.size() > 0
[zT, zB, zL, zLT, leg, parts, legB, gP, gImp, gWk, gFl, gRm] = pickZone(inv, d)
string gGr = gapGrade(gP)
string gDsc = gImp ? "implied" : gWk <= 0.25 and gFl <= 0.05 ? "clean" : "wicks in"
string gTxt = "Gap " + gGr + " (" + gDsc + (parts > 1 ? ", " + str.tostring(parts) + " stacked" : "") + ", wicks " + str.tostring(gWk * 100, "#") + "%, filled " + str.tostring(gFl * 100, "#") + "%, speed " + str.tostring(gRm, "#.#") + "x)"
float legX = d == 1 ? math.min(leg, low) : math.max(leg, high)
float buf = slBuf * tick
float sl = slMode == "Leg extreme" ? (d == 1 ? legX - buf : legX + buf) : slMode == "Inversion candle" ? (d == 1 ? low - buf : high + buf) : (d == 1 ? zB - buf : zT + buf)
// ── DODGY-style quality grade: candle strength /4 + inversion speed /3 + R:R /3
float qBody = math.abs(close - open)
float qRng = high - low
float qAtr = math.max(nz(atr), syminfo.mintick)
int csSc = (qRng > 0 and qBody / qRng >= 0.7 ? 2 : qRng > 0 and qBody / qRng >= 0.5 ? 1 : 0) + (qBody >= 1.0 * qAtr ? 2 : qBody >= 0.6 * qAtr ? 1 : 0)
bool newEx = d == 1 ? low < leg : high > leg
int bInv = bar_index - (newEx or na(legB) ? bar_index : legB)
int spSc = bInv <= spd3 ? 3 : bInv <= spd2 ? 2 : bInv <= spd1 ? 1 : 0
float over = (d == 1 ? close - zT : zB - close) / qAtr
int rrSc = over <= rr3 ? 3 : over <= rr2 ? 2 : over <= rr1 ? 1 : 0
bool keyTaken = d == 1 ? bslNow : sslNow
int qTot = keyTaken ? 0 : csSc + spSc + rrSc
string qGr = keyTaken ? "F" : qTot >= 10 ? "A+" : qTot == 9 ? "A" : qTot == 8 ? "A-" : qTot == 7 ? "B+" : qTot == 6 ? "B" : qTot == 5 ? "B-" : qTot >= 3 ? "C" : "F"
int qRank = gradeRank(qGr)
int entB = d == 1 ? lastBullTap : lastBearTap // price was inside the array on the move that made the gap (fresh entry from outside no longer needed)
bool htfOk = within(d == 1 ? lastBullTap : lastBearTap) and (not htfEnter or (within(entB) and entB >= zL - sweepLegN))
int swB = d == 1 ? lastSSL : lastBSL
bool swpOk = within(swB) and swB >= zL - sweepLegN
bool smtOk = smtAvail and within(d == 1 ? lastBullSMT : lastBearSMT)
bool rules = ((htfMode != "Required" or htfOk) and (sweepMode != "Required" or swpOk) and (smtMode != "Required" or smtOk))
bool passNoDisp = tfOk and rules and qRank >= minRank and trendOk(d) and sideOk(d) and (not useKz or inKz)
bool dispPass = d == 1 ? upDisp : dnDisp
bool pass = passNoDisp and dispPass
if dbgLog and not pass and barstate.isconfirmed
log.info("FILTERED " + (d == 1 ? "BULL " : "BEAR ") + fmtT(time) + " | htfTap " + str.tostring(within(d == 1 ? lastBullTap : lastBearTap)) + " | htfEnter " + str.tostring(htfOk) + " | sweepOnLeg " + str.tostring(swpOk) + " | quality " + qGr + " | session " + str.tostring(not useKz or inKz) + " | trend " + str.tostring(trendOk(d)) + " | disp " + str.tostring(dispPass))
if passNoDisp and barstate.isconfirmed
setBR.push(d == 1 ? impBRU : impBRD)
setRM.push(d == 1 ? impRMU : impRMD)
setSC.push(d == 1 ? impSCU : impSCD)
setOK.push(dispPass)
while setBR.size() > 100
setBR.shift()
setRM.shift()
setSC.shift()
setOK.shift()
int tot = (htfMode != "Off" ? 1 : 0) + (sweepMode != "Off" ? 1 : 0) + (smtMode != "Off" ? 1 : 0)
int sc = (htfMode != "Off" and htfOk ? 1 : 0) + (sweepMode != "Off" and swpOk ? 1 : 0) + (smtMode != "Off" and smtOk ? 1 : 0)
string grade = tot == 0 ? "no filters" : sc == tot ? "A+ " + str.tostring(sc) + "/" + str.tostring(tot) : str.tostring(sc) + "/" + str.tostring(tot)
string htfTxt = htfMode == "Off" ? "off" : htfOk ? "✓ " + (d == 1 ? lastBullTapName : lastBearTapName) : "✗"
string swpTxt = sweepMode == "Off" ? "off" : swpOk ? "✓ " + (d == 1 ? lastSSLName : lastBSLName) : "✗"
string smtTxt = smtMode == "Off" ? "off" : not smtAvail ? "n/a (set symbol)" : smtOk ? "✓ vs " + compSym : "✗"
string tapNmNow = d == 1 ? lastBullTapName : lastBearTapName
string out = (d == 1 ? "BULLISH iFVG" : "BEARISH iFVG") + " | " + syminfo.ticker + " " + timeframe.period
out += " | " + (htfOk ? tapNmNow : "no HTF FVG")
out += " | Gap " + gGr
out += " | gap formed " + fmtT(zLT) + " " + px(zB) + " - " + px(zT)
out += " | inverted " + fmtT(time) + " close " + px(close)
out += sweepMode == "Required" ? " | sweep " + swpTxt : ""
if pass
Pend np = Pend.new(zT, zB, zL, sl, qRank, qGr, qTot, csSc, spSc, rrSc, htfOk, d == 1 ? lastBullTapName : lastBearTapName, gGr, gTxt, out, grade, htfTxt, swpTxt, smtTxt, fmtT(zLT), fmtT(time), px(close), parts)
if d == 1
newU := np
else
newD := np
if confMode != C_NOW
string em = "ZEIFVG heads-up: " + (d == 1 ? "bullish" : "bearish") + " inversion candle closed on " + syminfo.ticker + " " + timeframe.period + " at " + px(close) + ", waiting for confirmation"
earlyMsg := earlyMsg == "" ? em : earlyMsg + "\n" + em
else if showFilt and not clean
label.new(bar_index, d == 1 ? low : high, "iFVG ✗", style = d == 1 ? label.style_label_up : label.style_label_down, color = color.new(color.gray, 60), textcolor = color.white, size = size.tiny, tooltip = "Filtered out\n" + out)
// Confirmation: the setup only goes out once the candle AFTER the inversion candle has closed
for d in array.from(1, -1)
Pend p = confMode == C_NOW ? (d == 1 ? newU : newD) : (d == 1 ? pendU : pendD)
if not na(p)
bool gapOpen = d == 1 ? (low - high[2] >= tick and low > p.zB) : (low[2] - high >= tick and high < p.zT)
bool beyond = d == 1 ? close > p.zT : close < p.zB
bool fire = confMode == C_NOW ? true : confMode == C_GAP ? gapOpen : beyond
if dbgLog and not fire and barstate.isconfirmed
log.info("NOT CONFIRMED " + (d == 1 ? "BULL " : "BEAR ") + fmtT(time) + " | next candle traded back into the space left by the candle before the inversion")
if fire
// the iFVG box = only the CLEAR space: where the old gap and the new gap left by the inversion overlap (no wicks inside)
bool clr = true
float cT = d == 1 ? math.min(p.zT, low) : math.min(p.zT, low[2])
float cB = d == 1 ? math.max(p.zB, high[2]) : math.max(p.zB, high)
bool useClr = cT - cB >= tick and cT - cB >= (p.zT - p.zB) / 3
float zT = useClr ? cT : p.zT
float zB = useClr ? cB : p.zB
int zL = p.zL // box starts at the candles that made the gap
float sl = p.sl
int qRank = p.qRank
string qGr = p.qGr
int qTot = p.qTot
int csSc = p.csSc
int spSc = p.spSc
int rrSc = p.rrSc
bool htfOk = p.htfOk
string gGr = p.gGr
string gTxt = p.gTxt
string grade = p.grade
string htfTxt = p.htfTxt
string swpTxt = p.swpTxt
string smtTxt = p.smtTxt
int parts = p.parts
string out = p.out + (confMode == C_NOW ? "" : " | confirmed " + fmtT(time))
color zc = d == 1 ? cBull : cBear
color sc0 = d == 1 ? #089981 : #F23645
int qTr = 50 + (5 - gapRank(gGr)) * 5
color qc = color.new(d == 1 ? cBull : cBear, 0)
if showTap and htfOk
int tL = d == 1 ? bullTapL : bearTapL
float tT = d == 1 ? bullTapT : bearTapT
float tB = d == 1 ? bullTapB : bearTapB
int prevDrawn = d == 1 ? lastTapDrawnBull : lastTapDrawnBear
if not na(tL) and not na(prevDrawn) and tL == prevDrawn and tapBoxes.size() > 0
tapBoxes.last().set_right(time)
tapUse.set(tapUse.size() - 1, bar_index)
if not na(tL) and (na(prevDrawn) or tL != prevDrawn)
tapUse.push(bar_index)
tapBoxes.push(box.new(math.max(tL, nz(time[40], tL)), tT, time, tB, xloc = xloc.bar_time, bgcolor = cTap, border_color = color.new(color.gray, 50), border_width = bdrW, text = p.tapNm, text_color = color.black, text_size = size.small, text_halign = text.align_left, text_valign = text.align_top))
if d == 1
lastTapDrawnBull := tL
else
lastTapDrawnBear := tL
label lbT = na
string lTxt = ""
lTxt := showGapGr ? lTxt + (lTxt == "" ? "" : " · ") + "Gap " + gGr : lTxt
if clean and lTxt != ""
lbT := label.new(bar_index, na, lTxt, tooltip = gTxt, yloc = d == 1 ? yloc.belowbar : yloc.abovebar, style = label.style_none, textcolor = color.black, size = size.small)
box bx = na
bx := clean ? box.new(zL, zT, clr ? bar_index - 1 : bar_index, zB, border_color = color.new(qc, bdrT), border_width = bdrW, bgcolor = color.new(qc, qTr)) : box.new(zL, zT, bar_index, zB, border_color = color.new(sc0, 40), bgcolor = zc, text = "iFVG " + qGr, text_size = size.tiny, text_color = color.new(sc0, 20), text_halign = text.align_right)
line sln = na
if not clean
sln := line.new(bar_index, sl, bar_index, sl, color = color.new(sc0, 20), style = line.style_dashed, width = 1)
string tt = (d == 1 ? "Bullish" : "Bearish") + " iFVG " + grade
tt += "\nFVG formed: " + p.fvgT
tt += "\nUpper: " + px(zT) + " Lower: " + px(zB) + (parts > 1 ? " (" + str.tostring(parts) + " stacked gaps)" : "")
tt += "\nInversion: " + p.invT + " close " + p.invC
tt += "\nStop: " + px(sl)
tt += "\n" + gTxt
tt += "\nQuality: " + qGr + " (" + str.tostring(qTot) + "/10 – strength " + str.tostring(csSc) + "/4, speed " + str.tostring(spSc) + "/3, R:R " + str.tostring(rrSc) + "/3)"
tt += "\nHTF: " + htfTxt + "\nSweep: " + swpTxt + "\nSMT: " + smtTxt + "\nTrend: " + trendTxt
label lbF = na
if not clean
lbF := label.new(bar_index, d == 1 ? low : high, (d == 1 ? "▲ iFVG " : "▼ iFVG ") + qGr + " · " + grade, style = d == 1 ? label.style_label_up : label.style_label_down, color = sc0, textcolor = color.white, size = size.small, tooltip = tt)
sigs.push(Sig.new(zT, zB, sl, d, bar_index, bx, sln, true, lbT, lbF))
while sigs.size() > showN
Sig o = sigs.shift()
box.delete(o.bx)
line.delete(o.slLn)
label.delete(o.lb)
label.delete(o.lb2)
int oldestBorn = sigs.size() > 0 ? sigs.first().bornBar : bar_index
while tapBoxes.size() > 0 and tapUse.first() < oldestBorn
box.delete(tapBoxes.shift())
tapUse.shift()
if d == 1
bullSig := true
else
bearSig := true
sDir := d == 1 ? "BULLISH ▲" : "BEARISH ▼"
sFvgT := p.fvgT
sTop := px(zT)
sBot := px(zB)
sInvT := p.invT
sClose := p.invC
sSL := px(sl)
sHtf := htfTxt
sSwp := swpTxt
sSmt := smtTxt
sGrade := grade
string tapA = htfOk ? p.tapNm : "none"
string aShort = "ZEIFVG " + (d == 1 ? "bullish" : "bearish") + " iFVG " + syminfo.ticker + " " + timeframe.period + " @ " + px(close) + " | " + tapA + " | Gap " + gGr
string aJson = '{"indicator":"ZEIFVG","side":"' + (d == 1 ? "long" : "short") + '","ticker":"' + syminfo.ticker + '","tf":"' + timeframe.period + '","price":' + str.tostring(close) + ',"box_top":' + str.tostring(zT) + ',"box_bottom":' + str.tostring(zB) + ',"htf":"' + tapA + '","gap":"' + gGr + '"}'
string aOut = alertFmt == "Short" ? aShort : alertFmt == "Full details" ? out : aJson
alertMsg := alertMsg == "" ? aOut : alertMsg + "\n" + aOut
if barstate.isconfirmed
log.info(out)
pendU := newU
pendD := newD
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// NEW FVG DETECTION (current bar = candle 3) – after inversion checks
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
addFVG(array<FVG> arr, float t, float b, int d, int c1T, color c, bool imp, float wsh) =>
float vrm = c2RngN > 0 ? (high[1] - low[1]) / c2RngN : 0.0
float vbr = high[1] > low[1] ? math.abs(close[1] - open[1]) / (high[1] - low[1]) : 0.0
float obx = d == 1 ? (close[2] < open[2] ? low[2] : na) : (close[2] > open[2] ? high[2] : na)
bool merged = false
if mergeMode == "Merge overlapping" and arr.size() > 0
FVG f = arr.last()
float tol = mergeTol * syminfo.mintick
if b <= f.top + tol and t >= f.bot - tol
f.top := math.max(f.top, t)
f.bot := math.min(f.bot, b)
f.cTop := math.max(f.cTop, t)
f.cBot := math.min(f.cBot, b)
f.c3Bar := bar_index
f.parts += 1
f.impl := f.impl or imp
f.wickSh := math.max(f.wickSh, wsh)
f.vRm := math.max(f.vRm, vrm)
f.vBr := math.max(f.vBr, vbr)
if (d == -1 and low < f.legExt) or (d == 1 and high > f.legExt)
f.legExt := d == -1 ? low : high
f.legBar := bar_index
if not na(f.bx)
f.bx.set_top(f.top)
f.bx.set_bottom(f.bot)
f.bx.set_right(bar_index)
f.bx.set_text(str.tostring(f.parts) + " gaps")
merged := true
if not merged
box bx = showRawE ? box.new(bar_index - 2, t, bar_index, b, border_color = na, bgcolor = c, text_size = size.tiny, text_color = color.gray, text_halign = text.align_left) : na
arr.push(FVG.new(t, b, d, bar_index - 2, c1T, bar_index, d == -1 ? low : high, 1, bx, bar_index, t, b, false, imp, wsh, vrm, vbr, obx))
if arr.size() > maxTracked
FVG o = arr.shift()
box.delete(o.bx)
int c1Time = time[2]
float gapDn = low[2] - high // bearish FVG: C1 low > C3 high
float gapUp = low - high[2] // bullish FVG: C1 high < C3 low
float c1BLo = math.min(open[2], close[2])
float c1BHi = math.max(open[2], close[2])
float c3BLo = math.min(open, close)
float c3BHi = math.max(open, close)
// share of the body-to-body space eaten by the C1 / C3 wicks (0 = no wicks in the gap at all)
float bgDn = c1BLo - c3BHi
float bgUp = c3BLo - c1BHi
float wsDn = bgDn > 0 ? math.max(0.0, 1 - gapDn / bgDn) : 1.0
float wsUp = bgUp > 0 ? math.max(0.0, 1 - gapUp / bgUp) : 1.0
if not na(gapDn) and gapDn > 0 and gapDn >= minGap and wsDn * 100 <= wickMax
addFVG(bearF, low[2], high, -1, c1Time, cRawBe, false, wsDn)
if not na(gapUp) and gapUp > 0 and gapUp >= minGap and wsUp * 100 <= wickMax
addFVG(bullF, low, high[2], 1, c1Time, cRawBu, false, wsUp)
// Implied FVGs: wicks of candle 1 and 3 overlap a little, bodies still leave clear space
float c2Rng = high[1] - low[1]
if useImpl and not na(gapDn) and gapDn <= 0 and close[1] < open[1] and c1BLo > c3BHi and -gapDn <= implTol / 100 * c2Rng
float iT = (low[2] + c1BLo) / 2
float iB = (high + c3BHi) / 2
if iT - iB >= minGap
addFVG(bearF, iT, iB, -1, c1Time, cRawBe, true, 1.0)
if useImpl and not na(gapUp) and gapUp <= 0 and close[1] > open[1] and c3BLo > c1BHi and -gapUp <= implTol / 100 * c2Rng
float iT = (low + c3BLo) / 2
float iB = (high[2] + c1BHi) / 2
if iT - iB >= minGap
addFVG(bullF, iT, iB, 1, c1Time, cRawBu, true, 1.0)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// PANEL
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
tPos = tblPos == "Top Right" ? position.top_right : tblPos == "Bottom Right" ? position.bottom_right : tblPos == "Top Left" ? position.top_left : position.bottom_left
var table tbl = table.new(tPos, 2, 13,bgcolor = color.new(#131722, 10), border_color = color.new(color.gray, 70), border_width = 1)
cell(int r, string k, string v) =>
tbl.cell(0, r, k, text_color = color.gray, text_size = size.small, text_halign = text.align_left)
tbl.cell(1, r, v, text_color = color.white, text_size = size.small, text_halign = text.align_left)
if showTblE and barstate.islast
cell(0, "Last iFVG", sDir)
cell(1, "Grade", sGrade)
cell(2, "FVG formed", sFvgT)
cell(3, "FVG upper", sTop)
cell(4, "FVG lower", sBot)
cell(5, "Inversion", sInvT)
cell(6, "Close", sClose)
cell(7, "Stop", sSL)
cell(8, "HTF tap", sHtf)
cell(9, "Sweep", sSwp)
cell(10, "SMT", sSmt)
cell(11, "SMT symbol", smtAvail ? compSym : "none")
cell(12, "Trend now", trendTxt + (trendMode == "Off" ? " (filter off)" : ""))
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ALERTS
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
bool alertT = alertOn and inKz
if alertT and alertWhen != A_EARLY and (bullSig or bearSig)
alert(alertMsg, alert.freq_once_per_bar_close)
if alertT and alertWhen != A_CONF and earlyMsg != ""
alert(earlyMsg, alert.freq_once_per_bar_close)
alertcondition(bullSig and alertT, "Bullish iFVG", "Bullish iFVG on {{ticker}} {{interval}} – close {{close}}")
alertcondition(bearSig and alertT, "Bearish iFVG", "Bearish iFVG on {{ticker}} {{interval}} – close {{close}}")