Indicator · Pine Script v6 · On the chart

LiqSweep+iFVG

by Matswm86

LiqSweep+iFVG is an indicator designed to identify liquidity raids across New York, London, and Asia sessions, signaling reversal entries using inverted Fair Value Gaps (iFVG).

View on GitHub

GitHub stars29on the repository
Pine versionv6current
Lines of code631
Settings40inputs
LicenceMIT
Last update6 weeks ago11 Oct 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

631 lines of Pine Script v6 from LiqSweep_iFVG.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

LiqSweep_iFVG.pine
//@version=6
indicator("LiqSweep+iFVG", "LiqSweep+iFVG", true, max_lines_count=500, max_labels_count=250, max_boxes_count=250)

// ===================================================================
// LiqSweep+iFVG - session-liquidity raid -> inverted-FVG reversal.
// - Sessions (NY/London/Asia) tracked as liquidity; a level dies on
//   its first touch, and a new session's level replaces the previous
//   still-live level of the same type (configurable depth).
// - A raid beyond a level arms a reversal for a limited window; all
//   sessions arm by default (per-session toggles).
// - Trigger: a Fair Value Gap body-closed through its far edge
//   against the raid direction. ONE inversion clears every live
//   same-direction arm. Pre-raid gaps within the lookback are
//   eligible; raid-leg gaps always are.
// - EQH/EQL module adapted from the public "EQ & RE" concept
//   (CantoLab). Consumed swings are pruned, active lines capped.
// - Optional overlays: higher-TF FVG boxes (off by default), the
//   premium/discount dealing range merged from the standalone Macro
//   Dealing Range indicator (group 05, on by default), and Williams-
//   fractal swing-point marks (group 06, 10 periods, on by default).
// Runs on any timeframe; defaults are sized for MNQ on 1-minute.
// ====================================================================

grpS = "01. Sessions (America/New_York)"
useNY  = input.bool(true,  "NY levels",     inline="1", group=grpS, tooltip="Track the New York session's high and low as liquidity levels. The session window is set in the field to the right.")
nySess = input.session("0930-1600", "",     inline="1", group=grpS)
useLO  = input.bool(true,  "London levels", inline="2", group=grpS, tooltip="Track the London session's high and low as liquidity levels.")
loSess = input.session("0300-1100", "",     inline="2", group=grpS)
useAS  = input.bool(true,  "Asia levels",   inline="3", group=grpS, tooltip="Track the Asia session's high and low as liquidity levels. 20:00-01:00 crosses midnight; that is handled.")
asSess = input.session("2000-0100", "",     inline="3", group=grpS)
armNY = input.bool(true,  "NY raids arm",     inline="a1", group=grpS, tooltip="Which sessions' levels can ARM a reversal. This is SEPARATE from tracking above: a session stays tracked (its high/low still counts as a draw-on-liquidity pool) even when its raids do not arm.\n\nAll sessions arm by default; narrow this to focus the signal on the session levels you care about.")
armLO = input.bool(true,  "London raids arm", inline="a1", group=grpS)
armAS = input.bool(true,  "Asia raids arm",   inline="a1", group=grpS)
showBoxes = input.bool(true, "Show session boxes", group=grpS, tooltip="Shade each session as a box whose top/bottom grow with the session's high/low while it is running, then freeze. Colors follow the per-session color inputs below.")
sessTransp = input.int(94, "Session box transparency", minval=0, maxval=100, group=grpS, tooltip="Fill transparency of the session boxes: 0 = solid, 100 = invisible. The session tag text is drawn a step more opaque than the fill.")
maxDays   = input.int(30, "Keep drawings for N sessions per type", minval=1, group=grpS, tooltip="History depth. Older session boxes and level lines beyond this count are deleted per session type, keeping the chart readable and under TradingView's drawing limits.")

grpL = "02. Levels (liquidity lines)"
showLevels = input.bool(true, "Show level lines", group=grpL, tooltip="Each completed session leaves two horizontal lines: its high and its low. A line extends forward until its FIRST touch in ANY later session, then freezes with a label. Touched once = gone forever; it can never be a target again. A new session's level also replaces still-live older levels of the same type beyond the configured live depth below.")
showRaidLabels = input.bool(true, "Show RAID / hit labels", group=grpL, tooltip="'RAID <tag>' marks a take-out that armed the reversal (price traded beyond the level by at least the raid buffer). 'hit <tag>' marks a touch too shallow to arm; the level still dies.")
liveDepth = input.int(1, "Untouched levels kept live per session type", minval=1, maxval=30, group=grpL, tooltip="1 = strict replacement: each new session's level REPLACES the previous still-live level of the same type, so only the newest untouched high/low per session type can be raided.\n\nRaise to N to keep the last N sessions' untouched levels live simultaneously, so an older pool that was never touched can still be raided days later.\n\nValues above 1 generate additional signals beyond the default model. Levels older than 'Keep drawings for N sessions' are deleted regardless, so keep that input at or above this one.")

