本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// ═══════════════════════════════════════════════════════════════════════════════════════════
// SMC SUPPORT AND RESISTANCE (short title: SMC S&R)
// Advanced Institutional Support & Resistance Zone Engine - TradingView Pine Script v6
// ═══════════════════════════════════════════════════════════════════════════════════════════
//
// AUTHOR / PUBLISHER / RIGHTS HOLDER
// ----------------------------------
// Author (TradingView username) ........ Michael_Fx_Trader
// Publisher ............................ Michael_Fx_Trader
// Copyright / Rights holder ............ Michael_Fx_Trader - all rights reserved
// Script title ......................... SMC Support and Resistance
// Script version ....................... 1.0 (Pine Script v6)
// Created .............................. November 2026
//
// ORIGINALITY DECLARATION AND AUTHOR VERIFICATION
// -----------------------------------------------
// I, Michael_Fx_Trader, declare and verify the following about this script:
//
// 1. ORIGINAL WORK. This indicator is an original, from-scratch implementation. Every line of
// logic (swing engine, structure engine, order block engine, FVG engine, liquidity engine,
// zone merging, scoring model, role-reversal lifecycle, multi-timeframe ingestion, alerts,
// drawing code and dashboards) was designed and written specifically for this script.
//
// 2. NOT COPIED. No source code, formula, text, naming scheme, visual layout or drawing routine
// has been copied, translated, re-skinned, mashed up or "cloned" from any open-source or
// closed-source script, library, or third-party indicator on TradingView or elsewhere.
// The script does not import or depend on any external library.
//
// 3. PUBLIC CONCEPTS ONLY. Market-analysis concepts used here (swing highs/lows, support and
// resistance, Break of Structure, Change of Character, order blocks, fair value gaps,
// liquidity, ATR, relative volume, multi-timeframe analysis) are general, publicly known
// trading concepts and are not owned by any single author. Only the CONCEPTS are shared;
// this implementation, its scoring model and its code are my own.
//
// 4. RIGHTS. I am the sole author and hold all rights to publish, distribute, license and
// modify this script. The script was developed with AI-assisted coding under my direction;
// the specification, design decisions, review and final ownership are mine.
//
// 5. HOUSE RULES. The script is written to follow TradingView House Rules: original logic,
// no repainting of confirmed signals, no misleading performance claims, no advertising
// inside the script, and a description that explains what the indicator does.
//
// 6. NO FINANCIAL ADVICE. This indicator is a charting and analysis tool. It does not give
// financial advice, does not guarantee profits, and past behaviour of zones does not
// guarantee future reactions. Use proper risk management.
//
// Signed: Michael_Fx_Trader (Author and Publisher)
//
// ───────────────────────────────────────────────────────────────────────────────────────────
// WHAT THE INDICATOR DRAWS
// ------------------------
// ONLY Support and Resistance zones are drawn on the chart. Each support zone carries the
// text "Support" and each resistance zone carries the text "Resistance". Nothing else is
// marked (no BOS/CHoCH, FVG, liquidity, order block or sweep drawings, no tags, no scores).
// Market structure, FVGs, liquidity and volume are used INTERNALLY only, as scoring evidence.
// The optional Zone Strength panel and details dashboard exist but are OFF by default.
//
// ───────────────────────────────────────────────────────────────────────────────────────────
// HOW THE DETECTION ENGINE WORKS
// ------------------------------
// 1. SWING ENGINE. Pivots are confirmed with Left/Right bars (default 5/5). A pivot is only
// used after the right-side bars have closed, so it is never known early. A pivot must
// produce a minimum reaction (ATR based, set by Swing Sensitivity) to become a zone.
// A pivot that is the highest/lowest of a wider window is flagged as a MAJOR swing.
// 2. ZONE GEOMETRY. Each level becomes a price zone, not a line. Zone half-width =
// ATR(14) x Zone Width Multiplier (default 0.20). The zone also covers the rejection wick
// (bounded to 3 half-widths). All distances are ATR based, so it adapts to any market.
// 3. STRUCTURE ENGINE. A close beyond the last confirmed swing (plus a small ATR buffer) is a
// BOS (same direction) or CHoCH (against the previous trend). The origin swing zone of the
// move receives structure evidence.
// 4. ORDER BLOCKS. When a BOS/CHoCH is confirmed with ATR displacement, the last opposite
// candle at the origin of the impulse becomes a Demand (bullish) or Supply (bearish) zone.
// 5. FAIR VALUE GAPS. 3-candle gaps larger than a minimum ATR size are tracked. A zone that
// overlaps a same-direction unmitigated FVG gets FVG points. Partially filled FVGs give
// half points, fully filled FVGs give none.
// 6. LIQUIDITY. Equal highs/lows (within an ATR tolerance) and confirmed liquidity sweeps
// (wick beyond a swing + close back inside) give liquidity evidence. A sweep also creates
// a reversal zone from the sweep candle.
// 7. VOLUME AND REJECTION. Relative volume (vs SMA) at the origin candle, wick rejection,
// engulfing and pin bars give evidence. Volume is optional; symbols without volume still
// work with no errors.
// 8. MERGING. Same-side zones that overlap or sit within the Merge Distance (ATR) are merged
// into one stronger zone. Evidence is combined as flags, so one event is never counted twice.
// 9. LIFECYCLE. Fresh -> Tested Once -> Tested Multiple -> Partially Mitigated -> Broken.
// A close beyond a zone by the break buffer (ATR) breaks it. With Role Reversal enabled the
// broken zone flips (support becomes resistance and vice versa) and waits for a retest.
// Wick-only penetration never breaks a zone.
// 10. MULTI-TIMEFRAME. Higher-timeframe pivots (5m/15m/1H/4H/1D/1W/1M, each switchable) are
// requested with request.security() using confirmed data only (expression shifted by one
// higher-timeframe bar, lookahead off). Only timeframes ABOVE the chart timeframe are used.
// Overlapping zones from different timeframes merge and gain confluence points.
//
// HOW THE STRENGTH SCORE (0-100) IS CALCULATED
// --------------------------------------------
// Score = sum(weight x evidence quality) / sum(weights) x 100 x freshness factor
// Major Swing Structure ..... 20 (reaction size, major-swing flag)
// BOS / CHoCH ............... 15 (0.5 without displacement, 0.85 BOS, 1.0 CHoCH)
// Order Block ............... 15 (displacement strength)
// FVG ....................... 10 (fresh 1.0, partially filled 0.5)
// Liquidity ................. 10 (equal highs/lows 1.0, sweep 0.8)
// Volume .................... 10 (relative volume vs threshold)
// Rejection ................. 10 (wick / pin / engulfing)
// Touch Quality ............. 5 (clean rejections minus failed touches)
// Multi-Timeframe ........... 5 (higher timeframe origin / overlap)
// Weights are configurable. Points are given only when real evidence exists.
// Freshness factor: untouched 1.00, 1 touch 0.97, 2 touches 0.93, 3+ touches 0.88,
// partially mitigated x0.85, flipped (role reversal) x0.90.
// Classes: 85-100 Very Strong (Institutional), 70-84 Strong, 50-69 Moderate, 30-49 Weak.
//
// NON-REPAINTING NOTES
// --------------------
// - The engine runs only on CLOSED bars. Pivots are used only after confirmation.
// - Higher-timeframe data is shifted by one HTF bar and requested with lookahead off.
// - Zones are created at confirmation time. By default a zone starts at its confirmation bar
// (option: draw from origin candle). Confirmed zones are not moved afterwards, except for
// lawful merges and lifecycle changes (touch, mitigation, break, flip).
// - Alerts fire on state transitions at bar close, not on every bar inside a zone.
// - Drawing is refreshed on the last bar; the zone list itself is built from closed bars only.
//
// RECOMMENDED SETTINGS
// --------------------
// XAUUSD (Gold), M15-H1 : Swing 5/5, Sensitivity Medium, ATR 14, Width 0.20-0.30, Merge 0.5,
// Displacement 1.2, Min Score 40, Max Zones 3, MTF: 1H + 4H + 1D.
// Forex majors : Swing 5/5, Width 0.20, Merge 0.5, Min Score 35-40, MTF: 1H + 4H + 1D.
// Crypto (BTC/ETH) : Swing 6/6, Sensitivity Medium or High, Width 0.25, Merge 0.6,
// Displacement 1.3, Relative Volume Threshold 1.8, MTF: 4H + 1D + 1W.
// Indices : Swing 5/5, Width 0.20, Merge 0.5, Min Score 40, MTF: 1H + 4H + 1D.
// Stocks : Swing 5/5, Width 0.20, Merge 0.5, Relative Volume 1.5, MTF: 1D + 1W.
// Cleaner chart : raise Minimum Strength Score or lower Maximum Active Zones.
// More zones : lower Minimum Strength Score (30) or use Swing Sensitivity High.
// ═══════════════════════════════════════════════════════════════════════════════════════════
indicator(title = "SMC Support and Resistance", shorttitle = "SMC S&R", overlay = true, max_boxes_count = 500, max_labels_count = 500, max_bars_back = 1000)
// ───────────────────────────────────────────── INPUT GROUPS ─────────────────────────────────────────────
G_MAIN = "A. Main Settings"
G_SW = "B. Swing Detection"
G_SMC = "C. SMC Settings"
G_VOL = "D. Volume and Rejection"
G_ZONE = "E. Zone Settings"
G_MTF = "F. Multi-Timeframe"
G_WGT = "G. Strength Weights"
G_VIS = "H. Visualization"
G_ALT = "I. Alerts"
// A. Main
enableInd = input.bool(true, "Enable Indicator", group = G_MAIN)
showSup = input.bool(true, "Show Support Zones", group = G_MAIN)
showRes = input.bool(true, "Show Resistance Zones", group = G_MAIN)
showMajor = input.bool(true, "Show Major Levels", group = G_MAIN)
showMinor = input.bool(true, "Show Minor Levels", group = G_MAIN)
minScore = input.int(35, "Minimum Strength Score", minval = 0, maxval = 100, group = G_MAIN)
maxZones = input.int(3, "Maximum Active Zones (per side)", minval = 1, maxval = 10, group = G_MAIN)
// B. Swing
swL = input.int(5, "Swing Left Bars", minval = 2, maxval = 30, group = G_SW)
swR = input.int(5, "Swing Right Bars", minval = 2, maxval = 30, group = G_SW)
sensStr = input.string("Medium", "Swing Sensitivity (minimum reaction)", options = ["Low", "Medium", "High"], group = G_SW)
lookbackBars = input.int(1500, "Historical Lookback (bars)", minval = 100, maxval = 5000, group = G_SW)
minSwingATR = sensStr == "Low" ? 1.5 : sensStr == "High" ? 0.6 : 1.0
// C. SMC
useBOS = input.bool(true, "Enable BOS", group = G_SMC)
useCHoCH = input.bool(true, "Enable CHoCH", group = G_SMC)
useOB = input.bool(true, "Enable Order Blocks", group = G_SMC)
useFVG = input.bool(true, "Enable FVG", group = G_SMC)
useLiq = input.bool(true, "Enable Liquidity Detection", group = G_SMC)
useSweep = input.bool(true, "Enable Liquidity Sweeps", group = G_SMC)
dispMult = input.float(1.2, "Displacement (ATR multiple)", minval = 0.5, step = 0.1, group = G_SMC)
bosBuf = input.float(0.05, "Structure Break Buffer (ATR)", minval = 0.0, step = 0.01, group = G_SMC)
fvgMinATR = input.float(0.3, "Minimum FVG Size (ATR)", minval = 0.0, step = 0.05, group = G_SMC)
eqTol = input.float(0.25, "Equal High/Low Tolerance (ATR)", minval = 0.05, step = 0.05, group = G_SMC)
obLook = input.int(150, "Order Block Origin Lookback (bars)", minval = 10, maxval = 300, group = G_SMC)
// D. Volume and rejection
useVol = input.bool(true, "Enable Volume Confirmation", group = G_VOL)
volLen = input.int(20, "Volume MA Length", minval = 2, group = G_VOL)
relVolThr = input.float(1.5, "Relative Volume Threshold", minval = 1.1, step = 0.1, group = G_VOL)
rejWick = input.float(0.5, "Rejection Wick Ratio", minval = 0.2, maxval = 0.9, step = 0.05, group = G_VOL)
// E. Zone
atrLen = input.int(14, "ATR Length", minval = 1, group = G_ZONE)
widthMult = input.float(0.20, "Zone Width Multiplier (ATR half-width)", minval = 0.05, step = 0.05, group = G_ZONE)
mergeMult = input.float(0.5, "Merge Distance (ATR)", minval = 0.0, step = 0.1, group = G_ZONE)
maxAge = input.int(3000, "Maximum Zone Age (bars)", minval = 50, group = G_ZONE)
maxTouches = input.int(6, "Freshness Filter: hide after N touches (0 = off)", minval = 0, group = G_ZONE)
hideMit = input.bool(false, "Hide Partially Mitigated Zones", group = G_ZONE)
brkBuf = input.float(0.15, "Breakout Confirmation Buffer (ATR)", minval = 0.0, step = 0.05, group = G_ZONE)
brkCloses = input.int(1, "Breakout Confirmation Closes", minval = 1, maxval = 5, group = G_ZONE)
useRoleRev = input.bool(true, "Enable Role Reversal (broken zone flips)", group = G_ZONE)
startMode = input.string("Confirmation Bar", "Zone Starts At", options = ["Confirmation Bar", "Origin Candle"], group = G_ZONE)
// F. MTF
useMTF = input.bool(true, "Enable MTF", group = G_MTF)
e5 = input.bool(false, "Enable 5m", group = G_MTF)
e15 = input.bool(true, "Enable 15m", group = G_MTF)
e60 = input.bool(true, "Enable 1H", group = G_MTF)
e240 = input.bool(true, "Enable 4H", group = G_MTF)
eD = input.bool(true, "Enable Daily", group = G_MTF)
eW = input.bool(false, "Enable Weekly", group = G_MTF)
eM = input.bool(false, "Enable Monthly", group = G_MTF)
// G. Weights
wSwing = input.float(20.0, "Major Swing Structure", minval = 0.0, group = G_WGT)
wStruct = input.float(15.0, "BOS / CHoCH Confirmation", minval = 0.0, group = G_WGT)
wOB = input.float(15.0, "Order Block Confluence", minval = 0.0, group = G_WGT)
wFVG = input.float(10.0, "FVG Confluence", minval = 0.0, group = G_WGT)
wLiq = input.float(10.0, "Liquidity Evidence", minval = 0.0, group = G_WGT)
wVol = input.float(10.0, "Volume Confirmation", minval = 0.0, group = G_WGT)
wRej = input.float(10.0, "Rejection Confirmation", minval = 0.0, group = G_WGT)
wTouch = input.float(5.0, "Historical Touch Quality", minval = 0.0, group = G_WGT)
wMTF = input.float(5.0, "Multi-Timeframe Confluence", minval = 0.0, group = G_WGT)
// H. Visualization
supCol = input.color(#00FF88, "Support Color", group = G_VIS)
resCol = input.color(#FF3B5C, "Resistance Color", group = G_VIS)
zoneTransp = input.int(80, "Zone Transparency", minval = 40, maxval = 95, group = G_VIS)
borderW = input.int(1, "Border Width", minval = 1, maxval = 4, group = G_VIS)
extMode = input.string("Extend Right", "Extend Zones", options = ["Extend Right", "Extend Left", "Extend Both", "Fixed Length"], group = G_VIS)
fixedLen = input.int(150, "Fixed Length (bars)", minval = 5, group = G_VIS)
showLabels = input.bool(true, "Show Strength Labels", group = G_VIS)
showPriceLbl = input.bool(false, "Show Price Labels", group = G_VIS)
showTags = input.bool(true, "Show Evidence Tags in Labels", group = G_VIS)
lblSize = input.string("Small", "Label Size", options = ["Tiny", "Small", "Normal"], group = G_VIS)
showStrength = input.bool(false, "Show Zone Strength Panel", group = G_VIS)
strPos = input.string("Top Right", "Zone Strength Panel Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = G_VIS)
showDash = input.bool(false, "Show Dashboard", group = G_VIS)
dashPos = input.string("Bottom Right", "Dashboard Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = G_VIS)
// I. Alerts
alSupTouch = input.bool(true, "Support Touch", group = G_ALT)
alResTouch = input.bool(true, "Resistance Touch", group = G_ALT)
alBullRej = input.bool(true, "Bullish Rejection", group = G_ALT)
alBearRej = input.bool(true, "Bearish Rejection", group = G_ALT)
alSupBrk = input.bool(true, "Support Breakout", group = G_ALT)
alResBrk = input.bool(true, "Resistance Breakout", group = G_ALT)
alBullRet = input.bool(true, "Bullish Retest", group = G_ALT)
alBearRet = input.bool(true, "Bearish Retest", group = G_ALT)
alStrSup = input.bool(true, "Strong Support Created", group = G_ALT)
alStrRes = input.bool(true, "Strong Resistance Created", group = G_ALT)
// ───────────────────────────────────────────── CONSTANTS ─────────────────────────────────────────────
C_SUP_STRONG = #00E676
C_RES_STRONG = #FF1744
C_SUP_MAJOR = #0A6B35
C_RES_MAJOR = #8B0A22
C_SUP_LBL = #0B3D22
C_RES_LBL = #4A0D18
STRONG_THR = 70.0
MAJOR_THR = 85.0
// ───────────────────────────────────────────── TYPES ─────────────────────────────────────────────
type Zone
bool isSup = true
float top = na
float bot = na
int t0 = na
int tBorn = na
int bBorn = na
int pBar = na
int tLast = na
int kind = 0
float swQ = 0.0
float structQ = 0.0
float obQ = 0.0
float liqQ = 0.0
float volQ = 0.0
float rejQ = 0.0
int touches = 0
int rejTouches = 0
bool inside = false
bool rejCounted = false
bool mitigated = false
bool majorSwing = false
bool flipped = false
bool retestPending = false
int flips = 0
int brkCnt = 0
bool strongSent = false
bool majorSent = false
float score = 0.0
array<bool> tfs = na
// ───────────────────────────────────────────── PERSISTENT STATE ─────────────────────────────────────────────
var array<Zone> zones = array.new<Zone>()
var array<float> fvgTop = array.new<float>()
var array<float> fvgBot = array.new<float>()
var array<int> fvgDir = array.new<int>()
var array<int> fvgSt = array.new<int>()
var array<float> eqHP = array.new<float>()
var array<int> eqHB = array.new<int>()
var array<float> eqLP = array.new<float>()
var array<int> eqLB = array.new<int>()
var array<int> lastHT = array.new<int>(8, 0)
var array<int> lastLT = array.new<int>(8, 0)
var array<bool> ev = array.new<bool>(12, false)
var array<string> TFN = array.from("CHART", "5m", "15m", "1H", "4H", "1D", "1W", "1M")
var array<box> dBoxes = array.new<box>()
var array<label> dLbls = array.new<label>()
var float lastPH = na
var float lastPL = na
var int lastPHbar = na
var int lastPLbar = na
var bool phUsed = false
var bool plUsed = false
var bool phSwept = false
var bool plSwept = false
var int trend = 0
var string lastEv = "RANGE"
var int lastEvBar = 0
// ───────────────────────────────────────────── HELPER FUNCTIONS ─────────────────────────────────────────────
f_clamp(float x, float lo, float hi) =>
math.max(lo, math.min(hi, x))
f_mid(Zone z) =>
(z.top + z.bot) * 0.5
f_new(bool isSup, float top, float bot, int t0, int kind) =>
Zone z = Zone.new()
z.isSup := isSup
z.top := top
z.bot := bot
z.t0 := t0
z.tBorn := time
z.bBorn := bar_index
z.pBar := bar_index
z.tLast := time
z.kind := kind
z.tfs := array.new<bool>(8, false)
array.set(z.tfs, 0, true)
z
f_tfCount(Zone z) =>
int n = 0
for i = 0 to 7
if array.get(z.tfs, i)
n += 1
n
f_anyHTF(Zone z) =>
bool r = false
for i = 1 to 7
if array.get(z.tfs, i)
r := true
r
f_tfTag(Zone z) =>
string s = ""
for i = 1 to 7
if array.get(z.tfs, i)
s += (s == "" ? "" : "+") + array.get(TFN, i)
s
f_fvgQ(Zone z, float tol) =>
float q = 0.0
if useFVG
int n = array.size(fvgTop)
if n > 0
int want = z.isSup ? 1 : -1
for i = 0 to n - 1
if array.get(fvgDir, i) == want
if array.get(fvgBot, i) <= z.top + tol and array.get(fvgTop, i) >= z.bot - tol
q := math.max(q, array.get(fvgSt, i) == 0 ? 1.0 : 0.5)
q
f_score(Zone z, float tol) =>
float tot = wSwing + wStruct + wOB + wFVG + wLiq + wVol + wRej + wTouch + wMTF
float fq = f_fvgQ(z, tol)
int bad = z.touches - z.rejTouches
float tq = f_clamp((z.rejTouches - 0.5 * bad) / 2.0, 0.0, 1.0)
int n = f_tfCount(z)
float mq = f_clamp((f_anyHTF(z) ? 0.5 : 0.0) + 0.5 * math.max(n - 1, 0), 0.0, 1.0)
float raw = wSwing * z.swQ + wStruct * z.structQ + wOB * z.obQ + wFVG * fq + wLiq * z.liqQ + wVol * z.volQ + wRej * z.rejQ + wTouch * tq + wMTF * mq
float fresh = z.touches == 0 ? 1.0 : z.touches == 1 ? 0.97 : z.touches == 2 ? 0.93 : 0.88
if z.mitigated
fresh *= 0.85
if z.flipped
fresh *= 0.9
z.score := tot > 0 ? math.min(100.0, raw / tot * 100.0 * fresh) : 0.0
z.score
f_isMajor(Zone z) =>
z.majorSwing or f_anyHTF(z) or z.score >= MAJOR_THR
f_visible(Zone z) =>
bool ok = z.score >= minScore
if z.isSup and not showSup
ok := false
if not z.isSup and not showRes
ok := false
bool maj = f_isMajor(z)
if maj and not showMajor
ok := false
if not maj and not showMinor
ok := false
if hideMit and z.mitigated
ok := false
if maxTouches > 0 and z.touches > maxTouches
ok := false
ok
f_class(float s) =>
s >= 85.0 ? "VERY STRONG" : s >= 70.0 ? "STRONG" : s >= 50.0 ? "MODERATE" : "WEAK"
f_state(Zone z) =>
z.flipped and z.retestPending ? "RETEST PENDING" : z.mitigated ? "PARTIALLY MITIGATED" : z.touches == 0 ? "FRESH" : z.touches == 1 ? "TESTED ONCE" : "TESTED MULTIPLE"
f_typeName(Zone z) =>
bool maj = f_isMajor(z)
string base = z.kind == 1 ? (z.isSup ? "DEMAND ZONE" : "SUPPLY ZONE") : maj ? (z.isSup ? "MAJOR SUPPORT" : "MAJOR RESISTANCE") : (z.isSup ? "SUPPORT" : "RESISTANCE")
z.flipped ? base + " (FLIP)" : base
f_tags(Zone z, float tol) =>
string s = ""
if z.kind == 1
s += "OB"
if z.structQ > 0
s += (s == "" ? "" : " + ") + "STRUCTURE"
if f_fvgQ(z, tol) > 0
s += (s == "" ? "" : " + ") + "FVG"
if z.liqQ > 0
s += (s == "" ? "" : " + ") + "LIQUIDITY"
if z.volQ >= 0.5
s += (s == "" ? "" : " + ") + "VOLUME"
if z.rejQ >= 0.6
s += (s == "" ? "" : " + ") + "REJECTION"
s += (s == "" ? "" : " | ") + f_state(z)
string tf = f_tfTag(z)
if tf != ""
s += " | " + tf
s
f_pos(string s) =>
s == "Top Right" ? position.top_right : s == "Top Left" ? position.top_left : s == "Bottom Left" ? position.bottom_left : position.bottom_right
f_bar(float pct) =>
int n = math.round(pct / 100.0 * 14.0)
string s = ""
for i = 1 to 14
s += (i <= n ? "█" : "░")
s
f_merge(Zone o, Zone nw, float atrN) =>
float nt = math.max(o.top, nw.top)
float nb = math.min(o.bot, nw.bot)
float maxH = math.max(1.5, 6.0 * widthMult) * atrN
if nt - nb <= maxH
o.top := nt
o.bot := nb
else if nw.score > o.score
o.top := nw.top
o.bot := nw.bot
o.t0 := math.min(o.t0, nw.t0)
o.pBar := math.max(o.pBar, nw.pBar)
o.swQ := math.max(o.swQ, nw.swQ)
o.structQ := math.max(o.structQ, nw.structQ)
o.obQ := math.max(o.obQ, nw.obQ)
o.liqQ := math.max(o.liqQ, nw.liqQ)
o.volQ := math.max(o.volQ, nw.volQ)
o.rejQ := math.max(o.rejQ, nw.rejQ)
o.majorSwing := o.majorSwing or nw.majorSwing
if nw.kind == 1
o.kind := 1
for i = 0 to 7
if array.get(nw.tfs, i)
array.set(o.tfs, i, true)
true
f_add(Zone nw, float atrN) =>
float tol = mergeMult * atrN
f_score(nw, tol)
bool merged = false
int n = array.size(zones)
if n > 0
for i = 0 to n - 1
Zone o = array.get(zones, i)
if o.isSup == nw.isSup and o.bot - tol <= nw.top and nw.bot - tol <= o.top
f_merge(o, nw, atrN)
f_score(o, tol)
merged := true
break
if not merged
int cnt = 0
float minSc = 1000000.0
int minIdx = -1
if n > 0
for i = 0 to n - 1
Zone o2 = array.get(zones, i)
if o2.isSup == nw.isSup
cnt += 1
if o2.score < minSc
minSc := o2.score
minIdx := i
if cnt >= maxZones + 4
if nw.score >= minSc and minIdx >= 0
array.remove(zones, minIdx)
array.push(zones, nw)
else
array.push(zones, nw)
true
f_fvgRemove(int i) =>
array.remove(fvgTop, i)
array.remove(fvgBot, i)
array.remove(fvgDir, i)
array.remove(fvgSt, i)
true
f_fvg(float atrN) =>
int n = array.size(fvgTop)
if n > 0
for i = n - 1 to 0
int d = array.get(fvgDir, i)
float t = array.get(fvgTop, i)
float b = array.get(fvgBot, i)
if d == 1
if close < b
f_fvgRemove(i)
else if low < t
array.set(fvgSt, i, 1)
else
if close > t
f_fvgRemove(i)
else if high > b
array.set(fvgSt, i, 1)
if useFVG
if low > high[2] and (low - high[2]) >= fvgMinATR * atrN
array.push(fvgTop, low)
array.push(fvgBot, high[2])
array.push(fvgDir, 1)
array.push(fvgSt, 0)
if high < low[2] and (low[2] - high) >= fvgMinATR * atrN
array.push(fvgTop, low[2])
array.push(fvgBot, high)
array.push(fvgDir, -1)
array.push(fvgSt, 0)
while array.size(fvgTop) > 40
f_fvgRemove(0)
true
f_markStruct(bool sup, int sinceBar, float q) =>
int pick = -1
float best = na
int n = array.size(zones)
if n > 0
for i = 0 to n - 1
Zone z = array.get(zones, i)
if z.isSup == sup and z.pBar > sinceBar and z.kind != 3
float key = sup ? -z.bot : z.top
if na(best) or key > best
best := key
pick := i
if pick >= 0
Zone zp = array.get(zones, pick)
zp.structQ := math.max(zp.structQ, q)
true
f_update(float atrN) =>
float tol = mergeMult * atrN
float rng = high - low
float lowWick = rng > 0 ? (math.min(open, close) - low) / rng : 0.0
float upWick = rng > 0 ? (high - math.max(open, close)) / rng : 0.0
int n = array.size(zones)
if n > 0
for i = n - 1 to 0
Zone z = array.get(zones, i)
if bar_index - z.bBorn > maxAge
array.remove(zones, i)
continue
bool insideNow = low <= z.top and high >= z.bot
if z.bBorn == bar_index
z.inside := insideNow
else
bool elig = f_visible(z)
bool brk = z.isSup ? close < z.bot - brkBuf * atrN : close > z.top + brkBuf * atrN
if brk
z.brkCnt += 1
else
z.brkCnt := 0
if z.brkCnt >= brkCloses
if elig
array.set(ev, z.isSup ? 4 : 5, true)
if useRoleRev and z.flips < 2
z.isSup := not z.isSup
z.flips += 1
z.flipped := true
z.retestPending := true
z.touches := 0
z.rejTouches := 0
z.inside := false
z.rejCounted := false
z.mitigated := false
z.brkCnt := 0
z.strongSent := false
z.majorSent := false
z.tLast := time
f_score(z, tol)
else
array.remove(zones, i)
continue
if insideNow
if not z.inside
z.touches += 1
z.tLast := time
z.rejCounted := false
if elig
array.set(ev, z.isSup ? 0 : 1, true)
if not z.rejCounted
float md = f_mid(z)
bool rej = z.isSup ? (close > md and close > open and (lowWick >= rejWick or close > z.top)) : (close < md and close < open and (upWick >= rejWick or close < z.bot))
if rej
z.rejCounted := true
z.rejTouches += 1
if elig
array.set(ev, z.isSup ? 2 : 3, true)
if z.flipped and z.retestPending
array.set(ev, z.isSup ? 6 : 7, true)
if z.flipped
z.retestPending := false
if z.isSup ? close < f_mid(z) : close > f_mid(z)
z.mitigated := true
z.inside := insideNow
f_score(z, tol)
if f_visible(z)
if not z.strongSent and z.score >= STRONG_THR
z.strongSent := true
array.set(ev, z.isSup ? 8 : 9, true)
if not z.majorSent and f_isMajor(z)
z.majorSent := true
array.set(ev, z.isSup ? 10 : 11, true)
true
f_ingest(int rank, bool en, float ph, float phB, float phW, float pl, float plB, float plW, float atH, float rv, int tp, float atrN) =>
if en and not na(atH) and atH > 0 and not na(tp)
float hw = atH * widthMult
bool vOK = useVol and not na(rv)
float vq = vOK ? f_clamp((rv - 1.0) / (relVolThr - 1.0), 0.0, 1.0) : 0.0
if not na(ph) and not na(phB) and tp != array.get(lastHT, rank)
array.set(lastHT, rank, tp)
Zone zh = f_new(false, ph + hw, math.min(math.max(phB, ph - 3.0 * hw), ph - hw), tp, 3)
zh.swQ := 1.0
zh.rejQ := phW >= rejWick ? 1.0 : (phW / rejWick) * 0.6
zh.volQ := vq
array.set(zh.tfs, 0, false)
array.set(zh.tfs, rank, true)
f_add(zh, atrN)
if not na(pl) and not na(plB) and tp != array.get(lastLT, rank)
array.set(lastLT, rank, tp)
Zone zl = f_new(true, math.max(math.min(plB, pl + 3.0 * hw), pl + hw), pl - hw, tp, 3)
zl.swQ := 1.0
zl.rejQ := plW >= rejWick ? 1.0 : (plW / rejWick) * 0.6
zl.volQ := vq
array.set(zl.tfs, 0, false)
array.set(zl.tfs, rank, true)
f_add(zl, atrN)
true
f_draw(Zone z, int barMs, float tol) =>
bool maj = f_isMajor(z)
bool strong = z.score >= STRONG_THR
color baseC = z.isSup ? supCol : resCol
color strongC = z.isSup ? C_SUP_STRONG : C_RES_STRONG
color majFill = z.isSup ? C_SUP_MAJOR : C_RES_MAJOR
color bC = maj ? baseC : strong ? strongC : baseC
color fillC = maj ? color.new(majFill, math.max(zoneTransp - 25, 30)) : strong ? color.new(strongC, math.max(zoneTransp - 5, 0)) : color.new(baseC, zoneTransp)
int xl = startMode == "Origin Candle" ? z.t0 : z.tBorn
int xr = extMode == "Fixed Length" ? xl + fixedLen * barMs : math.max(time, xl + barMs)
string extS = extMode == "Extend Right" ? extend.right : extMode == "Extend Left" ? extend.left : extMode == "Extend Both" ? extend.both : extend.none
if maj
float pad = (z.top - z.bot) * 0.3
box g = box.new(left = xl, top = z.top + pad, right = xr, bottom = z.bot - pad, border_color = color.new(bC, 65), border_width = borderW + 2, border_style = line.style_solid, extend = extS, xloc = xloc.bar_time, bgcolor = color.new(bC, 92))
array.push(dBoxes, g)
box b = box.new(left = xl, top = z.top, right = xr, bottom = z.bot, border_color = bC, border_width = borderW, border_style = line.style_solid, extend = extS, xloc = xloc.bar_time, bgcolor = fillC)
array.push(dBoxes, b)
if showLabels
string t1 = z.isSup ? "Support" : "Resistance"
int lx = extMode == "Fixed Length" ? xr : time
string lsz = lblSize == "Tiny" ? size.tiny : lblSize == "Normal" ? size.normal : size.small
label lb = label.new(x = lx, y = f_mid(z), text = t1, xloc = xloc.bar_time, yloc = yloc.price, color = color.new(z.isSup ? C_SUP_LBL : C_RES_LBL, 10), style = label.style_label_right, textcolor = color.white, size = lsz, textalign = text.align_left)
array.push(dLbls, lb)
true
// Higher-timeframe pack: evaluated INSIDE request.security(); every value is shifted by one HTF bar
// so only fully confirmed HTF data is ever returned (no future information).
f_htf() =>
float ph = ta.pivothigh(high, swL, swR)
float pl = ta.pivotlow(low, swL, swR)
float lowAft = ta.lowest(low, swR)
float highAft = ta.highest(high, swR)
float at = ta.atr(atrLen)
float vs = ta.sma(volume, volLen)
float rng = high[swR] - low[swR]
float phB = math.max(open[swR], close[swR])
float plB = math.min(open[swR], close[swR])
float phW = rng > 0 ? (high[swR] - phB) / rng : 0.0
float plW = rng > 0 ? (plB - low[swR]) / rng : 0.0
float rv = vs[swR] > 0 ? volume[swR] / vs[swR] : na
int tp = time[swR]
float phS = (not na(ph) and (high[swR] - lowAft) >= minSwingATR * nz(at[swR], at)) ? ph : na
float plS = (not na(pl) and (highAft - low[swR]) >= minSwingATR * nz(at[swR], at)) ? pl : na
[phS[1], phB[1], phW[1], plS[1], plB[1], plW[1], at[1], rv[1], tp[1]]
// ───────────────────────────────────────────── SERIES CALCULATIONS ─────────────────────────────────────────────
float atrV = ta.atr(atrLen)
float volSma = ta.sma(volume, volLen)
float relVol = volSma > 0 ? volume / volSma : na
float relVolMax3 = ta.highest(nz(relVol), 3)
float phv = ta.pivothigh(high, swL, swR)
float plv = ta.pivotlow(low, swL, swR)
float dispBody = ta.highest(math.abs(close - open), 3)
int majN = 3 * (swL + swR) + 1
float hiN = ta.highest(high, majN)
float loN = ta.lowest(low, majN)
bool volOK = useVol and nz(volSma) > 0
// ───────────────────────────────────────────── HIGHER TIMEFRAME REQUESTS ─────────────────────────────────────────────
bool en5 = useMTF and e5 and timeframe.in_seconds("5") > timeframe.in_seconds()
bool en15 = useMTF and e15 and timeframe.in_seconds("15") > timeframe.in_seconds()
bool en60 = useMTF and e60 and timeframe.in_seconds("60") > timeframe.in_seconds()
bool en240 = useMTF and e240 and timeframe.in_seconds("240") > timeframe.in_seconds()
bool enD = useMTF and eD and timeframe.in_seconds("D") > timeframe.in_seconds()
bool enW = useMTF and eW and timeframe.in_seconds("W") > timeframe.in_seconds()
bool enM = useMTF and eM and timeframe.in_seconds("M") > timeframe.in_seconds()
[ph1, pb1, pw1, pl1, lb1, lw1, at1, rv1, tp1] = request.security(syminfo.tickerid, en5 ? "5" : timeframe.period, f_htf(), lookahead = barmerge.lookahead_off)
[ph2, pb2, pw2, pl2, lb2, lw2, at2, rv2, tp2] = request.security(syminfo.tickerid, en15 ? "15" : timeframe.period, f_htf(), lookahead = barmerge.lookahead_off)
[ph3, pb3, pw3, pl3, lb3, lw3, at3, rv3, tp3] = request.security(syminfo.tickerid, en60 ? "60" : timeframe.period, f_htf(), lookahead = barmerge.lookahead_off)
[ph4, pb4, pw4, pl4, lb4, lw4, at4, rv4, tp4] = request.security(syminfo.tickerid, en240 ? "240" : timeframe.period, f_htf(), lookahead = barmerge.lookahead_off)
[ph5, pb5, pw5, pl5, lb5, lw5, at5, rv5, tp5] = request.security(syminfo.tickerid, enD ? "D" : timeframe.period, f_htf(), lookahead = barmerge.lookahead_off)
[ph6, pb6, pw6, pl6, lb6, lw6, at6, rv6, tp6] = request.security(syminfo.tickerid, enW ? "W" : timeframe.period, f_htf(), lookahead = barmerge.lookahead_off)
[ph7, pb7, pw7, pl7, lb7, lw7, at7, rv7, tp7] = request.security(syminfo.tickerid, enM ? "M" : timeframe.period, f_htf(), lookahead = barmerge.lookahead_off)
// ───────────────────────────────────────────── ENGINE (CLOSED BARS ONLY) ─────────────────────────────────────────────
for k = 0 to 11
array.set(ev, k, false)
bool inWindow = bar_index >= last_bar_index - lookbackBars
if barstate.isconfirmed and enableInd and inWindow and not na(atrV) and atrV > 0
float atrN = atrV
float hwN = atrN * widthMult
bool dispOK = dispBody >= dispMult * atrN
f_fvg(atrN)
// ---- confirmed swing HIGH -> resistance zone ----
if not na(phv)
float atrP = nz(atrV[swR], atrN)
float lowAfter = low
for k = 1 to swR - 1
lowAfter := math.min(lowAfter, low[k])
float legATR = atrP > 0 ? (phv - lowAfter) / atrP : 0.0
if legATR >= minSwingATR
lastPH := phv
lastPHbar := bar_index - swR
phUsed := false
phSwept := false
float hwP = atrP * widthMult
float bodyTop = math.max(open[swR], close[swR])
float rngP = high[swR] - low[swR]
float wickP = rngP > 0 ? (high[swR] - bodyTop) / rngP : 0.0
float rq = wickP >= rejWick ? 1.0 : (wickP / rejWick) * 0.6
if close[swR - 1] < open[swR - 1] and open[swR - 1] >= close[swR] and close[swR - 1] <= open[swR]
rq := math.max(rq, 0.9)
float rvP = math.max(nz(relVol[swR]), math.max(nz(relVol[swR - 1]), nz(relVol[swR + 1])))
float vq = volOK ? f_clamp((rvP - 1.0) / (relVolThr - 1.0), 0.0, 1.0) : 0.0
float lq = 0.0
if useLiq
int ne = array.size(eqHP)
if ne > 0
for j = 0 to ne - 1
if math.abs(array.get(eqHP, j) - phv) <= eqTol * atrP and (bar_index - swR) - array.get(eqHB, j) <= 500
lq := 1.0
array.push(eqHP, phv)
array.push(eqHB, bar_index - swR)
if array.size(eqHP) > 15
array.shift(eqHP)
array.shift(eqHB)
bool majP = high[swR] >= hiN[swR]
Zone zh = f_new(false, phv + hwP, math.min(math.max(bodyTop, phv - 3.0 * hwP), phv - hwP), time[swR], 0)
zh.pBar := bar_index - swR
zh.swQ := majP ? 1.0 : f_clamp(legATR / 6.0, 0.35, 0.8)
zh.rejQ := rq
zh.volQ := vq
zh.liqQ := lq
zh.majorSwing := majP
f_add(zh, atrN)
// ---- confirmed swing LOW -> support zone ----
if not na(plv)
float atrP = nz(atrV[swR], atrN)
float highAfter = high
for k = 1 to swR - 1
highAfter := math.max(highAfter, high[k])
float legATR = atrP > 0 ? (highAfter - plv) / atrP : 0.0
if legATR >= minSwingATR
lastPL := plv
lastPLbar := bar_index - swR
plUsed := false
plSwept := false
float hwP = atrP * widthMult
float bodyBot = math.min(open[swR], close[swR])
float rngP = high[swR] - low[swR]
float wickP = rngP > 0 ? (bodyBot - low[swR]) / rngP : 0.0
float rq = wickP >= rejWick ? 1.0 : (wickP / rejWick) * 0.6
if close[swR - 1] > open[swR - 1] and open[swR - 1] <= close[swR] and close[swR - 1] >= open[swR]
rq := math.max(rq, 0.9)
float rvP = math.max(nz(relVol[swR]), math.max(nz(relVol[swR - 1]), nz(relVol[swR + 1])))
float vq = volOK ? f_clamp((rvP - 1.0) / (relVolThr - 1.0), 0.0, 1.0) : 0.0
float lq = 0.0
if useLiq
int ne = array.size(eqLP)
if ne > 0
for j = 0 to ne - 1
if math.abs(array.get(eqLP, j) - plv) <= eqTol * atrP and (bar_index - swR) - array.get(eqLB, j) <= 500
lq := 1.0
array.push(eqLP, plv)
array.push(eqLB, bar_index - swR)
if array.size(eqLP) > 15
array.shift(eqLP)
array.shift(eqLB)
bool majP = low[swR] <= loN[swR]
Zone zl = f_new(true, math.max(math.min(bodyBot, plv + 3.0 * hwP), plv + hwP), plv - hwP, time[swR], 0)
zl.pBar := bar_index - swR
zl.swQ := majP ? 1.0 : f_clamp(legATR / 6.0, 0.35, 0.8)
zl.rejQ := rq
zl.volQ := vq
zl.liqQ := lq
zl.majorSwing := majP
f_add(zl, atrN)
// ---- liquidity sweeps (wick beyond last swing + close back inside) ----
float rngC = high - low
float upW = rngC > 0 ? (high - math.max(open, close)) / rngC : 0.0
float loW = rngC > 0 ? (math.min(open, close) - low) / rngC : 0.0
float vqNow = volOK ? f_clamp((nz(relVol) - 1.0) / (relVolThr - 1.0), 0.0, 1.0) : 0.0
if useLiq and useSweep
if not na(lastPH) and not phUsed and not phSwept and high > lastPH and close < lastPH
phSwept := true
Zone zs = f_new(false, high + hwN, math.min(math.max(math.max(open, close), high - 3.0 * hwN), high - hwN), time, 2)
zs.swQ := 0.5
zs.liqQ := 0.8
zs.rejQ := upW >= rejWick ? 1.0 : (upW / rejWick) * 0.6
zs.volQ := vqNow
f_add(zs, atrN)
if not na(lastPL) and not plUsed and not plSwept and low < lastPL and close > lastPL
plSwept := true
Zone zs2 = f_new(true, math.max(math.min(math.min(open, close), low + 3.0 * hwN), low + hwN), low - hwN, time, 2)
zs2.swQ := 0.5
zs2.liqQ := 0.8
zs2.rejQ := loW >= rejWick ? 1.0 : (loW / rejWick) * 0.6
zs2.volQ := vqNow
f_add(zs2, atrN)
// ---- bullish structure break (BOS / CHoCH) -> demand order block ----
if not na(lastPH) and not phUsed and close > lastPH + bosBuf * atrN
bool isCh = trend == -1
trend := 1
phUsed := true
lastEv := isCh ? "CHoCH" : "BOS"
lastEvBar := bar_index
if (isCh and useCHoCH) or ((not isCh) and useBOS)
float sq = dispOK ? (isCh ? 1.0 : 0.85) : 0.5
f_markStruct(true, lastPHbar, sq)
if useOB and dispOK and not na(lastPLbar) and bar_index - lastPLbar <= obLook
int off0 = bar_index - lastPLbar
int kSel = off0
for k = off0 to off0 + 4
if close[k] < open[k]
kSel := k
break
float oT = high[kSel]
float oB = low[kSel]
if oT - oB > 3.0 * atrN
oT := math.max(open[kSel], close[kSel])
oB := math.min(open[kSel], close[kSel])
if oT - oB < 2.0 * hwN
float cm = (oT + oB) * 0.5
oT := cm + hwN
oB := cm - hwN
Zone zo = f_new(true, oT, oB, time[kSel], 1)
zo.pBar := bar_index - kSel
zo.obQ := f_clamp(0.5 + 0.5 * (dispBody / atrN) / (2.0 * dispMult), 0.5, 1.0)
zo.structQ := sq
zo.swQ := 0.4
zo.volQ := volOK ? f_clamp((relVolMax3 - 1.0) / (relVolThr - 1.0), 0.0, 1.0) : 0.0
f_add(zo, atrN)
// ---- bearish structure break (BOS / CHoCH) -> supply order block ----
if not na(lastPL) and not plUsed and close < lastPL - bosBuf * atrN
bool isCh = trend == 1
trend := -1
plUsed := true
lastEv := isCh ? "CHoCH" : "BOS"
lastEvBar := bar_index
if (isCh and useCHoCH) or ((not isCh) and useBOS)
float sq = dispOK ? (isCh ? 1.0 : 0.85) : 0.5
f_markStruct(false, lastPLbar, sq)
if useOB and dispOK and not na(lastPHbar) and bar_index - lastPHbar <= obLook
int off0 = bar_index - lastPHbar
int kSel = off0
for k = off0 to off0 + 4
if close[k] > open[k]
kSel := k
break
float oT = high[kSel]
float oB = low[kSel]
if oT - oB > 3.0 * atrN
oT := math.max(open[kSel], close[kSel])
oB := math.min(open[kSel], close[kSel])
if oT - oB < 2.0 * hwN
float cm = (oT + oB) * 0.5
oT := cm + hwN
oB := cm - hwN
Zone zo = f_new(false, oT, oB, time[kSel], 1)
zo.pBar := bar_index - kSel
zo.obQ := f_clamp(0.5 + 0.5 * (dispBody / atrN) / (2.0 * dispMult), 0.5, 1.0)
zo.structQ := sq
zo.swQ := 0.4
zo.volQ := volOK ? f_clamp((relVolMax3 - 1.0) / (relVolThr - 1.0), 0.0, 1.0) : 0.0
f_add(zo, atrN)
// ---- higher-timeframe zones (confirmed HTF pivots only) ----
f_ingest(1, en5, ph1, pb1, pw1, pl1, lb1, lw1, at1, rv1, tp1, atrN)
f_ingest(2, en15, ph2, pb2, pw2, pl2, lb2, lw2, at2, rv2, tp2, atrN)
f_ingest(3, en60, ph3, pb3, pw3, pl3, lb3, lw3, at3, rv3, tp3, atrN)
f_ingest(4, en240, ph4, pb4, pw4, pl4, lb4, lw4, at4, rv4, tp4, atrN)
f_ingest(5, enD, ph5, pb5, pw5, pl5, lb5, lw5, at5, rv5, tp5, atrN)
f_ingest(6, enW, ph6, pb6, pw6, pl6, lb6, lw6, at6, rv6, tp6, atrN)
f_ingest(7, enM, ph7, pb7, pw7, pl7, lb7, lw7, at7, rv7, tp7, atrN)
// ---- lifecycle: touches, rejection, mitigation, breakout, role reversal, scoring ----
f_update(atrN)
// ───────────────────────────────────────────── RENDERING (LAST BAR) ─────────────────────────────────────────────
Zone nSup = na
Zone nRes = na
int cSup = 0
int cRes = 0
var table tblS = showStrength ? table.new(f_pos(strPos), 2, 5, bgcolor = color.new(#0A0F1A, 6), frame_color = #2F3E5C, frame_width = 1, border_width = 0) : na
var table tblD = showDash ? table.new(f_pos(dashPos), 2, 13, bgcolor = color.new(#0A0F1A, 6), frame_color = #2F3E5C, frame_width = 1, border_width = 1, border_color = color.new(#2F3E5C, 40)) : na
if barstate.isfirst
if showStrength
table.merge_cells(tblS, 0, 0, 1, 0)
table.merge_cells(tblS, 0, 2, 1, 2)
table.merge_cells(tblS, 0, 4, 1, 4)
if showDash
table.merge_cells(tblD, 0, 0, 1, 0)
if barstate.islast and enableInd
for b in dBoxes
box.delete(b)
array.clear(dBoxes)
for l in dLbls
label.delete(l)
array.clear(dLbls)
float atrL = nz(atrV, 1.0)
float tolL = mergeMult * atrL
int barMs = timeframe.in_seconds() * 1000
for side = 0 to 1
bool isS = side == 0
array<int> cidx = array.new<int>()
array<float> csc = array.new<float>()
int nzs = array.size(zones)
if nzs > 0
for i = 0 to nzs - 1
Zone zc = array.get(zones, i)
if zc.isSup == isS and f_visible(zc)
array.push(cidx, i)
array.push(csc, zc.score)
int m = array.size(cidx)
if m > 0
array<int> srt = array.sort_indices(csc, order.descending)
int lim = math.min(m, maxZones)
for j = 0 to lim - 1
Zone zd = array.get(zones, array.get(cidx, array.get(srt, j)))
f_draw(zd, barMs, tolL)
if isS
cSup += 1
if f_mid(zd) < close and (na(nSup) or f_mid(zd) > f_mid(nSup))
nSup := zd
else
cRes += 1
if f_mid(zd) > close and (na(nRes) or f_mid(zd) < f_mid(nRes))
nRes := zd
// ---- Zone Strength panel ----
if showStrength and not na(tblS)
float rS = na(nRes) ? 0.0 : nRes.score
float sS = na(nSup) ? 0.0 : nSup.score
table.cell(tblS, 0, 0, "Zone Strength", text_color = color.white, text_halign = text.align_center, text_size = size.normal, bgcolor = color.new(#0A0F1A, 0))
table.cell(tblS, 0, 1, "Resistance", text_color = color.white, text_halign = text.align_left, text_size = size.small)
table.cell(tblS, 1, 1, na(nRes) ? "--" : str.tostring(math.round(rS)) + "%", text_color = color.white, text_halign = text.align_right, text_size = size.small)
table.cell(tblS, 0, 2, f_bar(rS), text_color = C_RES_STRONG, text_halign = text.align_left, text_size = size.small)
table.cell(tblS, 0, 3, "Support", text_color = color.white, text_halign = text.align_left, text_size = size.small)
table.cell(tblS, 1, 3, na(nSup) ? "--" : str.tostring(math.round(sS)) + "%", text_color = color.white, text_halign = text.align_right, text_size = size.small)
table.cell(tblS, 0, 4, f_bar(sS), text_color = C_SUP_STRONG, text_halign = text.align_left, text_size = size.small)
// ---- Details dashboard ----
if showDash and not na(tblD)
string trTxt = trend == 1 ? "BULLISH" : trend == -1 ? "BEARISH" : "NEUTRAL"
color trCol = trend == 1 ? C_SUP_STRONG : trend == -1 ? C_RES_STRONG : color.gray
string msTxt = (lastEvBar == 0 or bar_index - lastEvBar > 150) ? "RANGE" : lastEv
string supTxt = na(nSup) ? "--" : str.tostring(f_mid(nSup), format.mintick)
string resTxt = na(nRes) ? "--" : str.tostring(f_mid(nRes), format.mintick)
string supDist = "--"
string resDist = "--"
if not na(nSup)
float dd = close - nSup.top
supDist := str.tostring(dd / atrL, "#.##") + " ATR / " + str.tostring(dd / close * 100.0, "#.##") + "%"
if not na(nRes)
float dd2 = nRes.bot - close
resDist := str.tostring(dd2 / atrL, "#.##") + " ATR / " + str.tostring(dd2 / close * 100.0, "#.##") + "%"
int tS = na(nSup) ? 0 : f_tfCount(nSup)
int tR = na(nRes) ? 0 : f_tfCount(nRes)
string htfTxt = (tS >= 2 or tR >= 2 ? "ALIGNED" : "NONE") + " (S:" + str.tostring(tS) + " R:" + str.tostring(tR) + ")"
float avgSc = (na(nSup) and na(nRes)) ? 0.0 : ((na(nSup) ? 0.0 : nSup.score) + (na(nRes) ? 0.0 : nRes.score)) / ((na(nSup) ? 0 : 1) + (na(nRes) ? 0 : 1))
string qTxt = avgSc >= 70 ? "STRONG" : avgSc >= 50 ? "MODERATE" : "WEAK"
color qCol = avgSc >= 70 ? C_SUP_STRONG : avgSc >= 50 ? color.orange : C_RES_STRONG
table.cell(tblD, 0, 0, "SMC SUPPORT AND RESISTANCE", text_color = color.white, text_halign = text.align_center, text_size = size.small, bgcolor = color.new(#12233F, 0))
table.cell(tblD, 0, 1, "Current Trend", text_color = color.silver, text_halign = text.align_left, text_size = size.small)
table.cell(tblD, 1, 1, trTxt, text_color = trCol, text_halign = text.align_right, text_size = size.small)
table.cell(tblD, 0, 2, "Nearest Support", text_color = color.silver, text_halign = text.align_left, text_size = size.small)
table.cell(tblD, 1, 2, supTxt, text_color = C_SUP_STRONG, text_halign = text.align_right, text_size = size.small)
table.cell(tblD, 0, 3, "Nearest Resistance", text_color = color.silver, text_halign = text.align_left, text_size = size.small)
table.cell(tblD, 1, 3, resTxt, text_color = C_RES_STRONG, text_halign = text.align_right, text_size = size.small)
table.cell(tblD, 0, 4, "Support Strength", text_color = color.silver, text_halign = text.align_left, text_size = size.small)
table.cell(tblD, 1, 4, na(nSup) ? "--" : str.tostring(math.round(nSup.score)) + "/100", text_color = color.white, text_halign = text.align_right, text_size = size.small)
table.cell(tblD, 0, 5, "Resistance Strength", text_color = color.silver, text_halign = text.align_left, text_size = size.small)
table.cell(tblD, 1, 5, na(nRes) ? "--" : str.tostring(math.round(nRes.score)) + "/100", text_color = color.white, text_halign = text.align_right, text_size = size.small)
table.cell(tblD, 0, 6, "Support Distance", text_color = color.silver, text_halign = text.align_left, text_size = size.small)
table.cell(tblD, 1, 6, supDist, text_color = color.white, text_halign = text.align_right, text_size = size.small)
table.cell(tblD, 0, 7, "Resistance Distance", text_color = color.silver, text_halign = text.align_left, text_size = size.small)
table.cell(tblD, 1, 7, resDist, text_color = color.white, text_halign = text.align_right, text_size = size.small)
table.cell(tblD, 0, 8, "Active Support Zones", text_color = color.silver, text_halign = text.align_left, text_size = size.small)
table.cell(tblD, 1, 8, str.tostring(cSup), text_color = color.white, text_halign = text.align_right, text_size = size.small)
table.cell(tblD, 0, 9, "Active Resistance Zones", text_color = color.silver, text_halign = text.align_left, text_size = size.small)
table.cell(tblD, 1, 9, str.tostring(cRes), text_color = color.white, text_halign = text.align_right, text_size = size.small)
table.cell(tblD, 0, 10, "HTF Confluence", text_color = color.silver, text_halign = text.align_left, text_size = size.small)
table.cell(tblD, 1, 10, htfTxt, text_color = color.white, text_halign = text.align_right, text_size = size.small)
table.cell(tblD, 0, 11, "Market Structure", text_color = color.silver, text_halign = text.align_left, text_size = size.small)
table.cell(tblD, 1, 11, msTxt, text_color = color.white, text_halign = text.align_right, text_size = size.small)
table.cell(tblD, 0, 12, "Zone Quality", text_color = color.silver, text_halign = text.align_left, text_size = size.small)
table.cell(tblD, 1, 12, qTxt, text_color = qCol, text_halign = text.align_right, text_size = size.small)
// ───────────────────────────────────────────── ALERTS ─────────────────────────────────────────────
// Events are produced only on closed bars and only on state transitions (not on every bar inside a zone).
alertcondition(array.get(ev, 0) and alSupTouch, "Price Entering Support", "SMC S&R: Price entered a support zone.")
alertcondition(array.get(ev, 1) and alResTouch, "Price Entering Resistance", "SMC S&R: Price entered a resistance zone.")
alertcondition(array.get(ev, 2) and alBullRej, "Bullish Rejection at Support", "SMC S&R: Bullish rejection at support.")
alertcondition(array.get(ev, 3) and alBearRej, "Bearish Rejection at Resistance", "SMC S&R: Bearish rejection at resistance.")
alertcondition(array.get(ev, 4) and alSupBrk, "Confirmed Support Breakout", "SMC S&R: Support zone broken (confirmed close).")
alertcondition(array.get(ev, 5) and alResBrk, "Confirmed Resistance Breakout", "SMC S&R: Resistance zone broken (confirmed close).")
alertcondition(array.get(ev, 6) and alBullRet, "Bullish Retest", "SMC S&R: Bullish retest of a former resistance zone (now support).")
alertcondition(array.get(ev, 7) and alBearRet, "Bearish Retest", "SMC S&R: Bearish retest of a former support zone (now resistance).")
alertcondition(array.get(ev, 8) and alStrSup, "Strong Support Detected", "SMC S&R: Strong support zone detected.")
alertcondition(array.get(ev, 9) and alStrRes, "Strong Resistance Detected", "SMC S&R: Strong resistance zone detected.")
alertcondition(array.get(ev, 10), "New Major Support", "SMC S&R: New major support zone.")
alertcondition(array.get(ev, 11), "New Major Resistance", "SMC S&R: New major resistance zone.")