本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ITTO-RYU
// v4.1 (2026-10-29): clean title, tooltips on all setting inputs, clearer Advanced input names, candle colouring off by default
// v4.2 (2026-10-30): tooltip fixes only: ATR length also sets liquidity width; five Advanced inputs marked as applying to every Style
// v4.3 (2026-10-30): alerts when a close first moves above the Bottom-out Stable or Confirm area (✓)
// v5.0 (2026-10-31): order blocks — the last opposite candle before each BOS / CHoCH move, with the volume traded inside it; low-volume blocks hidden by default
// v5.1 (2026-10-31): leg volume profile — volume at price from the Protected level (origin of the current leg) to the last bar, with POC and 70% value area
// v5.2 (2026-10-31): Smart POC levels — POC of each completed swing leg, kept only when the leg's volume is at least the 20-leg average; removed on a close through
// v5.3 (2026-11-01): wording only — the Bottom-out areas are described as recovery depth of the down leg (Stable 23.6–38.2%, Confirm 38.2–50% of the leg), not Fibonacci support; no logic change
// v5.4 (2026-11-03): English only — the Japanese characters are removed from the state names and the dashboard group cell (also in the state alert message); the Expected range row is off by default; tooltips carry no test figures or market references; no logic change
//@version=6
indicator("Auto Market Structure & Liquidity by [Itto-Ryu]", shorttitle = "Auto Structure", overlay = true, max_boxes_count = 200, max_lines_count = 100, max_labels_count = 100, max_bars_back = 2000)
// ─────────────────────────────── INPUTS ───────────────────────────────
G1 = "① Start here — Market & Style"
G2 = "② Pullback"
G3 = "③ Levels on chart"
G4 = "④ Dashboard"
G5 = "⑤ Colors"
G6 = "⑥ Advanced (Style = Custom)"
iMarket = input.string("Classic", "Market", options = ["Classic", "Crypto", "FX & Gold", "Custom"], group = G1, tooltip = "Sets the look-back to about 1 year. Bars per day are counted from your chart and multiplied by trading days per year: Classic 252 (stocks / indices), Crypto 365, FX & Gold 260, Custom = your number.")
iDays = input.int(252, "Trading days per year (Custom only)", minval = 50, maxval = 366, group = G1, tooltip = "Used only when Market = Custom. Bars per day are counted from your chart automatically, so one number works on every timeframe. Use your exchange's trading days per year (stocks ≈ 252, crypto 365).")
iStyle = input.string("Auto — follows chart TF", "Style", options = ["Auto — follows chart TF", "Scalp · fast · 1m–15m", "Swing · medium · 30m–4H", "Position · slow · D and above", "Custom"], group = G1, tooltip = "Auto picks Scalp/Swing/Position from your chart timeframe. Pick one yourself to override, e.g. Position values on a 1H chart for slower, steadier states.")
iPbMethod = input.string("ATR", "Pullback method", options = ["ATR", "Fibonacci"], group = G2, tooltip = "How the pullback zone and its Floor / Ceiling are measured while a trend is held. ATR = distance from the trend extreme in ATR units. Fibonacci = retracement of the trend's last leg between pivots (not the Protected-level leg used by the Fibonacci drawing).")
iPbLevel = input.string("Mid", "Pullback depth", options = ["Shallow", "Mid", "Deep", "Custom"], group = G2, tooltip = "How far price retraces into the trend. Shallow = near the extreme, Deep = far from it.")
iConfl = input.bool(false, "Highlight ATR/Fib confluence", group = G2, tooltip = "Off by default. Turn on to shade where the ATR zone and the Fibonacci zone overlap.")
iShowLiq = input.bool(true, "Liquidity zones", group = G3, tooltip = "Price areas just beyond recent swing highs / lows where many traders' orders tend to cluster. Structure only, not a forecast.")
iShowOb = input.bool(true, "Order blocks + volume", group = G3, tooltip = "The last opposite-colour candle before the move that broke structure (BOS / CHoCH), drawn from its high to its low and extended right until a close passes through it. The label shows the volume traded inside the block while that move formed, ranked against the last 30 blocks. Describes where the move started — not a forecast.")
iObHideLow = input.bool(true, "Hide low-volume order blocks", group = G3, tooltip = "Hides blocks whose volume is in the lowest third of the last 30 blocks. These are the least significant blocks.")
iObMax = input.int(4, "Order blocks per side", minval = 1, maxval = 8, group = G3, tooltip = "Live blocks kept on each side (demand / supply). The oldest is removed first.")
iShowVp = input.bool(true, "Leg volume profile", group = G3, tooltip = "Volume at price from the Protected level (the origin of the current structure leg) to the last bar, drawn as rows to the right of price. POC = the row with the most volume (solid line + label with its share of the leg's volume). Each bar's volume is spread evenly over its high–low range, so the profile is an estimate from chart-timeframe bars, not tick data. Shows where the leg traded most — not a forecast.")
iVpBars = input.int(0, "Profile anchor (bars back, 0 = auto)", minval = 0, maxval = 1999, group = G3, tooltip = "0 = start at the Protected level of the current structure leg (falls back to the latest swing when there is no trend). Any other number = that many bars back from the last bar.")
iVpRows = input.int(24, "Profile rows", minval = 8, maxval = 50, group = G3, inline = "vp", tooltip = "Rows = price bins of the profile. Width = how far the longest row reaches to the right, in bars.")
iVpWidth = input.int(24, "Width", minval = 10, maxval = 80, group = G3, inline = "vp")
iVpAlpha = input.int(82, "Profile transparency", minval = 50, maxval = 95, group = G3, tooltip = "Higher = lighter rows. The POC row is drawn 35 points stronger and the value-area rows 12 points stronger than this.")
iShowSp = input.bool(true, "Smart POC levels", group = G3, tooltip = "POC of each completed swing leg (same swings as Structure), kept only when the leg's volume is at least the average of the last 20 legs; a close through the level removes it. Shows where a high-volume leg traded most — a reference level, not a signal or a target.")
iSpMinVol = input.float(1.0, "Smart POC min volume (× 20-leg average)", minval = 0.5, maxval = 3, step = 0.1, group = G3, tooltip = "Legs whose volume is below this multiple of the recent average do not create a level. 1.0 = the default.")
iSpMax = input.int(6, "Smart POC levels kept", minval = 1, maxval = 12, group = G3, tooltip = "Oldest levels are removed first.")
iVpVa = input.bool(true, "Value area 70%", group = G3, tooltip = "Dotted lines at the top and bottom of the rows that hold 70% of the leg's volume around the POC.")
iShowBox = input.bool(true, "Compress box", group = G3, tooltip = "Grey dashed box drawn while volatility (ATR rank) is in its lowest 10% over the look-back.")
iShowBrk = input.bool(true, "Breakout / Breakdown lines", group = G3, tooltip = "Lines at the top and bottom of the latest compress box while it is live. A close beyond one with a clean move sets Breakout Up / Breakdown.")
iShowPb = input.bool(true, "Pullback zone + Floor / Ceiling", group = G3, tooltip = "Shown while the state machine holds a trend. Zone = where a pullback is normal for the chosen depth; a close beyond the Floor (uptrend) or Ceiling (downtrend) ends the trend memory.")
iShowFlip = input.bool(true, "Protected level", group = G3, tooltip = "The swing low (uptrend) or high (downtrend) that must hold. A close beyond it is a CHoCH.")
iZzK = input.float(2.0, "Swing size (× ATR)", minval = 0.5, step = 0.25, group = G3, tooltip = "A swing high/low counts only after price reverses at least this many ATR(14) from it. Larger = fewer, more significant swings. Swings always alternate high / low.")
iShowMs = input.bool(true, "BOS / CHoCH", group = G3, tooltip = "Structure breaks on closed bars. BOS = close beyond the last swing in the direction of the current structure. CHoCH = close beyond the last swing against it (structure changes direction).")
iShowSwing = input.bool(true, "Swing High / Low", group = G3, tooltip = "Highest high and lowest low of the swing look-back, plus their midpoint. Shown in WAIT and Sideways states.")
iShowFib = input.bool(true, "Fibonacci retracement", group = G3, tooltip = "Leg from the Protected level to the latest extreme. The 61.8% golden ratio is drawn in gold.")
iShowBo = input.bool(true, "Bottom-out areas", group = G3, tooltip = "Downtrend only, on the structure leg from the Protected High to its low. Recovery depth measured up from the low: Stable = 23.6–38.2% of the leg, Confirm = 38.2–50%. ✓ when the last close is above the area, with an alert for each ✓ (works even when the areas are hidden). Depth marks only: they say how much of the leg has been recovered, not Fibonacci support and not a signal.")
iExtMode = input.string("Off", "Fibonacci extension", options = ["Auto", "Up", "Down", "Off"], group = G3, tooltip = "3-point extension levels 1.272 / 1.618 / 2.0 / 2.618 from the last two pivots. Auto follows the state direction. Reference geometry only — not targets.")
iShowTbl = input.bool(true, "Show dashboard", group = G4, tooltip = "State, reason, expected range, higher timeframe, structure, levels and preset in one table.")
iTblSize = input.string("Small", "Size", options = ["Tiny", "Small", "Normal", "Large"], group = G4, tooltip = "Text size of the dashboard.")
iTblPos = input.string("Top Right", "Position", options = ["Top Right", "Bottom Right", "Top Left", "Bottom Left"], group = G4, tooltip = "Corner of the chart where the dashboard sits.")
iShowRng = input.bool(false, "Expected range row", group = G4, tooltip = "A typical high-to-low width for the next 10 bars, from ATR(14). It says how wide, not which way.")
iShowPre = input.bool(true, "Preset row", group = G4, tooltip = "Shows the Market and Style in use, with bars per day counted from the chart.")
iBarBy = input.string("Off", "Color candles by", options = ["Structure", "State", "Off"], group = G5, tooltip = "Off (default) = your chart's own candle colours. Structure = green from CHoCH ↑ until CHoCH ↓ (red), grey before the first break. State = TREND / READY / WAIT colours. Descriptive only — not entry timing.")
iBarCol = iBarBy != "Off"
cUp = input.color(#009E73, "Up / TREND", group = G5, inline = "c1")
cDn = input.color(#D55E00, "Down", group = G5, inline = "c1")
cReady = input.color(#0072B2, "READY", group = G5, inline = "c2")
cWait = input.color(#E69F00, "WAIT", group = G5, inline = "c2")
cLiq = input.color(#8E44AD, "Liquidity", group = G5, inline = "c3")
cPb = input.color(#F2A900, "Pullback", group = G5, inline = "c3")
cBoS = input.color(#56B4E9, "Bottom-out Stable", group = G5, inline = "c4")
cBoC = input.color(#009E73, "Bottom-out Confirm", group = G5, inline = "c4")
cGold = input.color(#FFD700, "Golden ratio", group = G5)
cObUp = input.color(#7FB3D5, "Demand block", group = G5, inline = "c5")
cObDn = input.color(#E6A29C, "Supply block", group = G5, inline = "c5")
cVp = input.color(#9BB0C1, "Volume profile", group = G5, inline = "c6")
cPoc = input.color(#E67E22, "POC", group = G5, inline = "c6")
iCusNS = input.int(5, "Momentum short (bars)", minval = 2, group = G6, inline = "a1", tooltip = "Custom style only. Short and long momentum look-backs, in bars.")
iCusNL = input.int(20, "Momentum long (bars)", minval = 3, group = G6, inline = "a1")
iCusER = input.int(10, "Efficiency Ratio length", minval = 3, group = G6, inline = "a2", tooltip = "Custom style only. Efficiency Ratio look-back, and bars left / right that confirm a pivot.")
iCusPv = input.int(5, "Pivot left / right bars", minval = 2, group = G6, inline = "a2")
iCusDon = input.int(20, "Swing look-back (bars)", minval = 5, group = G6, inline = "a3", tooltip = "Custom style only. Swing look-back = bars used for Swing High / Low. Breakout window = bars a finished compress box can still be broken.")
iCusBrkL = input.int(10, "Breakout window (bars)", minval = 1, group = G6, inline = "a3")
iCusBrkH = input.int(3, "Breakout hold (bars)", minval = 1, group = G6, inline = "a4", tooltip = "Custom style only. Bars a Breakout state is kept, and the minimum bars any state must last before it can change.")
iCusHold = input.int(2, "Minimum state hold (bars)", minval = 1, group = G6, inline = "a4")
iAtrLen = input.int(14, "ATR length", minval = 2, group = G6, tooltip = "Applies to every Style. ATR used by momentum, volatility rank, pullback zones and liquidity zone width / merge distance. Swings and the expected range always use ATR(14).")
iErOn = input.float(0.30, "Efficiency Ratio trend threshold", step = 0.01, group = G6, tooltip = "Applies to every Style. Efficiency Ratio at or above which the path counts as clean (trend on). It switches off 0.05 lower.")
iCnHold = input.int(3, "Chop ↔ Neutral hold", minval = 1, group = G6, tooltip = "Applies to every Style. Bars a Chop or Neutral state must last before switching to the other. Damps the most frequent back-and-forth.")
iGrHold = input.int(3, "Group change hold", minval = 1, group = G6, tooltip = "Applies to every Style. Bars the WAIT / READY / TREND group must last before it can change (Volatile and Breakout override).")
iSmooth = input.int(3, "Feature smoothing (EMA bars)", minval = 1, group = G6, tooltip = "Applies to every Style. Smooths ER and long momentum before states are assigned. 1 = no smoothing.")
iCusA = input.float(0.5, "Custom ATR zone start (× ATR)", step = 0.1, group = G6, inline = "p1", tooltip = "Pullback depth = Custom only. Distances from the trend extreme in ATR: zone start, zone end, Floor / Ceiling.")
iCusB = input.float(1.5, "end", step = 0.1, group = G6, inline = "p1")
iCusF = input.float(2.0, "Floor / Ceiling", step = 0.1, group = G6, inline = "p1")
iCusR1 = input.float(38.2, "Custom Fib zone start %", group = G6, inline = "p2", tooltip = "Pullback depth = Custom only. Fibonacci retracement of the trend leg: zone start %, zone end %, Floor / Ceiling %.")
iCusR2 = input.float(61.8, "end %", group = G6, inline = "p2")
iCusRF = input.float(78.6, "Floor / Ceiling %", group = G6, inline = "p2")
// ─────────────────────────────── DATA / PRESETS ───────────────────────────────
tfSec = timeframe.in_seconds()
styleEff = switch
str.startswith(iStyle, "Scalp") => "Scalp"
str.startswith(iStyle, "Swing") => "Swing"
str.startswith(iStyle, "Position") => "Position"
iStyle == "Custom" => "Custom"
tfSec <= 900 => "Scalp"
tfSec < 86400 => "Swing"
=> "Position"
[nS, nL, erLen, pvLen, donLen, brkLook, brkHold, minHold] = switch styleEff
"Scalp" => [3, 10, 8, 3, 10, 6, 2, 1]
"Swing" => [5, 20, 10, 5, 20, 10, 3, 2]
"Position" => [8, 30, 14, 8, 30, 15, 4, 3]
=> [iCusNS, iCusNL, iCusER, iCusPv, iCusDon, iCusBrkL, iCusBrkH, iCusHold]
// Rank window ≈ 1 year: bars per session day (counted on the chart, largest completed day) × trading days per year, capped at 5000
int daysPerYear = switch iMarket
"Crypto" => 365
"FX & Gold" => 260
"Custom" => iDays
=> 252
var int dayCnt = 0
var int barsPerDay = 0
if timeframe.change("D")
barsPerDay := math.max(barsPerDay, dayCnt)
dayCnt := 1
else
dayCnt += 1
int rankRaw = switch
timeframe.isweekly => math.round(52.0 / timeframe.multiplier)
timeframe.ismonthly => math.round(12.0 / timeframe.multiplier)
timeframe.isdaily => math.round(daysPerYear / timeframe.multiplier)
=> barsPerDay > 0 ? barsPerDay * daysPerYear : 50
int rankBars = math.max(50, math.min(rankRaw, 5000))
// ─────────────────────────────── FEATURES ───────────────────────────────
f_er(float src, int n) =>
float path = math.sum(math.abs(ta.change(src)), n)
path > 0 ? math.abs(src - src[n]) / path : 0.0
atr = ta.atr(iAtrLen)
atr14 = ta.atr(14)
mS = (close - close[nS]) / atr
mL = ta.ema((close - close[nL]) / atr, iSmooth)
er = ta.ema(f_er(close, erLen), iSmooth)
atrPct = ta.percentrank(atr, rankBars)
mPct = ta.percentrank(math.abs(mL), rankBars)
dirL = int(math.sign(mL))
dirS = int(math.sign(mS))
erOff = iErOn - 0.05
ph = ta.pivothigh(high, pvLen, pvLen)
pl = ta.pivotlow(low, pvLen, pvLen)
swHi = ta.highest(high, donLen)[1]
swLo = ta.lowest(low, donLen)[1]
// HTF flag (non-repainting: [1] + lookahead_on)
htfTf = tfSec <= 900 ? "60" : tfSec <= 3600 ? "240" : tfSec <= 14400 ? "D" : tfSec <= 86400 ? "W" : "M"
htfRank = htfTf == "M" ? 60 : htfTf == "W" ? 104 : 252
[htfDir, htfPct] = request.security(syminfo.tickerid, htfTf, [math.sign(close - close[nL])[1], ta.percentrank(math.abs((close - close[nL]) / ta.atr(iAtrLen)), htfRank)[1]], lookahead = barmerge.lookahead_on)
// Pullback level table
[pbA, pbB, pbF] = switch iPbLevel
"Shallow" => [0.3, 1.0, 1.5]
"Mid" => [0.5, 1.5, 2.0]
"Deep" => [1.0, 2.0, 3.0]
=> [iCusA, iCusB, iCusF]
[fbR1, fbR2, fbRF] = switch iPbLevel
"Shallow" => [0.236, 0.382, 0.618]
"Mid" => [0.382, 0.618, 0.786]
"Deep" => [0.5, 0.786, 1.0]
=> [iCusR1 / 100, iCusR2 / 100, iCusRF / 100]
// ─────────────────────────────── REGIME (state machine, closed bars only) ───────────────────────────────
// state codes: 0 warm-up · 1 Volatile · 2/3 Breakout Up/Down · 4/5 Pullback Up/Down · 6 Compressed · 7 Chop · 8/9 Up/Down · 10/11 Sideways Up/Down · 12 Neutral
var bool trendOn = false
var bool squeezeOn = false
var bool volOn = false
var bool moveOn = false
var bool lowEr = false
var int state = 0
var int stateBars = 0
var int groupBars = 0
var string reason = ""
// trend memory
var int trendDir = 0
var float trendExt = na
var int trendExtBar = na
var float atrExt = na
// pivots (latest two of each)
var float ph1 = na
var int ph1b = na
var float ph0 = na
var int ph0b = na
var float pl1 = na
var int pl1b = na
var float pl0 = na
var int pl0b = na
// compress box
var bool boxActive = false
var bool boxLive = false
var float boxTop = na
var float boxBot = na
var int boxLeft = na
var int boxFrozenBar = na
var int brkUntil = -1
var int brkDir = 0
var array<box> cBoxes = array.new<box>()
// liquidity zones
var array<float> lzHiP = array.new<float>()
var array<float> lzHiA = array.new<float>()
var array<int> lzHiN = array.new<int>()
var array<box> lzHiB = array.new<box>()
var array<float> lzLoP = array.new<float>()
var array<float> lzLoA = array.new<float>()
var array<int> lzLoN = array.new<int>()
var array<box> lzLoB = array.new<box>()
var array<label> sweepLbl = array.new<label>()
// order blocks
var array<box> obB = array.new<box>()
var array<int> obS = array.new<int>()
var array<float> obT = array.new<float>()
var array<float> obBt = array.new<float>()
var array<bool> obHit = array.new<bool>()
var array<float> obVolHist = array.new<float>()
var int obLastUp = na
var int obLastDn = na
// smart POC levels
var array<float> spP_ = array.new<float>()
var array<float> spH_ = array.new<float>()
var array<int> spSide = array.new<int>()
var array<line> spL = array.new<line>()
var array<label> spT_ = array.new<label>()
var array<float> spVolHist = array.new<float>()
// market structure (BOS / CHoCH)
var int msDir = 0
var bool phBroken = false
var bool plBroken = false
// ATR zigzag swings (alternating) + Dow trend with protected level
var int zzLeg = 0
var float zzHi = na
var int zzHiB = na
var float zzLo = na
var int zzLoB = na
var float sh1 = na
var int sh1b = na
var float sh0 = na
var float sl1 = na
var int sl1b = na
var float sl0 = na
var bool shBroken = false
var bool slBroken = false
var int stTrend = 0
var float protLvl = na
var int protB = na
var array<line> msLines = array.new<line>()
var array<label> msLabels = array.new<label>()
// pullback levels (from trend memory)
var float zTop = na
var float zBot = na
var float zFloor = na
var float zTopAlt = na
var float zBotAlt = na
var float flipLvl = na
var int flipBar = na
// events for alerts
bool evGroup = false
bool evBrkUp = false
bool evBrkDn = false
bool evPbStart = false
bool evFloor = false
bool evFlip = false
bool evSweepHi = false
bool evSweepLo = false
bool evObTouch = false
bool evBos = false
bool evChoch = false
f_group(int s) =>
s == 0 ? "—" : (s == 1 or s == 7 or s == 12) ? "WAIT" : (s >= 4 and s <= 6) ? "READY" : "TREND"
f_name(int s) =>
switch s
1 => "Volatile"
2 => "Breakout Up"
3 => "Breakdown"
4 => "Pullback Up"
5 => "Pullback Down"
6 => "Compressed"
7 => "Chop"
8 => "Up"
9 => "Down"
10 => "Sideways Up"
11 => "Sideways Down"
12 => "Neutral"
=> "— warming up"
f_dir(int s) =>
(s == 2 or s == 4 or s == 8 or s == 10) ? 1 : (s == 3 or s == 5 or s == 9 or s == 11) ? -1 : 0
// volume traded inside a price band over the last len bars (each bar's volume spread evenly over its range)
f_obVol(int len, float top, float bot) =>
float s = 0.0
for k = 1 to math.max(1, math.min(len, 1999))
float rg = math.max(high[k] - low[k], syminfo.mintick)
float ov = math.max(0.0, math.min(high[k], top) - math.max(low[k], bot))
s += nz(volume[k]) * ov / rg
s
// tercile of v among the stored block volumes: 0 low · 1 mid · 2 high (no history → mid)
f_obRank(float v) =>
int lower = 0
int n = obVolHist.size()
if n > 0
for i = 0 to n - 1
if obVolHist.get(i) < v
lower += 1
float pct = n > 0 ? lower / n : 0.5
pct < 0.333 ? 0 : pct < 0.667 ? 1 : 2
// POC of the bars from a to b (bar indexes in the past): [poc price, half row, total volume]
f_legPoc(int a, int b) =>
int ka = bar_index - a
int kb = bar_index - b
float lo = low[kb]
float hi = high[kb]
for k = kb to ka
hi := math.max(hi, high[k])
lo := math.min(lo, low[k])
float step = (hi - lo) / iVpRows
array<float> rows = array.new<float>(iVpRows, 0.0)
float tot = 0.0
if step > 0
for k = kb to ka
float v = nz(volume[k])
float rg = math.max(high[k] - low[k], step * 0.01)
int j0 = math.max(0, math.min(iVpRows - 1, math.floor((low[k] - lo) / step)))
int j1 = math.max(0, math.min(iVpRows - 1, math.floor((high[k] - lo) / step)))
for j = j0 to j1
float bt = lo + j * step
float ov = math.max(0.0, math.min(high[k], bt + step) - math.max(low[k], bt))
rows.set(j, rows.get(j) + v * ov / rg)
tot += v
int jp = 0
float vmax = 0.0
for j = 0 to iVpRows - 1
if rows.get(j) > vmax
vmax := rows.get(j)
jp := j
[lo + (jp + 0.5) * step, step / 2, tot]
f_liqBox(int left, float top, float bot, int n) =>
box.new(left, top, bar_index, bot, xloc = xloc.bar_index, extend = extend.right, border_color = color.new(cLiq, 40), bgcolor = color.new(cLiq, n > 1 ? 70 : 85), text = n > 1 ? "Liquidity ×" + str.tostring(n) : "Liquidity", text_color = color.new(cLiq, 20), text_size = size.tiny, text_halign = text.align_right)
// lowest low since the last swing high / highest high since the last swing low / extreme since the protected level
atrZ = ta.atr(14)
int lenSH = na(sh1b) ? 1 : math.max(1, math.min(bar_index - sh1b + 1, 2000))
int lenSL = na(sl1b) ? 1 : math.max(1, math.min(bar_index - sl1b + 1, 2000))
int lenPR = na(protB) ? 1 : math.max(1, math.min(bar_index - protB + 1, 2000))
loSinceSH = ta.lowest(low, lenSH)
loSinceSHb = bar_index + ta.lowestbars(low, lenSH)
hiSinceSL = ta.highest(high, lenSL)
hiSinceSLb = bar_index + ta.highestbars(high, lenSL)
hiSincePR = ta.highest(high, lenPR)
hiSincePRb = bar_index + ta.highestbars(high, lenPR)
loSincePR = ta.lowest(low, lenPR)
loSincePRb = bar_index + ta.lowestbars(low, lenPR)
if barstate.isconfirmed and not na(atr)
// ── raw flags with hysteresis
trendOn := trendOn ? not (er < erOff or mPct < 60) : (er >= iErOn and mPct >= 66)
squeezeOn := squeezeOn ? not (atrPct > 15) : atrPct <= 10
volOn := volOn ? not (atrPct < 85) : atrPct >= 90
moveOn := moveOn ? not (mPct < 28) : mPct >= 33
lowEr := lowEr ? not (er >= iErOn) : er < erOff
// ── pivots (located pvLen bars back)
if not na(ph)
ph0 := ph1, ph0b := ph1b, ph1 := ph, ph1b := bar_index - pvLen, phBroken := false
if not na(pl)
pl0 := pl1, pl0b := pl1b, pl1 := pl, pl1b := bar_index - pvLen, plBroken := false
int spA = na
int spB = na
// ── ATR zigzag: a swing is confirmed once price reverses iZzK × ATR from the leg extreme (swings alternate)
if zzLeg == 0 and not na(atrZ)
zzLeg := 1, zzHi := high, zzHiB := bar_index, zzLo := low, zzLoB := bar_index
else if zzLeg == 1
if high > zzHi
zzHi := high, zzHiB := bar_index
if low <= zzHi - iZzK * atrZ
spA := sl1b
spB := zzHiB
sh0 := sh1, sh1 := zzHi, sh1b := zzHiB, shBroken := false
zzLeg := -1, zzLo := low, zzLoB := bar_index
else if zzLeg == -1
if low < zzLo
zzLo := low, zzLoB := bar_index
if high >= zzLo + iZzK * atrZ
spA := sh1b
spB := zzLoB
sl0 := sl1, sl1 := zzLo, sl1b := zzLoB, slBroken := false
zzLeg := 1, zzHi := high, zzHiB := bar_index
// ── smart POC: POC of the leg that just completed, kept only when the leg's volume is at least the recent average
if not na(spA) and not na(spB) and spB > spA and bar_index - spA <= 1999
[spP, spH, spT] = f_legPoc(spA, spB)
float spAvg = spVolHist.size() >= 5 ? spVolHist.avg() : na
spVolHist.push(spT)
if spVolHist.size() > 20
spVolHist.shift()
float spRel = na(spAvg) ? na : spT / spAvg
if iShowSp and not na(spRel) and spRel >= iSpMinVol and spT > 0
spP_.push(spP)
spH_.push(spH)
spSide.push(close > spP ? 1 : -1)
spL.push(line.new(spB, spP, bar_index + 21, spP, extend = extend.none, color = color.new(cPoc, 10), width = 1))
spT_.push(label.new(bar_index + 21, spP, "POC " + str.tostring(spP, format.mintick) + " · vol ×" + str.tostring(spRel, "#.#"), style = label.style_label_right, color = color.new(cPoc, 85), textcolor = color.new(cPoc, 0), size = size.tiny))
if spL.size() > iSpMax
spL.shift().delete()
spT_.shift().delete()
spP_.shift()
spH_.shift()
spSide.shift()
if spP_.size() > 0
for i = spP_.size() - 1 to 0
float pp = spP_.get(i)
float hh = spH_.get(i)
int sd2 = spSide.get(i)
if (sd2 == 1 and close < pp - hh) or (sd2 == -1 and close > pp + hh)
spL.get(i).delete()
spT_.get(i).delete()
spL.remove(i), spT_.remove(i), spP_.remove(i), spH_.remove(i), spSide.remove(i)
else
spT_.get(i).set_x(bar_index + 21)
spL.get(i).set_x2(bar_index + 21)
// ── Dow trend: BOS = close beyond the last swing in the trend direction (protected level moves up/down);
// CHoCH = close beyond the protected level (the swing that started the last BOS move)
int msBreak = 0
bool isChoch = false
float brkLvl = na
int brkX = na
if stTrend == 1 and not na(protLvl) and close < protLvl
msBreak := -1, isChoch := true, brkLvl := protLvl, brkX := protB
stTrend := -1, protLvl := hiSincePR, protB := hiSincePRb
else if stTrend == -1 and not na(protLvl) and close > protLvl
msBreak := 1, isChoch := true, brkLvl := protLvl, brkX := protB
stTrend := 1, protLvl := loSincePR, protB := loSincePRb
else if stTrend >= 0 and not na(sh1) and not shBroken and close > sh1
msBreak := 1, brkLvl := sh1, brkX := sh1b, shBroken := true
stTrend := 1, protLvl := loSinceSH, protB := loSinceSHb
else if stTrend <= 0 and not na(sl1) and not slBroken and close < sl1
msBreak := -1, brkLvl := sl1, brkX := sl1b, slBroken := true
stTrend := -1, protLvl := hiSinceSL, protB := hiSinceSLb
if msBreak != 0
evBos := not isChoch
evChoch := isChoch
msDir := msBreak
if iShowMs and not na(brkLvl)
color mc = msBreak == 1 ? cUp : cDn
msLines.push(line.new(brkX, brkLvl, bar_index, brkLvl, color = color.new(mc, 20), style = line.style_dashed, width = 1))
msLabels.push(label.new(math.round((brkX + bar_index) / 2), brkLvl, isChoch ? "CHoCH" : "BOS", style = msBreak == 1 ? label.style_label_down : label.style_label_up, color = color.new(mc, 100), textcolor = mc, size = size.tiny))
while msLines.size() > 12
msLines.shift().delete()
msLabels.shift().delete()
// ── order block: last opposite candle between the leg origin (new Protected level bar) and the break bar
if iShowOb and not na(protB)
int legLen = math.min(bar_index - protB, 1999)
int kOb = -1
if legLen >= 1
for k = 1 to legLen
if (msBreak == 1 and close[k] < open[k]) or (msBreak == -1 and close[k] > open[k])
kOb := k
break
if kOb >= 1
float obTop = high[kOb]
float obBot = low[kOb]
float obV = f_obVol(legLen, obTop, obBot)
int rk = f_obRank(obV)
obVolHist.push(obV)
if obVolHist.size() > 30
obVolHist.shift()
int obPrev = msBreak == 1 ? obLastUp : obLastDn
if not (iObHideLow and rk == 0) and (na(obPrev) or obPrev != bar_index - kOb)
if msBreak == 1
obLastUp := bar_index - kOb
else
obLastDn := bar_index - kOb
color oc = msBreak == 1 ? cObUp : cObDn
string vt = rk == 2 ? "high" : rk == 1 ? "mid" : "low"
obB.push(box.new(bar_index - kOb, obTop, bar_index + 21, obBot, xloc = xloc.bar_index, extend = extend.none, border_color = color.new(oc, 55), bgcolor = color.new(oc, rk == 2 ? 80 : 88), text = (msBreak == 1 ? "Demand" : "Supply") + " · vol " + vt + " " + str.tostring(obV, format.volume), text_color = color.new(oc, 0), text_size = size.tiny, text_halign = text.align_center, text_valign = text.align_center))
obS.push(msBreak), obT.push(obTop), obBt.push(obBot), obHit.push(false)
int cnt = 0
for i = 0 to obS.size() - 1
if obS.get(i) == msBreak
cnt += 1
if cnt > iObMax
for i = 0 to obS.size() - 1
if obS.get(i) == msBreak
obB.get(i).delete()
obB.remove(i), obS.remove(i), obT.remove(i), obBt.remove(i), obHit.remove(i)
break
// ── compress box (from raw squeeze flag)
int newBrk = 0
if boxActive
if close > boxTop
newBrk := 1
else if close < boxBot
newBrk := -1
else if not squeezeOn
boxActive := false, boxLive := true, boxFrozenBar := bar_index
else
boxTop := math.max(boxTop, high), boxBot := math.min(boxBot, low)
else if boxLive
if close > boxTop
newBrk := 1
else if close < boxBot
newBrk := -1
else if bar_index - boxFrozenBar > brkLook
boxLive := false
if newBrk != 0
int boxLen = (boxActive ? bar_index : boxFrozenBar) - boxLeft + 1
boxActive := false, boxLive := false
if dirS == newBrk and er >= iErOn and boxLen >= 3
brkDir := newBrk, brkUntil := bar_index + brkHold - 1
if not boxActive and not boxLive and squeezeOn and newBrk == 0
boxActive := true, boxTop := high, boxBot := low, boxLeft := bar_index
if iShowBox
cBoxes.push(box.new(bar_index, high, bar_index, low, border_color = color.new(color.gray, 30), bgcolor = color.new(color.gray, 85), border_style = line.style_dashed, text = "Compress", text_size = size.tiny, text_color = color.gray, text_valign = text.align_top))
if cBoxes.size() > 2
cBoxes.shift().delete()
if iShowBox and cBoxes.size() > 0 and (boxActive or boxLive)
b = cBoxes.last()
b.set_top(boxTop), b.set_bottom(boxBot), b.set_right(bar_index)
// ── pullback zone from trend memory (previous bar's memory)
zTop := na, zBot := na, zFloor := na, zTopAlt := na, zBotAlt := na
if trendDir != 0 and not na(trendExt)
H = trendExt
float atrZT = H - trendDir * pbA * atrExt
float atrZB = H - trendDir * pbB * atrExt
float atrFl = H - trendDir * pbF * atrExt
// Fib leg: last opposite pivot before the extreme
float L = na
if trendDir == 1
L := pl1b < trendExtBar ? pl1 : pl0b < trendExtBar ? pl0 : na
L := L >= H ? na : L
else
L := ph1b < trendExtBar ? ph1 : ph0b < trendExtBar ? ph0 : na
L := L <= H ? na : L
float fibZT = na(L) ? na : H - (H - L) * fbR1
float fibZB = na(L) ? na : H - (H - L) * fbR2
float fibFl = na(L) ? na : H - (H - L) * fbRF
if iPbMethod == "ATR"
zTop := atrZT, zBot := atrZB, zFloor := atrFl, zTopAlt := fibZT, zBotAlt := fibZB
else
zTop := fibZT, zBot := fibZB, zFloor := fibFl, zTopAlt := atrZT, zBotAlt := atrZB
flipLvl := trendDir == 1 ? pl1 : trendDir == -1 ? ph1 : na
flipBar := trendDir == 1 ? pl1b : trendDir == -1 ? ph1b : na
// ── candidate state (priority list)
int cand = 12
// enter on a counter-move (mS against the trend), then hold while price stays inside the zone
bool inPbUp = trendDir == 1 and (mS < 0 or state == 4) and not na(zFloor) and close >= zFloor and close <= zTop
bool inPbDn = trendDir == -1 and (mS > 0 or state == 5) and not na(zFloor) and close <= zFloor and close >= zTop
if na(atrPct) or na(mPct)
cand := 0
else if volOn and lowEr
cand := 1
else if bar_index <= brkUntil
cand := brkDir == 1 ? 2 : 3
else if inPbUp
cand := 4
else if inPbDn
cand := 5
else if squeezeOn and not trendOn
cand := 6
else if not trendOn and lowEr
cand := 7
else if trendOn
cand := dirL >= 0 ? 8 : 9
else if moveOn and not lowEr
int sideDir = trendDir != 0 ? trendDir : dirL
cand := sideDir >= 0 ? 10 : 11
int prev = state
int needHold = (state == 7 and cand == 12) or (state == 12 and cand == 7) ? math.max(minHold, iCnHold) : minHold
bool grpChange = f_group(cand) != f_group(state)
if cand != state and (cand <= 3 or (stateBars >= needHold and (not grpChange or groupBars >= iGrHold)))
groupBars := grpChange ? 1 : groupBars + 1
state := cand, stateBars := 1
else
stateBars += 1
groupBars += 1
// ── trend memory update
int sd = f_dir(state)
if state == 2 or state == 3 or state == 8 or state == 9
if trendDir != sd
trendDir := sd, trendExt := sd == 1 ? high : low, trendExtBar := bar_index, atrExt := atr
if trendDir == 1 and high > trendExt
trendExt := high, trendExtBar := bar_index, atrExt := atr
if trendDir == -1 and low < trendExt
trendExt := low, trendExtBar := bar_index, atrExt := atr
bool crossFlip = trendDir == 1 ? close < flipLvl : trendDir == -1 ? close > flipLvl : false
bool crossFloor = trendDir == 1 ? close < zFloor : trendDir == -1 ? close > zFloor : false
evFlip := crossFlip
evFloor := crossFloor
if crossFlip or crossFloor or state == 1
trendDir := 0, trendExt := na, trendExtBar := na, atrExt := na
// ── reason string
reason := "mL " + str.tostring(mL, "+0.0;-0.0") + " ATR (rank " + str.tostring(mPct, "#") + "%) · ER " + str.tostring(er, "0.00") + " · Vol rank " + str.tostring(atrPct, "#") + "%"
// ── events
evGroup := f_group(state) != f_group(prev) and prev != 0
evBrkUp := state == 2 and prev != 2
evBrkDn := state == 3 and prev != 3
evPbStart := (state == 4 or state == 5) and prev != state
// ── order blocks: a close through the block removes it; the first wick into it is an event
if obS.size() > 0
for i = obS.size() - 1 to 0
int obSd = obS.get(i)
float obTp = obT.get(i)
float obBm = obBt.get(i)
if (obSd == 1 and close < obBm) or (obSd == -1 and close > obTp)
obB.get(i).delete()
obB.remove(i), obS.remove(i), obT.remove(i), obBt.remove(i), obHit.remove(i)
else
obB.get(i).set_right(bar_index + 21)
if not obHit.get(i) and ((obSd == 1 and low <= obTp) or (obSd == -1 and high >= obBm))
obHit.set(i, true)
evObTouch := true
// ── liquidity zones: sweeps / taken first, then new pivots
if lzHiP.size() > 0
for i = lzHiP.size() - 1 to 0
float p = lzHiP.get(i)
if close > p or high > p
if close <= p
evSweepHi := true
if iShowLiq
sweepLbl.push(label.new(bar_index, high, "◆", style = label.style_none, textcolor = cLiq, size = size.small, tooltip = "Liquidity sweep: wick above the swing high, close back below"))
lzHiB.get(i).delete()
lzHiP.remove(i), lzHiA.remove(i), lzHiN.remove(i), lzHiB.remove(i)
if lzLoP.size() > 0
for i = lzLoP.size() - 1 to 0
float p = lzLoP.get(i)
if close < p or low < p
if close >= p
evSweepLo := true
if iShowLiq
sweepLbl.push(label.new(bar_index, low, "◆", style = label.style_none, textcolor = cLiq, size = size.small, tooltip = "Liquidity sweep: wick below the swing low, close back above"))
lzLoB.get(i).delete()
lzLoP.remove(i), lzLoA.remove(i), lzLoN.remove(i), lzLoB.remove(i)
while sweepLbl.size() > 30
sweepLbl.shift().delete()
if not na(ph) and iShowLiq
int hit = -1
for i = 0 to lzHiP.size() - 1
if lzHiP.size() > 0 and math.abs(ph - lzHiP.get(i)) <= 0.1 * atr
hit := i
break
if hit >= 0
lzHiP.set(hit, math.max(lzHiP.get(hit), ph))
lzHiN.set(hit, lzHiN.get(hit) + 1)
float pp = lzHiP.get(hit)
int left = lzHiB.get(hit).get_left()
lzHiB.get(hit).delete()
lzHiB.set(hit, f_liqBox(left, pp + 0.25 * lzHiA.get(hit), pp, lzHiN.get(hit)))
else
lzHiP.push(ph), lzHiA.push(atr), lzHiN.push(1)
lzHiB.push(f_liqBox(bar_index - pvLen, ph + 0.25 * atr, ph, 1))
if lzHiP.size() > 3
lzHiB.shift().delete()
lzHiP.shift(), lzHiA.shift(), lzHiN.shift()
if not na(pl) and iShowLiq
int hit = -1
for i = 0 to lzLoP.size() - 1
if lzLoP.size() > 0 and math.abs(pl - lzLoP.get(i)) <= 0.1 * atr
hit := i
break
if hit >= 0
lzLoP.set(hit, math.min(lzLoP.get(hit), pl))
lzLoN.set(hit, lzLoN.get(hit) + 1)
float pp = lzLoP.get(hit)
int left = lzLoB.get(hit).get_left()
lzLoB.get(hit).delete()
lzLoB.set(hit, f_liqBox(left, pp, pp - 0.25 * lzLoA.get(hit), lzLoN.get(hit)))
else
lzLoP.push(pl), lzLoA.push(atr), lzLoN.push(1)
lzLoB.push(f_liqBox(bar_index - pvLen, pl, pl - 0.25 * atr, 1))
if lzLoP.size() > 3
lzLoB.shift().delete()
lzLoP.shift(), lzLoA.shift(), lzLoN.shift()
// ─────────────────────────────── OUTPUT ───────────────────────────────
grp = f_group(state)
stDir = f_dir(state)
color stCol = grp == "WAIT" ? cWait : grp == "READY" ? cReady : grp == "TREND" ? (stDir >= 0 ? cUp : cDn) : color.gray
// state is only updated on closed bars, so the forming candle shows the last closed state (no repaint)
color strCol = stTrend == 1 ? cUp : stTrend == -1 ? cDn : color.gray
barcolor(iBarBy == "Structure" ? strCol : iBarBy == "State" and state != 0 ? stCol : na)
f_tfName(string tf) =>
tf == "60" ? "1H" : tf == "240" ? "4H" : tf == "120" ? "2H" : tf == "1D" ? "D" : tf == "1W" ? "W" : tf == "1M" ? "M" : timeframe.isminutes and str.tonumber(tf) < 60 ? tf + "m" : tf
string htfName = f_tfName(htfTf)
string chartName = f_tfName(timeframe.period)
string htfTip = "HTF = higher timeframe (" + htfName + "), compared with this chart (" + chartName + "). ✓ = same direction. ⚠ = opposite direction: the chart move may be a pullback or bounce inside the bigger move. Grey = the " + htfName + " momentum is weak (flat) or this chart has no trend. Uses the last closed " + htfName + " bar (no repaint). Information only, not a signal."
bool htfNa = na(htfPct) or timeframe.in_seconds(htfTf) <= tfSec
bool htfConflict = not htfNa and htfPct >= 33 and stDir != 0 and htfDir == -stDir
// Level drawings, rebuilt on the last bar only
var array<line> lvLines = array.new<line>()
var array<label> lvLabels = array.new<label>()
var array<box> lvBoxes = array.new<box>()
f_hl(int x1, float y, color c, string st, string txt, int w = 1) =>
if not na(y) and not na(x1)
lvLines.push(line.new(x1, y, bar_index + 8, y, color = c, style = st, width = w))
lvLabels.push(label.new(bar_index + 8, y, txt + " " + str.tostring(y, format.mintick), style = label.style_label_left, color = color.new(c, 85), textcolor = c, size = size.tiny))
if barstate.islast
for l in lvLines
l.delete()
for l in lvLabels
l.delete()
for b in lvBoxes
b.delete()
lvLines.clear(), lvLabels.clear(), lvBoxes.clear()
// Breakout / Breakdown while a compress box is live
if iShowBrk and (boxActive or boxLive)
f_hl(boxLeft, boxTop, cUp, line.style_dashed, "Breakout")
f_hl(boxLeft, boxBot, cDn, line.style_dashed, "Breakdown")
// Pullback zone + floor
if iShowPb and trendDir != 0 and not na(zTop)
lvBoxes.push(box.new(trendExtBar, math.max(zTop, zBot), bar_index + 21, math.min(zTop, zBot), border_color = color.new(cPb, 50), bgcolor = color.new(cPb, 85), text = "Pullback zone", text_size = size.tiny, text_color = cPb, text_halign = text.align_right))
f_hl(trendExtBar, zFloor, cPb, line.style_solid, trendDir == 1 ? "Pullback Floor" : "Pullback Ceiling")
if iConfl and not na(zTopAlt)
float oTop = math.min(math.max(zTop, zBot), math.max(zTopAlt, zBotAlt))
float oBot = math.max(math.min(zTop, zBot), math.min(zTopAlt, zBotAlt))
if oTop > oBot
lvBoxes.push(box.new(trendExtBar, oTop, bar_index + 21, oBot, border_color = na, bgcolor = color.new(cPb, 60), text = "Confluence", text_size = size.tiny, text_color = cPb))
// Protected level of the structure trend (a close beyond it = CHoCH)
if iShowFlip and stTrend != 0 and not na(protLvl)
f_hl(protB, protLvl, stTrend == 1 ? color.fuchsia : color.purple, line.style_dashed, stTrend == 1 ? "Protected Low" : "Protected High")
// Swing High / Low in WAIT and Sideways
if iShowSwing and (grp == "WAIT" or state == 10 or state == 11)
f_hl(bar_index - donLen, swHi, color.gray, line.style_dashed, "Swing High")
f_hl(bar_index - donLen, swLo, color.gray, line.style_dashed, "Swing Low")
f_hl(bar_index - donLen, (swHi + swLo) / 2, color.new(color.gray, 50), line.style_dotted, "Mid")
// Fibonacci retracement of the leg from the protected level, same swings as Structure
// Bull: 100% = Protected Low · 0% = highest high since it (may be unconfirmed)
// Bear: 100% = Protected High · 0% = lowest low since it (may be unconfirmed)
float fH = na
float fL = na
int fx = protB
int extB = na
if stTrend != 0 and not na(protLvl) and not na(protB) and protB < bar_index
float ext = stTrend == 1 ? high : low
extB := bar_index
for i = 1 to math.min(bar_index - protB, 1999)
if stTrend == 1 ? high[i] > ext : low[i] < ext
ext := stTrend == 1 ? high[i] : low[i]
extB := bar_index - i
if stTrend == 1
fL := protLvl, fH := ext
else
fH := protLvl, fL := ext
bool legOk = not na(fH) and not na(fL) and fH > fL
if iShowFib and legOk
for r in array.from(0.0, 0.236, 0.382, 0.5, 0.618, 0.786, 1.0)
float lv = stTrend == 1 ? fH - r * (fH - fL) : fL + r * (fH - fL)
string tag = r == 0.0 ? (stTrend == 1 ? " (swing high)" : " (swing low)") : r == 1.0 ? (stTrend == 1 ? " (protected low)" : " (protected high)") : r == 0.618 ? " (golden ratio)" : ""
if r == 0.618
f_hl(fx, lv, cGold, line.style_solid, "Fib " + str.tostring(r * 100, "#.#") + "%" + tag, 2)
else
f_hl(fx, lv, color.new(color.gray, 30), line.style_dotted, "Fib " + str.tostring(r * 100, "#.#") + "%" + tag)
// Bottom-out areas (downtrend only): recovery depth of the structure leg measured up from its low, Stable = 23.6–38.2%, Confirm = 38.2–50% (depth marks, not Fibonacci support)
// ✓ = the last close is above the area. Describes the state of the structure; not a signal.
if iShowBo and stTrend == -1 and legOk
float rng = fH - fL
float s1 = fL + 0.236 * rng
float s2 = fL + 0.382 * rng
float c2 = fL + 0.5 * rng
bool sOk = close > s2
bool cOk = close > c2
lvBoxes.push(box.new(extB, s2, bar_index + 21, s1, border_color = color.new(cBoS, 40), bgcolor = color.new(cBoS, 85), text = "Bottom-out Stable" + (sOk ? " ✓" : ""), text_size = size.tiny, text_color = cBoS, text_halign = text.align_right))
lvBoxes.push(box.new(extB, c2, bar_index + 21, s2, border_color = color.new(cBoC, 40), bgcolor = color.new(cBoC, 85), text = "Bottom-out Confirm" + (cOk ? " ✓" : ""), text_size = size.tiny, text_color = cBoC, text_halign = text.align_right))
// Fibonacci extension (3-point)
int extDir = iExtMode == "Up" ? 1 : iExtMode == "Down" ? -1 : iExtMode == "Auto" ? (grp == "WAIT" ? 0 : stDir) : 0
if extDir == 1 and not na(pl0) and pl1b > ph1b and pl0b < ph1b and pl0 < pl1 and pl1 < ph1
for k in array.from(1.272, 1.618, 2.0, 2.618)
f_hl(pl1b, pl1 + (ph1 - pl0) * k, color.teal, line.style_dotted, "Ext " + str.tostring(k))
if extDir == -1 and not na(ph0) and ph1b > pl1b and ph0b < pl1b and ph0 > ph1 and ph1 > pl1
for k in array.from(1.272, 1.618, 2.0, 2.618)
f_hl(ph1b, ph1 - (ph0 - pl1) * k, color.teal, line.style_dotted, "Ext " + str.tostring(k))
// Dashboard
tblPos = switch iTblPos
"Bottom Right" => position.bottom_right
"Top Left" => position.top_left
"Bottom Left" => position.bottom_left
=> position.top_right
tblSz = switch iTblSize
"Tiny" => size.tiny
"Normal" => size.normal
"Large" => size.large
=> size.small
// ── leg volume profile: from the Protected level (origin of the current leg) to the last bar, rebuilt on the last bar only
var array<box> vpBoxes = array.new<box>()
var line vpPocL = na
var label vpPocT = na
var line vpVahL = na
var line vpValL = na
if barstate.islast
for b in vpBoxes
b.delete()
vpBoxes.clear()
if not na(vpPocL)
vpPocL.delete()
if not na(vpPocT)
vpPocT.delete()
if not na(vpVahL)
vpVahL.delete()
if not na(vpValL)
vpValL.delete()
int vpA = iVpBars > 0 ? bar_index - iVpBars : stTrend != 0 and not na(protB) ? protB : not na(sh1b) and not na(sl1b) ? math.max(sh1b, sl1b) : na
if iShowVp and not na(vpA)
int vlen = math.max(1, math.min(bar_index - vpA, 1999))
float vhi = high
float vlo = low
for k = 0 to vlen
vhi := math.max(vhi, high[k])
vlo := math.min(vlo, low[k])
float step = (vhi - vlo) / iVpRows
if step > 0
array<float> rows = array.new<float>(iVpRows, 0.0)
float vtot = 0.0
for k = 0 to vlen
float v = nz(volume[k])
float rg = math.max(high[k] - low[k], step * 0.01)
int j0 = math.max(0, math.min(iVpRows - 1, math.floor((low[k] - vlo) / step)))
int j1 = math.max(0, math.min(iVpRows - 1, math.floor((high[k] - vlo) / step)))
for j = j0 to j1
float bt = vlo + j * step
float ov = math.max(0.0, math.min(high[k], bt + step) - math.max(low[k], bt))
rows.set(j, rows.get(j) + v * ov / rg)
vtot += v
int jp = 0
float vmax = 0.0
for j = 0 to iVpRows - 1
if rows.get(j) > vmax
vmax := rows.get(j)
jp := j
if vtot > 0 and vmax > 0
int ju = jp
int jd = jp
float acc = rows.get(jp)
while acc < 0.7 * vtot and (ju < iVpRows - 1 or jd > 0)
float up = ju < iVpRows - 1 ? rows.get(ju + 1) : -1.0
float dn = jd > 0 ? rows.get(jd - 1) : -1.0
if up >= dn
ju += 1
acc += up
else
jd -= 1
acc += dn
int x0 = bar_index + 22
for j = 0 to iVpRows - 1
int w = math.round(iVpWidth * rows.get(j) / vmax)
if w > 0
bool inVa = j >= jd and j <= ju
vpBoxes.push(box.new(x0, vlo + (j + 1) * step, x0 + w, vlo + j * step, xloc = xloc.bar_index, border_color = na, bgcolor = j == jp ? color.new(cPoc, math.max(iVpAlpha - 40, 20)) : color.new(cVp, inVa ? math.max(iVpAlpha - 12, 20) : iVpAlpha)))
float pocP = vlo + (jp + 0.5) * step
vpPocL := line.new(vpA, pocP, x0 + iVpWidth, pocP, color = color.new(cPoc, 10), style = line.style_solid, width = 1)
vpPocT := label.new(x0 + iVpWidth, pocP, "POC " + str.tostring(pocP, format.mintick) + " · " + str.tostring(100 * vmax / vtot, "#.#") + "% · " + str.tostring(vtot, format.volume), style = label.style_label_left, color = color.new(cPoc, 85), textcolor = color.new(cPoc, 0), size = size.tiny)
if iVpVa
vpVahL := line.new(vpA, vlo + (ju + 1) * step, x0, vlo + (ju + 1) * step, color = color.new(cVp, 55), style = line.style_dotted)
vpValL := line.new(vpA, vlo + jd * step, x0, vlo + jd * step, color = color.new(cVp, 55), style = line.style_dotted)
var table tbl = table.new(tblPos, 2, 9, bgcolor = color.new(#131722, 10), border_color = color.new(color.gray, 70), border_width = 1, frame_color = color.new(color.gray, 50), frame_width = 1)
f_row(int r, string k, string v, color vc, string tip = "") =>
tbl.cell(0, r, k, text_color = color.gray, text_size = tblSz, text_halign = text.align_left, tooltip = tip)
tbl.cell(1, r, v, text_color = vc, text_size = tblSz, text_halign = text.align_left, tooltip = tip)
if barstate.islast and iShowTbl
tbl.clear(0, 0, 1, 8)
tbl.cell(0, 0, "AUTO STRUCTURE · v5.4", text_color = color.white, text_size = tblSz, bgcolor = color.new(stCol, 40))
tbl.merge_cells(0, 0, 1, 0)
string gk = grp == "WAIT" ? "WAIT" : grp == "READY" ? "READY" : grp == "TREND" ? "TREND" : "—"
tbl.cell(0, 1, gk, text_color = color.white, text_size = tblSz, bgcolor = color.new(stCol, 20))
tbl.cell(1, 1, f_name(state), text_color = color.white, text_size = tblSz, bgcolor = color.new(stCol, 20))
f_row(2, "Reason", reason, color.silver)
int r = 3
float atrC = barstate.isconfirmed ? atr14 : atr14[1]
if iShowRng
f_row(r, "Next 10 bars", "range ≈ " + str.tostring(2.07 * atrC, format.mintick) + " – " + str.tostring(5.71 * atrC, format.mintick), color.white)
r += 1
string hD = htfDir > 0 ? " Up" : htfDir < 0 ? " Down" : " flat"
string cD = stDir > 0 ? " Up" : stDir < 0 ? " Down" : " no trend"
if htfNa
f_row(r, "HTF", htfName + " n/a — not enough history", color.gray, htfTip)
else if htfConflict
f_row(r, "HTF", "⚠ " + htfName + hD + " vs " + chartName + cD, cWait, htfTip)
else if htfPct >= 33 and stDir != 0
f_row(r, "HTF", "✓ " + htfName + hD + " = " + chartName + cD, stDir > 0 ? cUp : cDn, htfTip)
else
f_row(r, "HTF", htfName + (htfPct >= 33 ? hD : " flat") + " · " + chartName + cD, color.gray, htfTip)
r += 1
f_row(r, "Move (live)", "mL " + str.tostring(mL, "+0.0;-0.0") + " ATR · ER " + str.tostring(er, "0.00") + " · Vol rank " + str.tostring(atrPct, "#") + "%", color.silver)
r += 1
string hs = na(sh0) or na(sl0) ? "—" : (sh1 > sh0 ? "HH" : "LH") + " · " + (sl1 > sl0 ? "HL" : "LL")
string md = stTrend == 1 ? "Bullish" : stTrend == -1 ? "Bearish" : "—"
string pk = na(protLvl) ? "" : " · protected " + str.tostring(protLvl, format.mintick)
f_row(r, "Structure", md + " (" + hs + ")" + pk, stTrend == 1 ? cUp : stTrend == -1 ? cDn : color.gray, "Trend from structure breaks (Dow): Bullish after a close above the last swing high, stays Bullish until a close below the protected low (CHoCH). Swings = ATR zigzag (" + str.tostring(iZzK) + " × ATR), last two highs (HH/LH) and lows (HL/LL).")
r += 1
string lv = trendDir != 0 ? (trendDir == 1 ? "Floor " : "Ceiling ") + str.tostring(zFloor, format.mintick) + " · Protected " + str.tostring(protLvl, format.mintick) : "Swing H " + str.tostring(swHi, format.mintick) + " · L " + str.tostring(swLo, format.mintick)
f_row(r, "Levels", lv, color.silver)
r += 1
if iShowPre
string mk = iMarket + " (" + (timeframe.isintraday ? str.tostring(barsPerDay) + " bars/day × " : "") + str.tostring(daysPerYear) + " d)"
string sk = str.startswith(iStyle, "Auto") ? styleEff + " (auto · " + timeframe.period + ")" : styleEff
f_row(r, "Preset", mk + " · " + sk, color.gray)
// Data window values
plot(mS, "mS", display = display.data_window)
plot(mL, "mL", display = display.data_window)
plot(er, "ER", display = display.data_window)
plot(atrPct, "ATR pct", display = display.data_window)
plot(mPct, "Mom pct", display = display.data_window)
plot(state, "State code", display = display.data_window)
// Bottom-out ✓ events, bar by bar on the same leg as the drawing (downtrend: 100% = Protected High,
// 0% = lowest low since it). An event fires on the first closed bar above the area; a new leg starts fresh.
var int boLegB = na
var float boLo = na
var bool boSOk = false
var bool boCOk = false
bool evBoStable = false
bool evBoConfirm = false
if barstate.isconfirmed
if stTrend == -1 and not na(protLvl) and not na(protB) and protB < bar_index
bool boNew = protB != boLegB
if boNew
boLegB := protB
boLo := low
for i = 1 to math.min(bar_index - protB, 1999)
boLo := math.min(boLo, low[i])
else
boLo := math.min(boLo, low)
float boRng = protLvl - boLo
bool sNow = boRng > 0 and close > boLo + 0.382 * boRng
bool cNow = boRng > 0 and close > boLo + 0.5 * boRng
evBoStable := not boNew and sNow and not boSOk
evBoConfirm := not boNew and cNow and not boCOk
boSOk := sNow, boCOk := cNow
else
boLegB := na, boSOk := false, boCOk := false
// ─────────────────────────────── ALERTS ───────────────────────────────
if evGroup
alert('{"event":"group","group":"' + grp + '","state":"' + f_name(state) + '","reason":"' + reason + '","symbol":"' + syminfo.ticker + '"}', alert.freq_once_per_bar_close)
if evBrkUp or evBrkDn
alert('{"event":"' + (evBrkUp ? "breakout_up" : "breakdown") + '","close":' + str.tostring(close) + '}', alert.freq_once_per_bar_close)
if evPbStart
alert('{"event":"pullback_start","state":"' + f_name(state) + '"}', alert.freq_once_per_bar_close)
if evFloor
alert('{"event":"pullback_floor_crossed","close":' + str.tostring(close) + '}', alert.freq_once_per_bar_close)
if evFlip
alert('{"event":"flip_crossed","close":' + str.tostring(close) + '}', alert.freq_once_per_bar_close)
if evBos or evChoch
alert('{"event":"' + (evChoch ? "choch" : "bos") + '","direction":"' + (msDir == 1 ? "up" : "down") + '","close":' + str.tostring(close) + '}', alert.freq_once_per_bar_close)
if evBoStable or evBoConfirm
alert('{"event":"' + (evBoConfirm ? "bottom_out_confirm" : "bottom_out_stable") + '","close":' + str.tostring(close) + '}', alert.freq_once_per_bar_close)
if evObTouch
alert('{"event":"order_block_touch","close":' + str.tostring(close) + '}', alert.freq_once_per_bar_close)
if evSweepHi or evSweepLo
alert('{"event":"' + (evSweepHi ? "sweep_high" : "sweep_low") + '","close":' + str.tostring(close) + '}', alert.freq_once_per_bar_close)
alertcondition(evGroup and grp == "TREND", "Group → TREND", "Auto Structure: TREND on {{ticker}} {{interval}}")
alertcondition(evGroup and grp == "READY", "Group → READY", "Auto Structure: READY on {{ticker}} {{interval}}")
alertcondition(evGroup and grp == "WAIT", "Group → WAIT", "Auto Structure: WAIT on {{ticker}} {{interval}}")
alertcondition(evBrkUp, "Breakout Up", "Auto Structure: Breakout Up on {{ticker}} {{interval}}")
alertcondition(evBrkDn, "Breakdown", "Auto Structure: Breakdown on {{ticker}} {{interval}}")
alertcondition(evBos, "BOS", "Auto Structure: BOS on {{ticker}} {{interval}}")
alertcondition(evChoch, "CHoCH", "Auto Structure: CHoCH on {{ticker}} {{interval}}")
alertcondition(evSweepHi or evSweepLo, "Liquidity sweep", "Auto Structure: liquidity sweep on {{ticker}} {{interval}}")
alertcondition(evObTouch, "Order block touched", "Auto Structure: price reached an order block on {{ticker}} {{interval}}")
alertcondition(evBoStable, "Bottom-out Stable ✓", "Auto Structure: Bottom-out Stable ✓ on {{ticker}} {{interval}}")
alertcondition(evBoConfirm, "Bottom-out Confirm ✓", "Auto Structure: Bottom-out Confirm ✓ on {{ticker}} {{interval}}")