grpE = "03. Raid + trigger"
entryMode = input.string("iFVG inversion", "Trigger after a raid", options=["iFVG inversion", "Return through level"], group=grpE, tooltip="What converts an armed raid into an entry signal.\n\niFVG inversion: a Fair Value Gap from the raid leg gets BODY-closed through its far edge in the reversal direction (a wick through is rejection, not inversion).\n\nReturn through level: simpler variant - the bar closes back through the raided level itself.")
sweepBufPts = input.float(0.25, "Min raid beyond level (points)", minval=0, step=0.25, group=grpE, tooltip="How far past the level price must trade for the take-out to count as a raid (arm), in POINTS (1.0 = 4 MNQ ticks).")
retTtlMin = input.int(60, "Trigger window after raid (minutes)", minval=1, group=grpE, tooltip="How long an armed raid stays valid. If the trigger (inversion or return) has not happened within this window, the raid is abandoned - no trade.")
entryWin  = input.session("0100-1500", "Active entry window (NY tz)", group=grpE, tooltip="Signals only fire inside this window (New York time). Levels and FVGs are tracked around the clock; only the ENTRY is gated.")

grpQ = "02b. Equal highs / lows (EQH-EQL)"
useEq   = input.bool(true, "Track equal highs / lows", group=grpQ, tooltip="Adapted from the public 'EQ & RE' concept (CantoLab). A swing high is a bar whose high is the highest of the last three (1-left/1-right pivot); when a later bar comes back into a tolerance band around it, the pair is an Equal High (EQH). Same, mirrored, for lows (EQL). Equal highs/lows are resting liquidity: a cluster of stops sits just beyond them.")
eqTolPts = input.float(1.5, "Tolerance (points)", minval=0, step=0.25, group=grpQ, tooltip="How close a later touch must come to count as EQUAL, in POINTS. 1.0 pt = 4 MNQ ticks = the source script's default. A touch further than this beyond the swing BREAKS the point instead.")
eqMinGap = input.int(3, "Minimum bars before an equal match", minval=1, group=grpQ, tooltip="Bars that must pass after the swing forms before a touch inside the band counts as equal. Sooner than that and the point is treated as broken (swept), never marked equal. Source default: 3.")
eqArm   = input.bool(false, "Raids of EQH/EQL also ARM", group=grpQ, tooltip="A take-out of an equal high/low beyond the tolerance arms a reversal exactly like a session-level raid does, so the same iFVG trigger can fire on it.\n\nOFF by default: equal highs/lows fire far more often than session levels, so expect a much noisier signal. Provided for research.")
colEq   = input.color(color.red, "EQH/EQL color", group=grpQ)

grpF = "04. Fair Value Gaps"
minFvgPts = input.float(1.0, "Minimum FVG size (points)", minval=0, step=0.25, group=grpF, tooltip="Gaps smaller than this are ignored entirely - not drawn, not usable for inversion. 1.0 point on MNQ = 4 ticks. Set 0 to keep every true 3-bar gap.\n\nTradeoff: with a size filter, a smaller gap can be the FIRST inversion, so the signal waits for the next gap that passes the filter and fires a few bars later. 0 removes that lateness at the cost of chart noise.")
fvgFillRule = input.string("Body close through", "FVG fill rule (gap death)", options=["Body close through", "Wick through"], group=grpF, tooltip="When a gap counts as FILLED and is deleted from chart and logic.\n\nBody close through: a candle body closes beyond the far edge (matches the model; a filled gap can no longer invert later).\n\nWick through: any wick beyond the far edge kills it (matches the common FVG indicators, stricter).\n\nNote: the INVERSION signal itself always requires a body close, regardless of this setting.")
fvgLookback = input.int(30, "FVGs eligible from N bars before raid", minval=0, group=grpF, tooltip="Only gaps formed at most this many bars before the raid (or any time after it, while armed) can invert into a signal. Keeps the inversion tied to the raid leg instead of stale gaps from hours ago.")
fvgExtBars = input.int(30, "Extend live gap boxes N bars", minval=5, group=grpF, tooltip="Visual only: how far unfilled gap boxes stretch to the right of their formation bar while alive.")
invExtBars = input.int(60, "Keep inverted gap visible N bars", minval=5, group=grpF, tooltip="After an inversion fires, the flipped gap is recolored and kept on the chart this many bars so the retest into it is visible.")
showFvg = input.bool(false, "Show FVG boxes", group=grpF, tooltip="Draw every live gap that passes the size filter. Green = bullish gap (support until inverted), red = bearish. Filled gaps disappear.")

