SMC Liquidity PRO | jjart

jjart · study · 478 行 · 点赞 265 · TradingView 原页

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

Pine Script

//@version=6
indicator("SMC Liquidity PRO | jjart | Smart Money FVG iFVG BPR Liquidity Sweeps OB", "SMC Liquidity PRO | jjart", overlay=true, max_boxes_count=450, max_lines_count=450, max_labels_count=450, max_bars_back=1000)
// Independent integration of structure, sweep, imbalance, order-block and sentiment concepts.
// BAP = optional custom Body Acceleration Pocket (not a standardized ICT definition).
 
string G1 = "01 | Market Structure"
showSwing = input.bool(true, "HH / HL / LH / LL (Major Swings)", group=G1, tooltip="Show confirmed major pivots. Recommended: On for readable market structure.")
showSub = input.bool(false, "Internal High / Low", group=G1, tooltip="Show intermediate pivots. Recommended: On for 15m/1h, Off if busy.")
showMinor = input.bool(false, "Micro High / Low", group=G1, tooltip="Show very short swings. Recommended: Off for a clean chart.")
swingLen = input.int(18, "Swing Pivot Length", minval=2, maxval=150, group=G1, tooltip="Left and right candles required to confirm a major pivot. 12-24 recommended; pivot labels appear after confirmation.")
subLen = input.int(6, "Internal Pivot Length", minval=2, maxval=75, group=G1, tooltip="Shorter structure confirmation in bars. Recommended: 5-8.")
minorLen = input.int(2, "Micro Pivot Length", minval=1, maxval=20, group=G1, tooltip="Micro pivot length in bars. Recommended: 2-3, only with Micro enabled.")
showBreaks = input.bool(true, "Show BOS / CHOCH", group=G1, tooltip="Mark close-confirmed breaks of major swings. Recommended: On.")
atrMult = input.float(0.12, "Structure Break ATR Buffer", minval=0, step=0.02, group=G1, tooltip="Close must exceed prior swing by this ATR multiple. Recommended: 0.10-0.25; higher removes marginal breaks.")
showStructureTags = input.bool(true, "Show HH / HL / LH / LL Tags", group=G1, tooltip="Classify confirmed major swing points relative to the preceding swing of the same type. Recommended: On.")
maxStructureMarks = input.int(24, "Maximum Visible Swing Labels", minval=4, maxval=100, group=G1, tooltip="Older pivot labels are deleted automatically. Recommended: 16-30.")
string G2 = "02 | Liquidity Sweeps"
showSweeps = input.bool(true, "Active BSL / SSL Sweep Levels", group=G2, tooltip="Wick beyond major pivot with close back inside. Recommended: On.")
showEQ = input.bool(false, "Show EQH / EQL", group=G2, tooltip="Show nearby equal internal pivots, within ATR tolerance. Recommended: On.")
eqAtr = input.float(0.15, "Equal Levels ATR Tolerance", minval=0.01, step=0.01, group=G2, tooltip="Maximum distance between matching pivots in ATR units. Recommended: 0.10-0.20.")
sweepLife = input.int(90, "Sweep Line Maximum Age (Bars)", minval=5, maxval=500, group=G2, tooltip="Remove sweep levels after this age even without a retest. Recommended: 60-120.")
showSweepArea = input.bool(true, "Show Grey Liquidity Sweep Area", group=G2, tooltip="Draw a subtle grey band between swept liquidity level and wick extreme, similar to SANCHO's sweep highlight. Recommended: On.")
sweepGrey = input.color(#A1A6AF, "Liquidity Sweep Area Grey", group=G2, tooltip="Neutral grey for the swept wick region. Recommended: cool medium grey.")
sweepOpacity = input.int(84, "Sweep Area Transparency %", minval=50, maxval=98, group=G2, tooltip="Higher values make the grey sweep area more subtle. Recommended: 82-90.")
sweepRetestPct = input.float(50.0, "Sweep Area Retest Depth %", minval=1, maxval=100, step=5, group=G2, tooltip="Remove a sweep on a later bar once price enters this percentage of its wick band. Recommended: 50%; 1 = remove at first touch.")
maxSweepLines = input.int(8, "Maximum Active Sweep Levels", minval=1, maxval=30, group=G2, tooltip="Cap active sweep lines to prevent clutter. Recommended: 5-10.")
string G3 = "03 | Imbalance Zones"
showFVG = input.bool(true, "Fair Value Gaps (FVG)", group=G3, tooltip="Three-candle non-overlap imbalance. Recommended: On.")
showGAP = input.bool(false, "Session / Candle Gaps (GAP)", group=G3, tooltip="Adjacent-candle true price gaps. Recommended: On for equities; optional for 24/7 crypto.")
showBAP = input.bool(false, "Body Acceleration Pockets (BAP*)", group=G3, tooltip="CUSTOM: disjoint candle bodies with overlapping wicks and displacement. Not a standardized ICT pattern. Recommended: Off initially.")
showIFVG = input.bool(true, "Inverted FVG (iFVG)", group=G3, tooltip="A fully broken FVG switches polarity on a confirmed closing break. Recommended: On.")
showBPR = input.bool(true, "Balanced Price Ranges (BPR)", group=G3, tooltip="Exact overlap of bullish and bearish FVGs. Recommended: On.")
minZoneATR = input.float(0.10, "Minimum Zone Height / ATR", minval=0, step=0.05, group=G3, tooltip="Reject small gaps relative to ATR. Recommended: 0.10-0.25.")
displacementATR = input.float(0.75, "BAP Body Displacement / ATR", minval=0.1, step=0.05, group=G3, tooltip="Strong candle body required for custom BAP. Recommended: 0.75-1.25.")
fillLimit = input.float(60.0, "Remove Standard Zones At Fill %", minval=5, maxval=100, step=5, group=G3, tooltip="Hide ordinary FVG/GAP/BAP when wick penetration reaches this fraction of original range. Recommended: 60%. iFVG/BPR use close invalidation instead.")
maxZones = input.int(32, "Maximum Active Zones", minval=10, maxval=110, group=G3, tooltip="Bound memory and drawings. Recommended: 40-70 for most charts.")
zoneLife = input.int(200, "Maximum Zone Age (Bars)", minval=20, maxval=1500, group=G3, tooltip="Remove stale zones after this many bars. Recommended: 200-500.")
projectBars = input.int(18, "Extend Zones Right (Bars)", minval=5, maxval=100, group=G3, tooltip="Project zones into future. Recommended: 12-25.")
labelInset = input.int(5, "Label Padding From Right (Bars)", minval=2, maxval=25, group=G3, tooltip="Inset labels from far-right border. Recommended: 4-7.")
showCE = input.bool(false, "Show 50% Equilibrium Lines", group=G3, tooltip="Dotted 50% line of ORIGINAL zone boundaries. Recommended: Off for clean display.")
inversionMode = input.string("Break Only", "iFVG Confirmation Mode", options=["Break + Retest", "Break Only"], group=G3, tooltip="Break + Retest: after confirmed FVG break, show its inversion only when price later retests the zone from the other side and rejects it. Break Only: show inversion immediately. Recommended: Break + Retest.")
showRetestMarks = input.bool(true, "Mark Confirmed iFVG Retests", group=G3, tooltip="Display a small diamond on the candle that confirms the inversion retest. Recommended: On.")
string G4 = "04 | Order Blocks & Confluence"
showOB = input.bool(true, "Show Displacement Order Blocks", group=G4, tooltip="Independent conventional order-block logic: last bearish candle before upward displacement = bullish demand OB, and vice versa. Recommended: On.")
obDisplacement = input.float(0.35, "Order Block Displacement / ATR", minval=0.2, maxval=4, step=0.1, group=G4, tooltip="Minimum ATR displacement beyond origin candle. Recommended 0.3-0.7 to detect more valid blocks.")
obLookback = input.int(8, "OB Origin Search (Bars)", minval=1, maxval=25, group=G4, tooltip="Find the last opposite candle within this many previous candles, not just candle [1]. Recommended 6-10.")
obLife = input.int(450, "OB Maximum Age (Bars)", minval=30, maxval=1500, group=G4, tooltip="Order blocks are monitored separately from imbalances. Recommended 300-600.")
obMitigation = input.float(90.0, "Remove OB After Fill (%)", minval=50, maxval=100, step=5, group=G4, tooltip="Hide order blocks after this depth of mitigation, or if their far boundary is broken by a close. Recommended 85-95%.")
maxOB = input.int(28, "Maximum Order Blocks", minval=5, maxval=80, group=G4, tooltip="Independent OB capacity. Prevents FVGs from evicting valid order blocks. Recommended 20-35.")
showConfluence = input.bool(false, "Show Sweep + BOS + Gap Confluence", group=G4, tooltip="Educational watch marker when liquidity sweep, structure break and fresh imbalance align. Not a backtested entry signal.")
setupWindow = input.int(14, "Sweep Confluence Window (Bars)", minval=1, maxval=100, group=G4, tooltip="Maximum bars between prior sweep and confirmed break. Recommended: 10-20.")
string G5 = "05 | Fear & Greed (Chart Labels Only)"
showFG = input.bool(true, "Show Extreme Fear / Greed Labels", group=G5, tooltip="Only chart labels on threshold crossings; NO oscillator or separate pane. Recommended: On.")
rsiLen = input.int(14, "Momentum RSI Length", minval=1, group=G5, tooltip="RSI-based 1/3 sentiment component. Recommended: 14.")
trdLen = input.int(50, "Trend SMA Length", minval=2, group=G5, tooltip="Price/SMA distance-based 1/3 component. Recommended: 50.")
flowLen = input.int(20, "Volume Flow Length", minval=2, group=G5, tooltip="Candle-direction volume share-based 1/3 component. Recommended: 20. Proxy sentiment, NOT external CNN index.")
obLvl = input.int(70, "Extreme Greed Threshold", minval=55, maxval=100, group=G5, tooltip="Label only on crossing above this composite score. Recommended: 70.")
osLvl = input.int(30, "Extreme Fear Threshold", minval=0, maxval=45, group=G5, tooltip="Label only on crossing below this composite score. Recommended: 30.")
fgCooldown = input.int(8, "Sentiment Label Cooldown (Bars)", minval=1, maxval=100, group=G5, tooltip="Suppress excessive repeats. Recommended: 8-15 bars.")
showFGText = input.bool(true, "Show FEAR/GREED Score Next To Dot", group=G5, tooltip="Show score as green/red text next to a circular marker. Recommended: On; turn Off for dots only.")
string G6 = "06 | Pastel Appearance"
bullColor = input.color(#A9D9F2, "Bullish Sky-Blue", group=G6, tooltip="Fill and marks for bullish zones. Recommended: pastel sky blue.")
bearColor = input.color(#F3DEA4, "Bearish Soft Yellow", group=G6, tooltip="Fill and marks for bearish zones. Recommended: muted warm pastel yellow.")
bprColor = input.color(#C7B8EB, "BPR Accent Lavender", group=G6, tooltip="BPR border accent; fill always follows bullish/bearish blue/yellow rule.")
invColor = input.color(#B9C7E6, "iFVG Accent Periwinkle", group=G6, tooltip="iFVG border accent; fill always follows current direction.")
gapColor = input.color(#EACFA7, "Sweep / EQ Accent", group=G6, tooltip="Accent for sweep and equal-level markers.")
bapColor = input.color(#D9C5DD, "BAP Accent", group=G6, tooltip="Accent for custom BAP borders, not directional fill.")
textColor = input.color(#455367, "Label Text", group=G6, tooltip="Dark desaturated text works on both dark and light charts. Recommended default.")
obBullColor = input.color(#3579DA, "Bullish Order Block Blue", group=G6, tooltip="More saturated blue exclusively for bullish order blocks. Recommended: medium royal blue; independent of sky-blue FVG colors.")
obBearColor = input.color(#DA5361, "Bearish Order Block Red", group=G6, tooltip="More saturated red exclusively for bearish order blocks. Recommended: medium muted red; independent of soft-yellow FVG colors.")
obTransparency = input.int(72, "Order Block Transparency %", minval=25, maxval=95, group=G6, tooltip="Opacity of bullish-blue and bearish-red order blocks. Recommended: 68-78 for good separation from FVG.")
fillTransparency = input.int(78, "Zone Fill Transparency %", minval=20, maxval=95, group=G6, tooltip="Pastel zone transparency; higher = more transparent. Recommended: 75-85.")
atr = ta.atr(14)
float threshold = atr * atrMult
float tolerance = atr * eqAtr
 
// Confirmed pivots are deliberately delayed by their strength value.
float sh = ta.pivothigh(high, swingLen, swingLen)
float sl = ta.pivotlow(low, swingLen, swingLen)
float uh = ta.pivothigh(high, subLen, subLen)
float ul = ta.pivotlow(low, subLen, subLen)
float mh = ta.pivothigh(high, minorLen, minorLen)
float ml = ta.pivotlow(low, minorLen, minorLen)
 
var float lastSwingH = na
var float lastSwingL = na
var float prevSwingH = na
var float prevSwingL = na
var float lastSubH = na
var float lastSubL = na
var int swingHBar = na
var int swingLBar = na
var bool swingHBroken = false
var bool swingLBroken = false
var int trend = 0
var array<label> swingMarks = array.new<label>()
var array<label> breakMarks = array.new<label>()
var array<line> breakLines = array.new<line>()
 
if barstate.isconfirmed and not na(sh)
    string tagH = na(prevSwingH) ? "H" : sh > prevSwingH ? "HH" : sh < prevSwingH ? "LH" : "EQH"
    if showSwing and showStructureTags
        swingMarks.push(label.new(bar_index-swingLen, sh, tagH, style=label.style_label_down, color=color.new(bearColor, 42), textcolor=textColor, size=size.tiny))
    prevSwingH := sh
    lastSwingH := sh
    swingHBar := bar_index-swingLen
    swingHBroken := false
if barstate.isconfirmed and not na(sl)
    string tagL = na(prevSwingL) ? "L" : sl > prevSwingL ? "HL" : sl < prevSwingL ? "LL" : "EQL"
    if showSwing and showStructureTags
        swingMarks.push(label.new(bar_index-swingLen, sl, tagL, style=label.style_label_up, color=color.new(bullColor, 40), textcolor=textColor, size=size.tiny))
    prevSwingL := sl
    lastSwingL := sl
    swingLBar := bar_index-swingLen
    swingLBroken := false
while swingMarks.size() > maxStructureMarks
    label.delete(swingMarks.shift())
if barstate.isconfirmed and not na(uh)
    if showSub
        swingMarks.push(label.new(bar_index-subLen, uh, "h", style=label.style_none, textcolor=bearColor, size=size.tiny))
    if showEQ and not na(lastSubH) and math.abs(uh-lastSubH) <= tolerance
        swingMarks.push(label.new(bar_index-subLen, uh, "EQH", style=label.style_none, textcolor=gapColor, size=size.tiny))
    lastSubH := uh
if barstate.isconfirmed and not na(ul)
    if showSub
        swingMarks.push(label.new(bar_index-subLen, ul, "l", style=label.style_none, textcolor=bullColor, size=size.tiny))
    if showEQ and not na(lastSubL) and math.abs(ul-lastSubL) <= tolerance
        swingMarks.push(label.new(bar_index-subLen, ul, "EQL", style=label.style_none, textcolor=gapColor, size=size.tiny))
    lastSubL := ul
if showMinor and barstate.isconfirmed and not na(mh)
    swingMarks.push(label.new(bar_index-minorLen, mh, "·", style=label.style_none, textcolor=bearColor, size=size.tiny))
if showMinor and barstate.isconfirmed and not na(ml)
    swingMarks.push(label.new(bar_index-minorLen, ml, "·", style=label.style_none, textcolor=bullColor, size=size.tiny))
while swingMarks.size() > maxStructureMarks
    label.delete(swingMarks.shift())
 
bool breakUp = barstate.isconfirmed and not na(lastSwingH) and not swingHBroken and close > lastSwingH+threshold
bool breakDown = barstate.isconfirmed and not na(lastSwingL) and not swingLBroken and close < lastSwingL-threshold
bool chochUp = breakUp and trend == -1
bool chochDown = breakDown and trend == 1
if breakUp
    swingHBroken := true
    if showBreaks
        breakLines.push(line.new(swingHBar, lastSwingH, bar_index, lastSwingH, color=color.new(#377BBB, 0), style=line.style_dashed, width=1))
        breakMarks.push(label.new(int(math.floor((swingHBar+bar_index)/2)), lastSwingH, chochUp ? "CHoCH ↑" : "BOS ↑", style=label.style_none, textcolor=#5299BA, size=size.tiny))
    trend := 1
if breakDown
    swingLBroken := true
    if showBreaks
        breakLines.push(line.new(swingLBar, lastSwingL, bar_index, lastSwingL, color=color.new(#BF6670, 0), style=line.style_dashed, width=1))
        breakMarks.push(label.new(int(math.floor((swingLBar+bar_index)/2)), lastSwingL, chochDown ? "CHoCH ↓" : "BOS ↓", style=label.style_none, textcolor=#AD9360, size=size.tiny))
    trend := -1
while breakLines.size() > 12
    line.delete(breakLines.shift())
while breakMarks.size() > 12
    label.delete(breakMarks.shift())
 
// A sweep level is maintained until a LATER candle revisits its exact wick level.
type Sweep
    float level
    int born
    bool bull
    float innerLevel
    float outerLevel
    line ln
    box area
var array<Sweep> sweepLevels = array.new<Sweep>()
var int recentBullSweep = na
var int recentBearSweep = na
if barstate.isconfirmed and sweepLevels.size() > 0
    for i = sweepLevels.size()-1 to 0
        Sweep sw = sweepLevels.get(i)
        float retestPrice = sw.bull ? sw.innerLevel - (sw.innerLevel-sw.outerLevel)*sweepRetestPct/100.0 : sw.innerLevel + (sw.outerLevel-sw.innerLevel)*sweepRetestPct/100.0
        bool retested = bar_index > sw.born and (sw.bull ? low <= retestPrice : high >= retestPrice)
        bool old = bar_index-sw.born > sweepLife
        if retested or old
            line.delete(sw.ln)
            box.delete(sw.area)
            sweepLevels.remove(i)
        else
            line.set_x2(sw.ln, bar_index+projectBars)
            if not na(sw.area)
                box.set_right(sw.area, bar_index+projectBars)
bool sweepH = barstate.isconfirmed and showSweeps and not na(lastSwingH) and not swingHBroken and high > lastSwingH and close < lastSwingH and close[1] <= lastSwingH
bool sweepL = barstate.isconfirmed and showSweeps and not na(lastSwingL) and not swingLBroken and low < lastSwingL and close > lastSwingL and close[1] >= lastSwingL
if sweepH
    recentBearSweep := bar_index
    line ln = line.new(bar_index, lastSwingH, bar_index+projectBars, lastSwingH, color=color.new(sweepGrey, 15), style=line.style_dashed, width=1)
    box area = showSweepArea ? box.new(bar_index, high, bar_index+projectBars, lastSwingH, border_color=color.new(sweepGrey, 70), bgcolor=color.new(sweepGrey, sweepOpacity)) : na
    sweepLevels.push(Sweep.new(lastSwingH, bar_index, false, lastSwingH, high, ln, area))
if sweepL
    recentBullSweep := bar_index
    line ln = line.new(bar_index, lastSwingL, bar_index+projectBars, lastSwingL, color=color.new(sweepGrey, 15), style=line.style_dashed, width=1)
    box area = showSweepArea ? box.new(bar_index, lastSwingL, bar_index+projectBars, low, border_color=color.new(sweepGrey, 70), bgcolor=color.new(sweepGrey, sweepOpacity)) : na
    sweepLevels.push(Sweep.new(lastSwingL, bar_index, true, lastSwingL, low, ln, area))
while sweepLevels.size() > maxSweepLines
    Sweep sw = sweepLevels.shift()
    line.delete(sw.ln)
    box.delete(sw.area)
 
// Local sentiment proxy adapted from the three-factor methodology supplied in the user reference.
float momentum = nz(ta.rsi(close, rsiLen), 50.0)
float trendSma = ta.sma(close, trdLen)
float trendDist = na(trendSma) or trendSma == 0 ? 0.0 : (close - trendSma) / trendSma * 100.0
float trendFactor = math.max(0.0, math.min(100.0, 50.0 + trendDist * 4.0))
float totalFlow = ta.sma(nz(volume, 0), flowLen)
float bullishFlow = ta.sma(close >= open ? nz(volume, 0) : 0.0, flowLen)
float volumeFactor = totalFlow > 0 ? bullishFlow / totalFlow * 100.0 : 50.0
float fg = (momentum + trendFactor + volumeFactor) / 3.0
var int lastFgBar = na
var array<label> fgMarks = array.new<label>()
bool crossedGreed = ta.crossover(fg, obLvl)
bool crossedFear = ta.crossunder(fg, osLvl)
bool greedSignal = showFG and barstate.isconfirmed and crossedGreed and (na(lastFgBar) or bar_index-lastFgBar > fgCooldown)
bool fearSignal = showFG and barstate.isconfirmed and crossedFear and (na(lastFgBar) or bar_index-lastFgBar > fgCooldown)
if greedSignal
    fgMarks.push(label.new(bar_index, high, "●", style=label.style_none, textcolor=#20B65A, size=size.normal))
    if showFGText
        fgMarks.push(label.new(bar_index, high+atr*0.22, "GREED " + str.tostring(math.round(fg)), style=label.style_none, textcolor=#169D48, size=size.tiny))
    lastFgBar := bar_index
if fearSignal
    fgMarks.push(label.new(bar_index, low, "●", style=label.style_none, textcolor=#E14A4A, size=size.normal))
    if showFGText
        fgMarks.push(label.new(bar_index, low-atr*0.22, "FEAR " + str.tostring(math.round(fg)), style=label.style_none, textcolor=#D83C3C, size=size.tiny))
    lastFgBar := bar_index
 
while fgMarks.size() > 35
    label.delete(fgMarks.shift())
 
// Zone types: 1=FVG 2=GAP 3=custom BAP 4=iFVG 5=BPR 6=standard OB 7=structure-confirmed OB.
type Zone
    float top
    float bottom
    float remainingTop
    float remainingBottom
    int direction
    int kind
    int born
    int left
    box outline
    box filling
    line midpoint
    label tag
    bool pending = false
 
var array<Zone> zones = array.new<Zone>()
// Hidden FVGs remain monitored for a later closing-break inversion, despite the 60% visual cleanup.
type DormantFVG
    float top
    float bottom
    int dir
    int born
var array<DormantFVG> dormantFVGs = array.new<DormantFVG>()
f_color(int direction) =>
    direction == 1 ? bullColor : bearColor
f_title(int kind) =>
    kind == 1 ? "FVG" : kind == 2 ? "GAP" : kind == 3 ? "BAP*" : kind == 4 ? "iFVG" : kind == 5 ? "BPR" : kind == 7 ? "OB ★" : "OB"
f_delete(Zone z) =>
    box.delete(z.outline)
    box.delete(z.filling)
    line.delete(z.midpoint)
    label.delete(z.tag)
f_add(float top, float bottom, int dir, int kind, int leftBar) =>
    if not na(top) and not na(bottom) and top > bottom and top-bottom >= syminfo.mintick
        color col = (kind == 6 or kind == 7) ? (dir == 1 ? obBullColor : obBearColor) : f_color(dir)
        color edge = (kind == 6 or kind == 7) ? col : kind == 5 ? bprColor : kind == 4 ? invColor : kind == 3 ? bapColor : color.new(col, 20)
        int transp = (kind == 6 or kind == 7) ? (kind == 7 ? math.max(25, obTransparency - 17) : obTransparency) : fillTransparency
        int right = bar_index + projectBars
        box outline = box.new(leftBar, top, right, bottom, border_color=color.new(edge, 18), border_width=kind == 7 ? 2 : 1, bgcolor=color.new(col, 100))
        box filling = box.new(leftBar, top, right, bottom, border_color=color.new(col, 100), bgcolor=color.new(col, transp))
        line mid = line.new(leftBar, (top+bottom)/2, right, (top+bottom)/2, style=line.style_dotted, color=showCE ? color.new(edge, 40) : color.new(edge, 100))
        label tag = label.new(math.max(leftBar+1, right-labelInset), (top+bottom)/2, f_title(kind) + (dir == 1 ? " ↑" : " ↓"), style=label.style_none, color=color.new(col, 100), textcolor=textColor, size=size.tiny)
        zones.push(Zone.new(top, bottom, top, bottom, dir, kind, bar_index, leftBar, outline, filling, mid, tag, false))
        // Per-family capacity prevents frequent FVGs from evicting order blocks.
        int obCount = 0
        int regularCount = 0
        for zz in zones
            if zz.kind >= 6
                obCount += 1
            else
                regularCount += 1
        int ii = 0
        while obCount > maxOB and ii < zones.size()
            Zone zz = zones.get(ii)
            if zz.kind >= 6
                f_delete(zz)
                zones.remove(ii)
                obCount -= 1
            else
                ii += 1
        ii := 0
        while regularCount > maxZones and ii < zones.size()
            Zone zz = zones.get(ii)
            if zz.kind < 6
                f_delete(zz)
                zones.remove(ii)
                regularCount -= 1
            else
                ii += 1
 
// Evaluate old zones before creating new ones, so the creation candle never mitigates itself.
if barstate.isconfirmed and zones.size() > 0
    for i = zones.size()-1 to 0
        Zone z = zones.get(i)
        float height = z.top-z.bottom
        bool penetrated = z.direction == 1 ? low < z.top : high > z.bottom
        float depth = z.direction == 1 ? (z.top-math.max(low,z.bottom))/height*100.0 : (math.min(high,z.top)-z.bottom)/height*100.0
        float portion = math.max(0.0, math.min(100.0, depth))
        float oldPortion = z.direction == 1 ? (z.top-z.remainingTop)/height*100.0 : (z.remainingBottom-z.bottom)/height*100.0
        float cumulativeFill = math.max(portion, oldPortion)
        bool broken = z.direction == 1 ? close < z.bottom : close > z.top
        bool isOB = z.kind >= 6
        bool aged = bar_index-z.born > (isOB ? obLife : zoneLife)
        bool inverted = z.kind == 4
        bool balanced = z.kind == 5
        // iFVG and BPR are managed by closing-break invalidation, not the ordinary 65% rule.
        bool retire = aged or broken or (isOB ? cumulativeFill >= obMitigation : (not inverted and not balanced and cumulativeFill >= fillLimit))
        if retire
            // An FVG only becomes an iFVG after a CONFIRMED close beyond its far boundary.
            bool flip = z.kind == 1 and broken and showIFVG and not aged
            float origTop = z.top
            float origBot = z.bottom
            int origDir = z.direction
            if z.kind == 1 and not broken and not aged and showIFVG
                dormantFVGs.push(DormantFVG.new(z.top, z.bottom, z.direction, z.born))
                while dormantFVGs.size() > 60
                    dormantFVGs.shift()
            f_delete(z)
            zones.remove(i)
            if flip
                f_add(origTop, origBot, -origDir, 4, bar_index)
                if inversionMode == "Break + Retest" and zones.size() > 0
                    Zone inv = zones.last()
                    inv.pending := true
                    box.set_bgcolor(inv.filling, color.new(invColor, 100))
                    box.set_border_color(inv.outline, color.new(invColor, 100))
                    label.set_text(inv.tag, "")
        else
            // Pending inversions are hidden until a subsequent bar retests and rejects the flipped zone.
            if inverted and z.pending and bar_index > z.born
                bool touched = high >= z.bottom and low <= z.top
                bool rejected = z.direction == 1 ? close > z.top : close < z.bottom
                if touched and rejected
                    z.pending := false
                    if showRetestMarks
                        label.new(bar_index, z.direction == 1 ? low : high, "◇", style=label.style_none, textcolor=z.direction == 1 ? #4B9FC7 : #B39A55, size=size.small)
                    box.set_bgcolor(z.filling, color.new(f_color(z.direction), fillTransparency))
                    box.set_border_color(z.outline, invColor)
                    label.set_text(z.tag, "iFVG " + (z.direction == 1 ? "↑" : "↓"))
            if penetrated and not z.pending
                // Preserve ORIGINAL outline; move filled rectangle edge to the furthest wick reached.
                if z.direction == 1
                    z.remainingTop := math.min(z.remainingTop, math.max(z.bottom, low))
                else
                    z.remainingBottom := math.max(z.remainingBottom, math.min(z.top, high))
            int right = bar_index + projectBars
            box.set_right(z.outline, right)
            box.set_right(z.filling, right)
            box.set_top(z.filling, z.remainingTop)
            box.set_bottom(z.filling, z.remainingBottom)
            // Never paint a zero-height / fully mitigated body.
            if z.remainingTop - z.remainingBottom <= syminfo.mintick
                box.set_bgcolor(z.filling, color.new(f_color(z.direction), 100))
            line.set_x2(z.midpoint, right)
            label.set_x(z.tag, math.max(z.left+1, right-labelInset))
 
// Confirm inverted FVGs from previously hidden (>=60% mitigated) gaps.
// They are not drawn until a later candle CLOSES beyond the original far edge.
if barstate.isconfirmed and dormantFVGs.size() > 0
    for k = dormantFVGs.size()-1 to 0
        DormantFVG d = dormantFVGs.get(k)
        bool expired = bar_index-d.born > zoneLife
        bool flipped = d.dir == 1 ? close < d.bottom : close > d.top
        if expired or flipped
            dormantFVGs.remove(k)
            if flipped and not expired and showIFVG
                f_add(d.top, d.bottom, -d.dir, 4, bar_index)
                if inversionMode == "Break + Retest" and zones.size() > 0
                    Zone inv = zones.last()
                    inv.pending := true
                    box.set_bgcolor(inv.filling, color.new(invColor, 100))
                    box.set_border_color(inv.outline, color.new(invColor, 100))
                    label.set_text(inv.tag, "")
 
// Non-overlapping 3-candle FVG; session gap only if adjacent candles have no overlapping range.
bool bullFvg = barstate.isconfirmed and low > high[2] and close[1] > high[2] and (low-high[2]) >= atr*minZoneATR
bool bearFvg = barstate.isconfirmed and high < low[2] and close[1] < low[2] and (low[2]-high) >= atr*minZoneATR
bool bullGap = barstate.isconfirmed and low > high[1] and (low-high[1]) >= atr*minZoneATR
bool bearGap = barstate.isconfirmed and high < low[1] and (low[1]-high) >= atr*minZoneATR
float prevBodyHi = math.max(open[1],close[1])
float prevBodyLo = math.min(open[1],close[1])
float curBodyHi = math.max(open,close)
float curBodyLo = math.min(open,close)
bool bullBap = barstate.isconfirmed and curBodyLo > prevBodyHi and low <= high[1] and close > open and math.abs(close-open) >= atr*displacementATR and curBodyLo-prevBodyHi >= atr*minZoneATR
bool bearBap = barstate.isconfirmed and curBodyHi < prevBodyLo and high >= low[1] and close < open and math.abs(close-open) >= atr*displacementATR and prevBodyLo-curBodyHi >= atr*minZoneATR
 
// Opposing FVG overlap yields exact BPR intersection; do not merge unrelated same-direction gaps.
if barstate.isconfirmed and (bullFvg or bearFvg)
    int dir = bullFvg ? 1 : -1
    float top = bullFvg ? low : low[2]
    float bottom = bullFvg ? high[2] : high
    bool createdBpr = false
    float bprTop = na
    float bprBottom = na
    if showBPR and zones.size() > 0
        for j=zones.size()-1 to 0
            Zone old = zones.get(j)
            if not createdBpr and old.kind == 1 and old.direction == -dir and bar_index-old.born <= 35
                float overlapTop = math.min(top, old.top)
                float overlapBottom = math.max(bottom, old.bottom)
                if overlapTop > overlapBottom and overlapTop-overlapBottom >= atr*minZoneATR
                    bprTop := overlapTop
                    bprBottom := overlapBottom
                    createdBpr := true
    if createdBpr
        f_add(bprTop, bprBottom, dir, 5, bar_index-2)
    if showFVG and not (bullGap or bearGap)
        f_add(top, bottom, dir, 1, bar_index-2)
if showGAP and bullGap
    f_add(low, high[1], 1, 2, bar_index-1)
if showGAP and bearGap
    f_add(low[1], high, -1, 2, bar_index-1)
if showBAP and bullBap and not bullGap
    f_add(curBodyLo, prevBodyHi, 1, 3, bar_index-1)
if showBAP and bearBap and not bearGap
    f_add(prevBodyLo, curBodyHi, -1, 3, bar_index-1)
 
// OB v6: scan several preceding candles; include wick from the confirming candle.
// A structural break upgrades the block to bright blue/red (kind 7).
// This models demand below upward displacement and supply above downward displacement.
// An origin index is used once, so later displacement candles do not duplicate the same OB.
var array<int> usedObOrigins = array.new<int>()
if showOB and barstate.isconfirmed and not na(atr) and bar_index > obLookback + 5
    for direction = -1 to 1 by 2
        bool directionCandle = direction == 1 ? close > open : close < open
        int originOffset = na
        if directionCandle
            for q = 1 to obLookback
                bool originOpposite = direction == 1 ? close[q] < open[q] : close[q] > open[q]
                bool passed = direction == 1 ? close > high[q] + atr * obDisplacement : close < low[q] - atr * obDisplacement
                if originOpposite and passed
                    originOffset := q
                    break
        if not na(originOffset)
            int originKey = (bar_index - originOffset) * 2 + (direction == 1 ? 1 : 0)
            bool alreadyUsed = usedObOrigins.includes(originKey)
            // The block is the origin candle plus the relevant confirming candle's wick.
            float obTop = direction == 1 ? high[originOffset] : math.max(high[originOffset], high)
            float obBottom = direction == 1 ? math.min(low[originOffset], low) : low[originOffset]
            // Reject zones already closed through between origin and confirmation.
            bool valid = true
            for j = 1 to obLookback
                if j < originOffset
                    bool crossedFarSide = direction == 1 ? close[j] < obBottom : close[j] > obTop
                    if crossedFarSide
                        valid := false
            if not alreadyUsed and valid and obTop > obBottom
                bool structural = direction == 1 ? (breakUp or (not na(lastSwingL) and math.abs(low[originOffset] - lastSwingL) <= atr * 0.35)) : (breakDown or (not na(lastSwingH) and math.abs(high[originOffset] - lastSwingH) <= atr * 0.35))
                f_add(obTop, obBottom, direction, structural ? 7 : 6, bar_index - originOffset)
                usedObOrigins.push(originKey)
                if usedObOrigins.size() > 400
                    usedObOrigins.shift()
 
bool bullConfluence = showConfluence and breakUp and not na(recentBullSweep) and bar_index-recentBullSweep <= setupWindow and (bullFvg or bullBap)
bool bearConfluence = showConfluence and breakDown and not na(recentBearSweep) and bar_index-recentBearSweep <= setupWindow and (bearFvg or bearBap)
if bullConfluence
    label.new(bar_index, low, "LONG WATCH ✧\nSweep + BOS + Gap", style=label.style_label_up, color=color.new(bullColor, 15), textcolor=textColor, size=size.tiny)
if bearConfluence
    label.new(bar_index, high, "SHORT WATCH ✧\nSweep + BOS + Gap", style=label.style_label_down, color=color.new(bearColor, 15), textcolor=textColor, size=size.tiny)
alertcondition(breakUp, "Bullish BOS/CHOCH", "SMC Liquidity PRO: bullish structure break")
alertcondition(breakDown, "Bearish BOS/CHOCH", "SMC Liquidity PRO: bearish structure break")
alertcondition(sweepH, "BSL Sweep", "SMC Liquidity PRO: buy-side liquidity sweep")
alertcondition(sweepL, "SSL Sweep", "SMC Liquidity PRO: sell-side liquidity sweep")
alertcondition(bullFvg or bearFvg, "Fresh FVG", "SMC Liquidity PRO: new fair value gap")
alertcondition(bullConfluence, "Long Confluence", "SMC Liquidity PRO: bullish confluence watch")
alertcondition(bearConfluence, "Short Confluence", "SMC Liquidity PRO: bearish confluence watch")
alertcondition(greedSignal, "Extreme Greed", "SMC Liquidity PRO: extreme greed threshold crossing")
alertcondition(fearSignal, "Extreme Fear", "SMC Liquidity PRO: extreme fear threshold crossing")

← 返回列表