grpH = "04b. Higher-timeframe FVG confluence"
htfFvgOn = input.bool(false, "Require price inside a higher-TF FVG", group=grpH, tooltip="Location confluence: a signal only fires if price has traded inside a live higher-timeframe FVG at any point from the raid through the trigger.\n\nHigher gap timeframes filter harder: fewer signals, each backed by stronger higher-timeframe context. Off by default so the unfiltered baseline is what you see first.")
htfFvgTf = input.string("15", "Gap timeframe", options=["5", "15", "60", "240", "D"], group=grpH, tooltip="Which timeframe's gaps count. Higher = stronger filter and fewer signals.")
htfFvgShow = input.bool(false, "Show higher-TF gap boxes", group=grpH, tooltip="Draw each live higher-timeframe gap. Boxes disappear the bar a chart candle body closes beyond the far edge, which is the same gap-death rule the 1m gaps use.")
colHtfFvg = input.color(color.new(color.aqua, 0), "Higher-TF gap color", inline="hc", group=grpH)
htfTransp = input.int(93, "transparency", minval=0, maxval=100, inline="hc", group=grpH, tooltip="Fill transparency of the higher-TF gap boxes: 0 = solid, 100 = invisible. Border and label follow, drawn more opaque than the fill.")
grpP = "05. Macro dealing range (premium/discount)"
usePD      = input.bool(true, "Show premium/discount zones", group=grpP, tooltip="Shade the active dealing range: premium (upper half) and discount (lower half) around the equilibrium midpoint. The range is the highest high / lowest low over the lookback below. Judge entries against where price sits inside the range.")
pdLookback = input.int(50, "Dealing range lookback (bars)", minval=2, group=grpP, tooltip="How many bars back the dealing range looks for its high and low.")
colPdBear  = input.color(color.new(#a65c4f, 85), "Premium",  inline="pd", group=grpP, tooltip="Zone fill colors. The opacity set in the color picker is applied to the shading as-is.")
colPdBull  = input.color(color.new(#7f9a65, 85), "Discount", inline="pd", group=grpP)

grpW = "06. Swing points (fractals)"
useSwings = input.bool(true, "Mark swing points", group=grpW, tooltip="Williams-fractal swing marks: a high/low that is the extreme of N bars on each side. A mark is CONFIRMED N bars after the swing bar and is plotted back on it - it cannot appear in real time, by definition.")
swingN    = input.int(10, "Periods (bars each side)", minval=1, group=grpW)
colSwHi   = input.color(#009688, "High", inline="sw", group=grpW)
colSwLo   = input.color(#F44336, "Low",  inline="sw", group=grpW)

grpC = "07. Colors"
colNY = input.color(color.orange, "NY", inline="c", group=grpC, tooltip="Session box + level line colors per session type.")
colLO = input.color(color.blue, "London", inline="c", group=grpC)
colAS = input.color(color.purple, "Asia", inline="c", group=grpC)
colBull = input.color(color.green, "Bull FVG", inline="c2", group=grpC, tooltip="Fill colors for live gap boxes and the inverted-gap highlight.")
colBear = input.color(color.red, "Bear FVG", inline="c2", group=grpC)

tzNY = "America/New_York"
tick = syminfo.mintick
// vertical clearance that floats event labels off the candles (~0.6 ATR,
// tick fallback while ATR warms up). Visual only.
float labPad = nz(ta.atr(14), tick * 8) * 0.6
useIfvg = entryMode == "iFVG inversion"
bodyFill = fvgFillRule == "Body close through"

inNY = useNY and not na(time(timeframe.period, nySess, tzNY))
inLO = useLO and not na(time(timeframe.period, loSess, tzNY))
inAS = useAS and not na(time(timeframe.period, asSess, tzNY))
inWin = not na(time(timeframe.period, entryWin, tzNY))

// ── Session boxes ──────────────────────────────────────────────────
var array<box>    sbBox = array.new<box>()
var array<string> sbTag = array.new<string>()

f_newBox(string tag, color col) =>
    if showBoxes
        sbBox.push(box.new(time, high, time, low, xloc=xloc.bar_time,
             border_color=color.new(col, 100), bgcolor=color.new(col, sessTransp),
             text=tag, text_color=color.new(col, math.max(sessTransp - 49, 0)), text_size=size.tiny,
             text_halign=text.align_left, text_valign=text.align_top))
        sbTag.push(tag)
        int cnt = 0
        for j = sbTag.size() - 1 to 0
            if sbTag.get(j) == tag
                cnt += 1
                if cnt > maxDays
                    box.delete(sbBox.get(j))
                    sbBox.remove(j)
                    sbTag.remove(j)
                    break

f_growBox(string tag) =>
    if showBoxes and sbTag.size() > 0
        for j = sbTag.size() - 1 to 0
            if sbTag.get(j) == tag
                box b = sbBox.get(j)
                b.set_right(time)
                b.set_top(math.max(b.get_top(), high))
                b.set_bottom(math.min(b.get_bottom(), low))
                break

// ── Level lines ────────────────────────────────────────────────────
var array<line>   lvLine = array.new<line>()
var array<string> lvTag  = array.new<string>()
var array<int>    lvSide = array.new<int>()
var array<bool>   lvLive = array.new<bool>()

f_newLevel(string tag, int side, float price, color col) =>
    if showLevels
        // replacement semantics: a new session's level retires still-live older
        // levels of the same tag beyond the configured live depth. liveDepth=1
        // (default) = strict replacement: newest untouched level only.
        if lvTag.size() > 0
            int liveCnt = 0
            for j = lvTag.size() - 1 to 0
                if lvTag.get(j) == tag and lvLive.get(j)
                    liveCnt += 1
                    if liveCnt > liveDepth - 1
                        lvLive.set(j, false)
        lvLine.push(line.new(time, price, time, price, xloc=xloc.bar_time, color=col, width=2))
        lvTag.push(tag)
        lvSide.push(side)
        lvLive.push(true)
        int cnt = 0
        for j = lvTag.size() - 1 to 0
            if lvTag.get(j) == tag
                cnt += 1
                if cnt > maxDays
                    line.delete(lvLine.get(j))
                    lvLine.remove(j)
                    lvTag.remove(j)
                    lvSide.remove(j)
                    lvLive.remove(j)
                    break

var float nyHi = na, var float nyLo = na
var float loHi = na, var float loLo = na
var float asHi = na, var float asLo = na

if inNY
    if na(nyHi)
        f_newBox("NY", colNY)
    f_growBox("NY")
    nyHi := na(nyHi) ? high : math.max(nyHi, high)
    nyLo := na(nyLo) ? low : math.min(nyLo, low)
else if not na(nyHi)
    f_newLevel("NYH", 1, nyHi, colNY)
    f_newLevel("NYL", -1, nyLo, colNY)
    nyHi := na
    nyLo := na
if inLO
    if na(loHi)
        f_newBox("LONDON", colLO)
    f_growBox("LONDON")
    loHi := na(loHi) ? high : math.max(loHi, high)
    loLo := na(loLo) ? low : math.min(loLo, low)
else if not na(loHi)
    f_newLevel("LOH", 1, loHi, colLO)
    f_newLevel("LOL", -1, loLo, colLO)
    loHi := na
    loLo := na
if inAS
    if na(asHi)
        f_newBox("ASIA", colAS)
    f_growBox("ASIA")
    asHi := na(asHi) ? high : math.max(asHi, high)
    asLo := na(asLo) ? low : math.min(asLo, low)
else if not na(asHi)
    f_newLevel("ASH", 1, asHi, colAS)
    f_newLevel("ASL", -1, asLo, colAS)
    asHi := na
    asLo := na

// ── Live FVGs with fill-death lifecycle ────────────────────────────
var array<float> fvgTop = array.new_float()
var array<float> fvgBot = array.new_float()
var array<int>   fvgIdx = array.new_int()
var array<int>   fvgDir = array.new_int()      // 1 bull, -1 bear
var array<box>   fvgBoxA = array.new<box>()
var array<int>   fvgInvAt = array.new_int()    // -1 = live; else bar of inversion

f_addFvg(int d, float top, float bot) =>
    fvgTop.push(top)
    fvgBot.push(bot)
    fvgIdx.push(bar_index)
    fvgDir.push(d)
    fvgInvAt.push(-1)
    color cc = d == 1 ? colBull : colBear
    fvgBoxA.push(showFvg ? box.new(bar_index - 1, top, bar_index + fvgExtBars, bot,
         border_color=color.new(cc, 100), bgcolor=color.new(cc, 92)) : box(na))
    if fvgTop.size() > 150
        box.delete(fvgBoxA.get(0))
        fvgTop.shift()
        fvgBot.shift()
        fvgIdx.shift()
        fvgDir.shift()
        fvgInvAt.shift()
        fvgBoxA.shift()

if useIfvg
    if low > high[2] and low - high[2] >= minFvgPts
        f_addFvg(1, low, high[2])
    if high < low[2] and low[2] - high >= minFvgPts
        f_addFvg(-1, low[2], high)

// ── Higher-timeframe FVGs (location confluence, group 04b) ─────────
// Same 3-bar gap rule as the 1m gaps, requested on the selected timeframe
// with lookahead_off so a gap only exists once its HTF bar has confirmed.
var array<float> hzTop = array.new_float()
var array<float> hzBot = array.new_float()
var array<int>   hzDir = array.new_int()
var array<box>   hzBox = array.new<box>()
var int lastHzTime = 0

f_htfGap() =>
    bool gb = low > high[2] and low - high[2] >= minFvgPts
    bool gs = high < low[2] and low[2] - high >= minFvgPts
    [gb, gs, gb ? low : gs ? low[2] : na, gb ? high[2] : gs ? high : na, time]

// when the overlay is off, request the chart TF instead - near-free, and
// the htfFvgShow guard below already discards the values
[hgB, hgS, hgT, hgBm, hgTime] = request.security(syminfo.tickerid, (htfFvgOn or htfFvgShow) ? htfFvgTf : timeframe.period, f_htfGap(), lookahead=barmerge.lookahead_off)

if (htfFvgOn or htfFvgShow) and (hgB or hgS) and not na(hgT) and not na(hgBm) and hgTime != lastHzTime
    lastHzTime := hgTime
    hzTop.push(hgT)
    hzBot.push(hgBm)
    hzDir.push(hgB ? 1 : -1)
    hzBox.push(htfFvgShow ? box.new(bar_index, hgT, bar_index + 1, hgBm, xloc=xloc.bar_index,
         border_color=color.new(colHtfFvg, math.max(htfTransp - 13, 0)), bgcolor=color.new(colHtfFvg, htfTransp),
         text=(htfFvgTf == "240" ? "4h" : htfFvgTf == "D" ? "1D" : htfFvgTf + "m") + " FVG", text_color=color.new(colHtfFvg, math.max(htfTransp - 48, 0)), text_size=size.tiny) : box(na))
    if hzTop.size() > 60
        box.delete(hzBox.get(0))
        hzTop.shift()
        hzBot.shift()
        hzDir.shift()
        hzBox.shift()

// gap death: a chart-bar body close beyond the far edge (same rule as 1m)
if hzTop.size() > 0
    for j = hzTop.size() - 1 to 0
        bool deadH = hzDir.get(j) == 1 ? close < hzBot.get(j) : close > hzTop.get(j)
        if deadH
            box.delete(hzBox.get(j))
            hzTop.remove(j)
            hzBot.remove(j)
            hzDir.remove(j)
            hzBox.remove(j)
        else if htfFvgShow and not na(hzBox.get(j))
            box.set_right(hzBox.get(j), bar_index + 1)

// does this bar trade inside a live higher-TF gap? (confluence filter)
f_inHtfZone() =>
    bool found = false
    if hzTop.size() > 0
        for j = 0 to hzTop.size() - 1
            if low <= hzTop.get(j) and high >= hzBot.get(j)
                found := true
                break
    found
bool inHtfGap = f_inHtfZone()

// ── Arms ───────────────────────────────────────────────────────────
var array<int>   armDir = array.new_int()
var array<float> armLvl = array.new_float()
var array<float> armExt = array.new_float()
var array<int>   armExp = array.new_int()
var array<int>   armI0  = array.new_int()
var array<bool>  armQ   = array.new<bool>()

// ── EQH/EQL module (adapted from "Equal Highs and Lows with Relative
// [CantoLab]" - same swing/equal/sweep semantics, bar_time drawings) ──
type SwingPoint
    float price      = na
    int   time       = na
    int   formBarIdx = na
    bool  referenced = false

type ActiveLine
    line  ln         = na
    label lb         = na
    int   startTime  = na
    float startPrice = na
    int   endTime    = na
    float endPrice   = na

method isFarEnough(SwingPoint sp, int currentBarIdx, int minGap) =>
    (currentBarIdx - sp.formBarIdx) > minGap

method checkLevel(SwingPoint sp, float level, float tolerance, bool isHigh, int currentBarIdx, int minGap) =>
    string state = "none"
    if not sp.referenced
        bool farEnough = sp.isFarEnough(currentBarIdx, minGap)
        if isHigh
            if level > sp.price + tolerance
                state := "break"
            else if farEnough and level <= sp.price + tolerance and level >= sp.price - tolerance
                state := "equal"
        else
            if level < sp.price - tolerance
                state := "break"
            else if farEnough and level >= sp.price - tolerance and level <= sp.price + tolerance
                state := "equal"
        if state != "none"
            sp.referenced := true
    state

method mergeOrCreate(ActiveLine[] arr, SwingPoint sp, int endTime, float endPrice, float tolerance, bool isHigh) =>
    int matchIdx = -1
    if arr.size() > 0
        for i = 0 to arr.size() - 1
            ActiveLine alx = arr.get(i)
            if alx.endTime == sp.time and math.abs(alx.endPrice - sp.price) <= tolerance
                matchIdx := i
                break
    if matchIdx == -1
        ActiveLine alNew = ActiveLine.new()
        alNew.ln := line.new(sp.time, sp.price, endTime, endPrice, xloc=xloc.bar_time, color=colEq, width=1)
        alNew.startTime := sp.time
        alNew.startPrice := sp.price
        arr.push(alNew)
        matchIdx := arr.size() - 1
    ActiveLine al = arr.get(matchIdx)
    al.endTime := endTime
    al.endPrice := endPrice
    line.set_x2(al.ln, endTime)
    line.set_y2(al.ln, endPrice)
    bool exact = al.startPrice == endPrice
    string labelText = isHigh ? (exact ? "EQH" : "REH") : (exact ? "EQL" : "REL")
    int midTime = int(math.round((al.startTime + endTime) / 2))
    if na(al.lb)
        al.lb := label.new(midTime, endPrice, labelText, xloc=xloc.bar_time,
             style=isHigh ? label.style_label_down : label.style_label_up,
             color=color.new(color.white, 100), textcolor=colEq, size=size.small)
    if not na(al.lb)
        al.lb.set_x(midTime)
        al.lb.set_y(endPrice)
        al.lb.set_text(labelText)

method checkSweep(ActiveLine[] arr, float level, bool isHigh, float tolerance) =>
    if arr.size() > 0
        for i = arr.size() - 1 to 0
            ActiveLine al = arr.get(i)
            float extreme = isHigh ? math.max(al.startPrice, al.endPrice) : math.min(al.startPrice, al.endPrice)
            bool swept = isHigh ? level > extreme + tolerance : level < extreme - tolerance
            if swept
                if eqArm
                    armDir.push(isHigh ? -1 : 1)
                    armLvl.push(extreme)
                    armExt.push(level)
                    armExp.push(time + retTtlMin * 60000)
                    armI0.push(bar_index)
                    armQ.push(inHtfGap)
                line.delete(al.ln)
                if not na(al.lb)
                    label.delete(al.lb)
                arr.remove(i)

var SwingPoint[] swingHighs  = array.new<SwingPoint>()
var SwingPoint[] swingLows   = array.new<SwingPoint>()
var ActiveLine[] activeHighs = array.new<ActiveLine>()
var ActiveLine[] activeLows  = array.new<ActiveLine>()

int hb3 = ta.highestbars(3)
int lb3 = ta.lowestbars(3)

if useEq
    float eqH1 = high[1]
    float eqL1 = low[1]
    int   eqT1 = time[1]
    activeHighs.checkSweep(eqH1, true, eqTolPts)
    activeLows.checkSweep(eqL1, false, eqTolPts)
    int recentEQHIdx  = -1
    int recentEQHTime = -1
    if swingHighs.size() > 0
        for i = 0 to swingHighs.size() - 1
            SwingPoint sp = swingHighs.get(i)
            if sp.checkLevel(eqH1, eqTolPts, true, bar_index, eqMinGap) == "equal" and sp.time > recentEQHTime
                recentEQHTime := sp.time
                recentEQHIdx  := i
    int recentEQLIdx  = -1
    int recentEQLTime = -1
    if swingLows.size() > 0
        for i = 0 to swingLows.size() - 1
            SwingPoint spL = swingLows.get(i)
            if spL.checkLevel(eqL1, eqTolPts, false, bar_index, eqMinGap) == "equal" and spL.time > recentEQLTime
                recentEQLTime := spL.time
                recentEQLIdx  := i
    if hb3 == -1
        swingHighs.push(SwingPoint.new(high[1], time[1], bar_index, false))
    if lb3 == -1
        swingLows.push(SwingPoint.new(low[1], time[1], bar_index, false))
    if recentEQHIdx != -1
        activeHighs.mergeOrCreate(swingHighs.get(recentEQHIdx), eqT1, eqH1, eqTolPts, true)
    if recentEQLIdx != -1
        activeLows.mergeOrCreate(swingLows.get(recentEQLIdx), eqT1, eqL1, eqTolPts, false)
    // prune consumed swing points (behavior-neutral: checkLevel skips
    // referenced ones anyway) and cap active EQ lines so the arrays
    // and drawing count stay bounded on long histories
    if swingHighs.size() > 0
        for i = swingHighs.size() - 1 to 0
            if swingHighs.get(i).referenced
                swingHighs.remove(i)
    if swingLows.size() > 0
        for i = swingLows.size() - 1 to 0
            if swingLows.get(i).referenced
                swingLows.remove(i)
    if activeHighs.size() > 100
        ActiveLine oldEqH = activeHighs.get(0)
        line.delete(oldEqH.ln)
        label.delete(oldEqH.lb)
        activeHighs.remove(0)
    if activeLows.size() > 100
        ActiveLine oldEqL = activeLows.get(0)
        line.delete(oldEqL.ln)
        label.delete(oldEqL.lb)
        activeLows.remove(0)

if lvLine.size() > 0
    for j = lvLine.size() - 1 to 0
        if not lvLive.get(j)
            continue
        line ln = lvLine.get(j)
        float price = ln.get_y1()
        ln.set_x2(time)
        bool isHigh = lvSide.get(j) == 1
        bool touched = isHigh ? high >= price : low <= price
        if touched
            lvLive.set(j, false)
            bool raided = isHigh ? high >= price + sweepBufPts : low <= price - sweepBufPts
            string tg0 = lvTag.get(j)
            bool armOk0 = str.startswith(tg0, "NY") ? armNY : str.startswith(tg0, "LO") ? armLO : armAS
            if showRaidLabels
                // float the marker clear of the wick instead of sitting on the level:
                // highs anchor above the bar's high, lows below its low, +/- labPad
                float lvY = isHigh ? math.max(high, price) + labPad : math.min(low, price) - labPad
                color lvCol = str.startswith(tg0, "NY") ? colNY : str.startswith(tg0, "LO") ? colLO : colAS
                if raided
                    label.new(time, lvY, (armOk0 ? "RAID " : "raid ") + tg0, xloc=xloc.bar_time,
                         style=isHigh ? label.style_label_down : label.style_label_up,
                         color=color.new(lvCol, armOk0 ? 15 : 55), textcolor=color.white, size=size.tiny)
                else
                    // shallow touch: quiet text-only marker, no bubble
                    label.new(time, lvY, "hit " + tg0, xloc=xloc.bar_time,
                         style=label.style_none, textcolor=color.new(color.gray, 35), size=size.tiny)
            if raided and armOk0
                armDir.push(isHigh ? -1 : 1)
                armLvl.push(price)
                armExt.push(isHigh ? high : low)
                armExp.push(time + retTtlMin * 60000)
                armI0.push(bar_index)
                armQ.push(inHtfGap)

// ── Trigger scan + FVG lifecycle ───────────────────────────────────
// Expiry pass first, then ONE inversion scan per direction. A single
// body-closed gap clears EVERY live arm of that direction: one signal
// per reversal context. (A per-arm scan that consumes one gap per arm
// fires late duplicate signals when raids stack.)
f_fireDir(int d) =>
    // newest same-direction armI0 anchors the pre-raid lookback window
    int newestI0 = -1
    if armDir.size() > 0
        for j = 0 to armDir.size() - 1
            if armDir.get(j) == d
                newestI0 := math.max(newestI0, armI0.get(j))
    bool qOk = not htfFvgOn
    if not qOk and armDir.size() > 0
        for j = 0 to armDir.size() - 1
            if armDir.get(j) == d and armQ.get(j)
                qOk := true
                break
    int hitK = -1
    if newestI0 >= 0 and qOk
        if useIfvg
            if fvgTop.size() > 0
                for k = fvgTop.size() - 1 to 0
                    if fvgInvAt.get(k) != -1
                        continue
                    if fvgIdx.get(k) < newestI0 - fvgLookback
                        break
                    if d == -1 and fvgDir.get(k) == 1 and close < fvgBot.get(k)
                        hitK := k
                        break
                    if d == 1 and fvgDir.get(k) == -1 and close > fvgTop.get(k)
                        hitK := k
                        break
        else
            for j = 0 to armDir.size() - 1
                if armDir.get(j) == d and (d == -1 ? close < armLvl.get(j) : close > armLvl.get(j))
                    hitK := -2
                    break
    hitK

f_dropDir(int d) =>
    if armDir.size() > 0
        for j = armDir.size() - 1 to 0
            if armDir.get(j) == d
                armDir.remove(j)
                armLvl.remove(j)
                armExt.remove(j)
                armExp.remove(j)
                armI0.remove(j)
                armQ.remove(j)

plotTrig = 0
if armDir.size() > 0
    for j = armDir.size() - 1 to 0
        if time > armExp.get(j)
            armDir.remove(j)
            armLvl.remove(j)
            armExt.remove(j)
            armExp.remove(j)
            armI0.remove(j)
            armQ.remove(j)
        else
            armExt.set(j, armDir.get(j) == -1 ? math.max(armExt.get(j), high) : math.min(armExt.get(j), low))

if htfFvgOn and inHtfGap and armDir.size() > 0
    for j = 0 to armDir.size() - 1
        armQ.set(j, true)

for s = 0 to 1
    int d = s == 0 ? -1 : 1
    int hitK = f_fireDir(d)
    if hitK != -1
        if hitK >= 0
            fvgInvAt.set(hitK, bar_index)
            box b = fvgBoxA.get(hitK)
            if not na(b)
                b.set_border_color(color.new(d == -1 ? colBear : colBull, 40))
                b.set_bgcolor(color.new(d == -1 ? colBear : colBull, 82))
                b.set_right(bar_index + invExtBars)
        // signal label floats 2x pad beyond the bar (clears both the wick and
        // the entry triangle); the triangle stays the precise entry marker
        float sigY = d == -1 ? high + labPad * 2 : low - labPad * 2
        label.new(time, sigY, (useIfvg ? "iFVG " : "RTN ") + (d == -1 ? "SHORT" : "LONG") + (inWin ? "" : " (outside window)"),
             xloc=xloc.bar_time, style=d == -1 ? label.style_label_down : label.style_label_up,
             color=color.new(d == -1 ? colBear : colBull, 20), textcolor=color.white, size=size.small)
        f_dropDir(d)
        if inWin
            plotTrig := d

// filled gaps die: delete box + remove from logic (inversion above already ran)
if fvgTop.size() > 0
    for k = fvgTop.size() - 1 to 0
        int inv = fvgInvAt.get(k)
        bool dead = false
        if inv != -1
            dead := bar_index > inv + invExtBars
        else
            if fvgIdx.get(k) < bar_index
                if fvgDir.get(k) == 1
                    dead := bodyFill ? close < fvgBot.get(k) : low < fvgBot.get(k)
                else
                    dead := bodyFill ? close > fvgTop.get(k) : high > fvgTop.get(k)
                if not dead and na(fvgBoxA.get(k)) == false and bar_index <= fvgIdx.get(k) + fvgExtBars
                    box b2 = fvgBoxA.get(k)
                    b2.set_right(bar_index + 1)
        if dead
            box.delete(fvgBoxA.get(k))
            fvgTop.remove(k)
            fvgBot.remove(k)
            fvgIdx.remove(k)
            fvgDir.remove(k)
            fvgInvAt.remove(k)
            fvgBoxA.remove(k)

plotshape(plotTrig == -1, "Signal short (enter next bar)", shape.triangledown, location.abovebar, color.red, size=size.small)
plotshape(plotTrig == 1, "Signal long (enter next bar)", shape.triangleup, location.belowbar, color.green, size=size.small)
bgcolor(armDir.size() > 0 ? color.new(color.yellow, 92) : na, title="Armed (raid happened, waiting for trigger)")

// ── Macro dealing range: premium/discount (merged from the standalone
// "Macro Dealing Range & Premium/Discount" indicator) ────────────────

float pdHigh = ta.highest(high, pdLookback)
float pdLow  = ta.lowest(low, pdLookback)
float pdEq   = (pdHigh + pdLow) / 2

// Boundary plots go to the Data Window only (display.data_window): the
// fills between them still render on the chart, but with no pane plots
// there are no selection dots when the indicator is clicked.
pPdHigh = plot(usePD ? pdHigh : na, "Premium Top",     color.new(colPdBear, 50), style=plot.style_linebr, display=display.data_window)
pPdEq   = plot(usePD ? pdEq   : na, "Equilibrium",     color.new(color.gray, 50), style=plot.style_linebr, display=display.data_window)
pPdLow  = plot(usePD ? pdLow  : na, "Discount Bottom", color.new(colPdBull, 50), style=plot.style_linebr, display=display.data_window)
fill(pPdHigh, pPdEq, color=colPdBear, title="Premium Zone")
fill(pPdEq, pPdLow, color=colPdBull, title="Discount Zone")

// dotted equilibrium midline as a drawing (drawings get no selection dots);
// left edge clamped to bar 0: a negative bar_index coordinate is a runtime error
var line pdEqLine = na
if usePD and barstate.islast
    line.delete(pdEqLine)
    pdEqLine := line.new(math.max(bar_index - pdLookback + 1, 0), pdEq, bar_index + 3, pdEq, color=color.new(color.gray, 45), style=line.style_dotted)

// ── Swing points (Williams fractals) ─────────────────────────────────

float swPtHi = ta.pivothigh(swingN, swingN)
float swPtLo = ta.pivotlow(swingN, swingN)
plotshape(useSwings and not na(swPtHi), "Swing high", shape.triangleup,   location.abovebar, colSwHi, offset=-swingN, size=size.tiny)
plotshape(useSwings and not na(swPtLo), "Swing low",  shape.triangledown, location.belowbar, colSwLo, offset=-swingN, size=size.tiny)

Overview

LiqSweep+iFVG tracks session highs and lows as liquidity pools, arming a potential trade setup when price sweeps beyond these levels. Reversal entry signals occur when a Fair Value Gap is closed through by bar bodies in the opposite direction of the raid within a specified time window. It plots session background boxes, liquidity level lines, raid labels, and iFVG signals directly on the main price chart.

Details

Published by

Matswm86 on GitHub

Draws

On the price chart

Markets

Any symbol

Timeframes

M1-M5, M15-H1

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

day-tradingfair-value-gapfuturesictindicatorliquidity-sweepmnqpine-scripttradingviewvwap

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
NY levelsbooltrueuseNY
nySesssession0930-1600nySess
London levelsbooltrueuseLO
loSesssession0300-1100loSess
Asia levelsbooltrueuseAS
asSesssession2000-0100asSess
NY raids armbooltruearmNY
London raids armbooltruearmLO
Asia raids armbooltruearmAS
Show session boxesbooltrueshowBoxes
Session box transparencyint94sessTransp
Keep drawings for N sessions per typeint30maxDays
Show all 40 settings
SettingTypeDefaultVariable
Show level linesbooltrueshowLevels
Show RAID / hit labelsbooltrueshowRaidLabels
Untouched levels kept live per session typeint1liveDepth
Trigger after a raidstringiFVG inversionentryMode
Min raid beyond level (points)float0.25sweepBufPts
Trigger window after raid (minutes)int60retTtlMin
Active entry window (NY tz)session0100-1500entryWin
Track equal highs / lowsbooltrueuseEq
Tolerance (points)float1.5eqTolPts
Minimum bars before an equal matchint3eqMinGap
Raids of EQH/EQL also ARMboolfalseeqArm
EQH/EQL colorcolorcolor.redcolEq
Minimum FVG size (points)float1.0minFvgPts
FVG fill rule (gap death)stringBody close throughfvgFillRule
FVGs eligible from N bars before raidint30fvgLookback
Extend live gap boxes N barsint30fvgExtBars
Keep inverted gap visible N barsint60invExtBars
Show FVG boxesboolfalseshowFvg
Require price inside a higher-TF FVGboolfalsehtfFvgOn
Gap timeframestring15htfFvgTf
Show higher-TF gap boxesboolfalsehtfFvgShow
Higher-TF gap colorcolorcolor.new(color.aqua, 0)colHtfFvg
transparencyint93htfTransp
Show premium/discount zonesbooltrueusePD
Dealing range lookback (bars)int50pdLookback
Premiumcolorcolor.new(#a65c4f, 85)colPdBear
Discountcolorcolor.new(#7f9a65, 85)colPdBull
Mark swing pointsbooltrueuseSwings
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Golden Bullet Strategy

by TradersPost
228 stars

The Golden Bullet Strategy is an overlay signal indicator based on Smart Money Concepts and time-based liquidity models. It identifies liquidity sweeps of a designated reference session range during a specified hunt window. It then confirms Market Structure Sh

Indicator v6 SMC / ICT / price actionSessions & time
Updated 4 months ago · None stated GitHub repository of Golden Bullet Strategy

This indicator detects and draws the first Fair Value Gap (FVG) that forms in each hourly session based on a selected lower timeframe, with specialized handling for Regular Trading Hours (RTH) confluence windows. It draws FVG range boxes, midpoint lines, hourl

Indicator v5 SMC / ICT / price actionSupport & resistance Repaints

This indicator combines six trading tools into a single chart overlay to optimize indicator limits. It calculates Bollinger Bands, projects weekend price boundaries, plots market structure elements like order blocks, breaker blocks, and MSB lines, marks New Yo

Indicator v6 Support & resistanceSMC / ICT / price action Repaints
34 stars

ICT Everything is a technical analysis indicator that plots Inner Circle Trader (ICT) session ranges, midnight open price lines, and historical session markers directly on the price chart. It highlights major trading sessions including London, New York, London

Indicator v5 SMC / ICT / price actionSessions & time Repaints
Updated 2 weeks ago · MIT GitHub repository of ICT Everything @coldbrewrosh

SMC Marks

by kxngHADES
34 stars

This Pine Script indicator automatically marks Smart Money Concepts on the price chart. It identifies swing highs and lows as HH, HL, LH, LL using a configurable swing length. It detects breaks of market structure (BMS/BOS) and changes of character (CHoCH), wi

Indicator v6 SMC / ICT / price actionTrend
Updated 8 weeks ago · None stated GitHub repository of SMC Marks

More SMC / ICT scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers