本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// © 2026 builtbyuba · Trend Regime Engine v1.0 · Aurora (trend defaults tuned for accuracy on BTC 2025 2H, tested on BTC 2026, ETH, SOL)
// Licensed under CC BY-NC-SA 4.0: https://creativecommons.org/licenses/by-nc-sa/4.0/
// Structure and pattern engine adapted from the author's own Pattern Structure Pro (MIT).
// Trend engine concept inspired by LuxAlgo's "SuperTrend AI (Clustering)".
// Independent implementation, no code reused.
//
// Chart-analysis tool, not a trading system. No entries, stops or targets.
// * Runs several ATR trails with different factors, scores each one's recent
// direction-correct movement, and clusters the scores (k-means, 3 groups).
// * The chosen factor drifts slowly toward the best cluster, so it does not jump.
// * Optional noise gate: a flip needs a CLOSE beyond the trail by gate × ATR (0 by default, tuned for accuracy).
// * Wave: display-only smoothing of the trail, restarted on every flip.
// * Quality: efficiency ratio × R², 0–100. How clean the move is, not a forecast.
// * Structure (adapted from our MIT Pattern Structure Pro engine, retuned for swings):
// confirmed swings, supply/demand zones, BOS/CHoCH, equal-high/low liquidity,
// previous day / week levels. Swing strength and spans adapt to the timeframe.
// Tuned for 2H / 4H. All states use closed bars only.
indicator("Trend Regime Engine", "TRE", overlay=true, max_bars_back=600, max_labels_count=150, max_lines_count=100, max_boxes_count=20)
// ───────────────────────── Inputs
string layout = input.string("Desktop", "Layout", options=["Desktop", "Mobile"], group="View", tooltip="Desktop: full level-ladder dashboard. Mobile: small, compact card made for phone screens.")
bool mobile = layout == "Mobile"
string G_T = "Trend engine"
int atrLen = input.int(10, "ATR length", minval=5, maxval=50, group=G_T)
float fMin = input.float(1.5, "Min factor", minval=0.5, maxval=5.0, step=0.25, group=G_T)
float fMax = input.float(3.0, "Max factor", minval=1.0, maxval=8.0, step=0.25, group=G_T)
float fStep = input.float(0.5, "Factor step", minval=0.25, maxval=1.0, step=0.25, group=G_T)
float perfAlpha = input.float(0.05, "Performance memory", minval=0.01, maxval=0.3, step=0.01, group=G_T, tooltip="Lower = longer memory. Score decays toward recent direction-correct movement.")
float drift = input.float(0.05, "Factor drift per bar", minval=0.05, maxval=1.0, step=0.05, group=G_T, tooltip="How fast the used factor moves toward the best cluster. 1 = jump immediately.")
float gate = input.float(0.0, "Noise gate • ATR", minval=0.0, maxval=1.0, step=0.05, group=G_T)
int warmup = input.int(100, "Warm-up bars", minval=30, maxval=500, group=G_T)
string G_Q = "Quality"
int qLen = input.int(20, "Quality lookback", minval=10, maxval=100, group=G_Q)
string G_S = "Style"
color upColor = input.color(#34D399, "Up", group=G_S, inline="c")
color dnColor = input.color(#FB7185, "Down", group=G_S, inline="c")
bool showFlips = input.bool(true, "Flip dots", group=G_S)
bool tintCandles = input.bool(false, "Tint candles", group=G_S)
float waveSmooth = input.float(0.3, "Wave smoothing", minval=0.1, maxval=1.0, step=0.05, group=G_S, tooltip="Display only: how closely the wave follows the trail. 1 = raw trail. Direction logic is unchanged.")
string htf1 = input.timeframe("240", "Higher timeframe 1", group=G_S, tooltip="Full adaptive TRE direction from the last completed higher-timeframe bar. Equal or lower timeframes are shown as a dash.")
string htf2 = input.timeframe("D", "Higher timeframe 2", group=G_S, tooltip="Uses the same ATR candidates, clustering, factor drift and noise gate as the chart TRE.")
int auroraStrength = input.int(84, "Aurora band transparency", minval=40, maxval=95, group=G_S, tooltip="Transparency of the band next to price. The band fades toward the trail.")
string panelStyle = input.string("Dashboard", "Panel", options=["Dashboard", "Compact"], group=G_S, tooltip="Dashboard: every reading, zone, level and pattern. Compact: direction, trend quality and top pattern.")
string dashPos = input.string("Top right", "Dashboard position", options=["Top right", "Top left", "Bottom left", "Bottom right"], group=G_S)
string G_ST = "Structure"
int strengthIn = input.int(0, "Swing strength (0 = auto)", minval=0, maxval=10, group=G_ST, tooltip="Auto: 4 on ≤2H, 3 on 4H and above. Right-hand bars needed to confirm a swing.")
float zoneDeparture = input.float(2.0, "Zone departure • ATR", minval=1.0, maxval=4.0, step=0.25, group=G_ST, tooltip="Only swings price left by at least this much become zones.")
float zoneMaxWidth = input.float(0.6, "Zone max width • ATR", minval=0.2, maxval=1.5, step=0.1, group=G_ST)
float breakTol = input.float(0.15, "Closed-bar break • ATR", minval=0.05, maxval=0.5, step=0.05, group=G_ST)
float eqTol = input.float(0.15, "Equal high/low • ATR", minval=0.05, maxval=0.5, step=0.05, group=G_ST)
bool showZones = input.bool(true, "Supply / demand zones", group=G_ST)
int zonesPerSide = input.int(1, "Zones per side on chart", minval=1, maxval=3, group=G_ST)
bool showBreaks = input.bool(false, "BOS / CHoCH", group=G_ST)
bool showLiquidity = input.bool(false, "Equal highs / lows (liquidity)", group=G_ST)
bool showHTFLevels = input.bool(false, "Previous day / week levels", group=G_ST)
int extendBars = input.int(10, "Extension • bars", minval=0, maxval=40, group=G_ST)
string G_P = "Patterns"
float equalTol = input.float(0.40, "Matching levels • ATR", minval=0.1, maxval=1.0, step=0.05, group=G_P)
float touchTol = input.float(0.40, "Boundary contact • ATR", minval=0.1, maxval=0.8, step=0.05, group=G_P)
float minQuality = input.float(55, "Minimum geometric quality", minval=0, maxval=100, step=5, group=G_P, tooltip="A geometry filter, not a direction probability.")
bool drawPattern = input.bool(false, "Draw top pattern", group=G_P)
bool showDouble = input.bool(true, "Double / Triple Top & Bottom", group=G_P)
bool showShoulders = input.bool(true, "Head & Shoulders / Inverse", group=G_P)
bool showTriangles = input.bool(true, "Triangles", group=G_P)
bool showWedges = input.bool(true, "Wedges", group=G_P)
bool showFlags = input.bool(true, "Flags / Pennants", group=G_P)
bool showChannels = input.bool(true, "Channels / Rectangles", group=G_P)
// ───────────────────────── Shared adaptive TRE engine
f_bestFactor(array<float> perf, array<float> fac) =>
float c0 = perf.percentile_linear_interpolation(25)
float c1 = perf.percentile_linear_interpolation(50)
float c2 = perf.percentile_linear_interpolation(75)
array<int> assign = array.new<int>(perf.size(), 0)
for iter = 0 to 4
for i = 0 to perf.size() - 1
float p = perf.get(i)
float d0 = math.abs(p - c0)
float d1 = math.abs(p - c1)
float d2 = math.abs(p - c2)
assign.set(i, d2 <= d1 and d2 <= d0 ? 2 : d1 <= d0 ? 1 : 0)
float s0 = 0.0
float s1 = 0.0
float s2 = 0.0
int n0 = 0
int n1 = 0
int n2 = 0
for i = 0 to perf.size() - 1
int a = assign.get(i)
float p = perf.get(i)
if a == 0
s0 += p
n0 += 1
else if a == 1
s1 += p
n1 += 1
else
s2 += p
n2 += 1
c0 := n0 > 0 ? s0 / n0 : c0
c1 := n1 > 0 ? s1 / n1 : c1
c2 := n2 > 0 ? s2 / n2 : c2
// best non-empty cluster = highest centroid
int best = 0
float bestC = na
for k = 0 to 2
float ck = k == 0 ? c0 : k == 1 ? c1 : c2
bool used = assign.includes(k)
if used and (na(bestC) or ck > bestC)
bestC := ck
best := k
float sum = 0.0
int cnt = 0
for i = 0 to fac.size() - 1
if assign.get(i) == best
sum += fac.get(i)
cnt += 1
[cnt > 0 ? sum / cnt : na, bestC]
// One price-normalised ATR trail step, used by every TRE timeframe.
f_engineTrail(float factor, float prevUpper, float prevLower, int prevTrend, float g, float a) =>
float up = hl2 + factor * a
float dn = hl2 - factor * a
float newUpper = na(prevUpper) ? up : close[1] < prevUpper + g * a ? math.min(up, prevUpper) : up
float newLower = na(prevLower) ? dn : close[1] > prevLower - g * a ? math.max(dn, prevLower) : dn
int t = prevTrend
if not na(prevUpper) and close > prevUpper + g * a
t := 1
else if not na(prevLower) and close < prevLower - g * a
t := -1
[newUpper, newLower, t]
// A written call owns its state; security requests evaluate it in their own context.
// The chart commits only on its close. HTF requests read the previous completed bar.
f_tre(bool commit) =>
float a = ta.atr(atrLen)
var array<float> fs = array.new<float>()
var array<float> us = array.new<float>()
var array<float> ls = array.new<float>()
var array<int> ts = array.new<int>()
var array<float> ps = array.new<float>()
if fs.size() == 0
float f = fMin
while f <= fMax + 1e-9
fs.push(f)
us.push(na)
ls.push(na)
ts.push(0)
ps.push(0.0)
f += fStep
float normalMove = nz((close - close[1]) / a)
if commit and not na(a)
for i = 0 to fs.size() - 1
int prevT = ts.get(i)
[u, l, t] = f_engineTrail(fs.get(i), us.get(i), ls.get(i), prevT, 0.0, a)
ps.set(i, ps.get(i) + perfAlpha * (normalMove * prevT - ps.get(i)))
us.set(i, u)
ls.set(i, l)
ts.set(i, t)
var float factor = na
var float score = na
var int bars = 0
if commit
bars += 1
if bars >= warmup
[target, bc] = f_bestFactor(ps, fs)
score := bc
if not na(target)
factor := na(factor) ? target : factor + drift * (target - factor)
var float upper = na
var float lower = na
var int direction = 0
bool upFlip = false
bool downFlip = false
if commit and not na(factor) and not na(a)
int previous = direction
[u, l, t] = f_engineTrail(factor, upper, lower, direction, gate, a)
upper := u
lower := l
direction := t
upFlip := direction == 1 and previous != 1
downFlip := direction == -1 and previous != -1
float rawTrail = direction == 1 ? lower : direction == -1 ? upper : na
[direction, rawTrail, factor, score, upFlip, downFlip]
[dir, trail, usedFactor, bestPerf, flipUp, flipDn] = f_tre(barstate.isconfirmed)
// wave: display-only smoothing of the trail, restarted on every flip
var float wave = na
var float flipPrice = na
if barstate.isconfirmed
if flipUp or flipDn
flipPrice := close
wave := na(trail) ? na : (flipUp or flipDn or na(wave)) ? trail : wave + waveSmooth * (trail - wave)
// The exact same adaptive TRE engine, read from the last CLOSED HTF bar.
// No barstate.isconfirmed inside security: confirmation is provided by [1].
f_htfTrend() =>
[d, _, _, _, _, _] = f_tre(true)
d
f_htf(string tf) =>
timeframe.in_seconds(tf) > timeframe.in_seconds() ? request.security(syminfo.tickerid, tf, f_htfTrend()[1], lookahead=barmerge.lookahead_on) : na
int htfDir1 = int(f_htf(htf1))
int htfDir2 = int(f_htf(htf2))
// ───────────────────────── Quality: efficiency ratio × R²
float path = math.sum(math.abs(close - close[1]), qLen)
float er = path > 0 ? math.abs(close - close[qLen]) / path : 0.0
float rLive = ta.correlation(close, bar_index, qLen)
float qLive = 100 * math.sqrt(er * nz(rLive * rLive))
// shown values come from the last closed bar, so the panel and line colour do not flicker intrabar
float quality = barstate.isconfirmed ? qLive : qLive[1]
float r = barstate.isconfirmed ? rLive : rLive[1]
bool agrees = (r > 0 and dir == 1) or (r < 0 and dir == -1)
// ───────────────────────── Self-test: flips per 100 bars
var array<int> flipBars = array.new<int>()
if flipUp or flipDn
flipBars.push(bar_index)
while flipBars.size() > 0 and bar_index - flipBars.first() > 100
flipBars.shift()
// ───────────────────────── Plots
color dc = dir == 1 ? upColor : dir == -1 ? dnColor : color.gray
// Aurora: a band between price and trail, strongest at price, fading into the trail
// no vertical connector on the flip bar; the line glows brighter when the move is clean
float trailShown = flipUp or flipDn ? na : wave
color trailColor = color.new(dc, int(math.max(0, 45 - 0.45 * nz(quality))))
pTrail = plot(trailShown, "Trail", color=trailColor, linewidth=2, style=plot.style_linebr)
pClose = plot(na(trail) ? na : close, "Aurora edge", color=na, display=display.none)
fill(pClose, pTrail, close, trailShown, color.new(dc, auroraStrength), color.new(dc, 97), "Aurora band")
barcolor(tintCandles and dir != 0 ? color.new(dc, 20) : na, title="Candle tint")
plotshape(showFlips and flipUp, "Flip up", shape.circle, location.belowbar, upColor, size=size.tiny)
plotshape(showFlips and flipDn, "Flip down", shape.circle, location.abovebar, dnColor, size=size.tiny)
// No small-value plots (direction, quality, counts): values far from price make TradingView
// move the whole indicator to its own scale. Those readings live in the dashboard instead.
// ───────────────────────── Structure engine (closed bars)
float tfHours = timeframe.in_seconds() / 3600.0
int strength = strengthIn > 0 ? strengthIn : tfHours <= 2 ? 4 : 3
// pattern spans and lifetimes are set in hours, so 2H and 4H mean the same calendar time
int spanMax = math.min(150, int(math.round(360 / tfHours)))
int lifeBars = math.max(15, int(math.round(96 / tfHours)))
int ctxBars = math.max(6, int(math.round(36 / tfHours)))
float sAtr = ta.atr(14)
type Swing
int idx
float price
bool isHigh
float atr
float bodyEdge
float departure
int detIdx
float context
type Zone
bool isDemand
float top
float bottom
int originIdx
float atr
int touches
bool inside
bool valid
type StructEvent
int originIdx
int eventIdx
float price
string kind
int dir
type Liquidity
int firstIdx
int lastIdx
float level
bool isHigh
bool active
var array<Swing> swings = array.new<Swing>()
var array<Zone> zones = array.new<Zone>()
var array<StructEvent> events = array.new<StructEvent>()
var array<Liquidity> pools = array.new<Liquidity>()
var int structBias = 0
var int lastBrokenHigh = -1
var int lastBrokenLow = -1
float ph = ta.pivothigh(high, strength, strength)
float pl = ta.pivotlow(low, strength, strength)
float lowestR = ta.lowest(low, strength + 1)
float highestR = ta.highest(high, strength + 1)
// keeps highs and lows alternating; a more extreme same-side swing replaces the last one
f_ingest(Swing s) =>
bool changed = false
int n = swings.size()
if n == 0
swings.push(s)
changed := true
else
Swing prev = swings.get(n - 1)
if s.idx > prev.idx
if prev.isHigh == s.isHigh
if s.isHigh ? s.price > prev.price : s.price < prev.price
swings.set(n - 1, s)
changed := true
else
swings.push(s)
changed := true
if swings.size() > 60
swings.shift()
changed
f_label(float latest, float previous, bool highSide, float a) =>
math.abs(latest - previous) <= eqTol * a ? (highSide ? "EQH" : "EQL") : highSide ? (latest > previous ? "HH" : "LH") : (latest > previous ? "HL" : "LL")
f_structure(float a) =>
float h1 = na
float h2 = na
float l1 = na
float l2 = na
for p in swings
if p.isHigh
h2 := h1
h1 := p.price
else
l2 := l1
l1 := p.price
string hT = not na(h2) ? f_label(h1, h2, true, a) : ""
string lT = not na(l2) ? f_label(l1, l2, false, a) : ""
string trend = hT == "HH" and lT == "HL" ? "Up" : hT == "LH" and lT == "LL" ? "Down" : "Range"
[trend, hT, lT]
bool newSwing = false
if barstate.isconfirmed and not na(sAtr[strength])
bool ambiguous = not na(ph) and not na(pl)
if not ambiguous and (not na(ph) or not na(pl))
bool isHigh = not na(ph)
float price = isHigh ? ph : pl
float body = isHigh ? math.max(open[strength], close[strength]) : math.min(open[strength], close[strength])
float departure = isHigh ? price - lowestR : highestR - price
float context = price - close[strength + ctxBars]
newSwing := f_ingest(Swing.new(bar_index - strength, price, isHigh, sAtr[strength], body, departure, bar_index, context))
while swings.size() > 0 and bar_index - swings.first().idx > 500
swings.shift()
if newSwing
Swing s = swings.last()
// zone: only from swings price clearly left
if s.departure >= zoneDeparture * s.atr
float raw = s.isHigh ? s.price - s.bodyEdge : s.bodyEdge - s.price
float w = math.max(0.2 * s.atr, math.min(zoneMaxWidth * s.atr, raw))
zones.push(Zone.new(not s.isHigh, s.isHigh ? s.price : s.price + w, s.isHigh ? s.price - w : s.price, s.idx, s.atr, 0, true, true))
// liquidity: equal highs / lows with an earlier unbroken same-side swing
if swings.size() >= 3
for i = swings.size() - 3 to math.max(0, swings.size() - 9) by 2
Swing o = swings.get(i)
if o.isHigh == s.isHigh and s.idx - o.idx <= 150 and math.abs(o.price - s.price) <= eqTol * s.atr
pools.push(Liquidity.new(o.idx, s.idx, s.isHigh ? math.max(o.price, s.price) : math.min(o.price, s.price), s.isHigh, true))
break
[trendNow, hT, lT] = f_structure(sAtr)
structBias := trendNow == "Up" ? 1 : trendNow == "Down" ? -1 : 0
// zones: count fresh touches, invalidate on a close through
for z in zones
if z.valid
if z.isDemand ? close < z.bottom - breakTol * z.atr : close > z.top + breakTol * z.atr
z.valid := false
else
bool inZone = high >= z.bottom and low <= z.top
if inZone and not z.inside and bar_index - z.originIdx > strength
z.touches += 1
z.inside := inZone
while zones.size() > 30
zones.shift()
// liquidity is taken once price trades through the level
for lq in pools
if lq.active and (lq.isHigh ? high > lq.level : low < lq.level) and bar_index > lq.lastIdx + strength
lq.active := false
while pools.size() > 20
pools.shift()
// BOS / CHoCH on a closed-bar break of the latest swing
Swing lastH = na
Swing lastL = na
for p in swings
if p.isHigh
lastH := p
else
lastL := p
if not na(lastH) and lastH.idx != lastBrokenHigh and close > lastH.price + breakTol * lastH.atr
events.push(StructEvent.new(lastH.idx, bar_index, lastH.price, structBias == 1 ? "BOS" : structBias == -1 ? "CHoCH" : "Break", 1))
lastBrokenHigh := lastH.idx
if not na(lastL) and lastL.idx != lastBrokenLow and close < lastL.price - breakTol * lastL.atr
events.push(StructEvent.new(lastL.idx, bar_index, lastL.price, structBias == -1 ? "BOS" : structBias == 1 ? "CHoCH" : "Break", -1))
lastBrokenLow := lastL.idx
while events.size() > 12
events.shift()
// previous completed day / week: [1] + lookahead_on does not repaint
[pdh, pdl] = request.security(syminfo.tickerid, "D", [high[1], low[1]], lookahead=barmerge.lookahead_on)
[pwh, pwl] = request.security(syminfo.tickerid, "W", [high[1], low[1]], lookahead=barmerge.lookahead_on)
// ───────────────────────── Pattern engine (ported from PSD; spans scaled by timeframe hours)
type Pattern
string id
string kind
int startIndex
int endIndex
int detectedIndex
float atr
float upperSlope
float upperIntercept
float lowerSlope
float lowerIntercept
float extremeHigh
float extremeLow
int expectedDirection
string state
int stateIndex
float quality
int contacts
float apex
bool returned
array<int> anchorIndices
array<float> anchorPrices
var array<Pattern> patterns = array.new<Pattern>()
f_boundary(float slope, float intercept, int x) =>
slope * x + intercept
f_clamp(float value, float lo, float hi) =>
math.max(lo, math.min(hi, value))
f_isReversal(string kind) =>
str.contains(kind, "Top") or str.contains(kind, "Bottom") or str.contains(kind, "Shoulders") or kind == "Inverse H&S"
f_fitLine(array<Swing> points, bool highs) =>
float sx = 0.0
float sy = 0.0
float sxx = 0.0
float sxy = 0.0
int n = 0
int base = points.size() > 0 ? points.get(0).idx : 0
for p in points
if p.isHigh == highs
float x = p.idx - base
sx += x
sy += p.price
sxx += x * x
sxy += x * p.price
n += 1
float den = n * sxx - sx * sx
float slope = n >= 2 and den > 0 ? (n * sxy - sx * sy) / den : na
float intercept = n >= 2 and not na(slope) ? (sy - slope * sx) / n - slope * base : na
float residual = 0.0
if not na(slope)
for p in points
if p.isHigh == highs
residual := math.max(residual, math.abs(p.price - f_boundary(slope, intercept, p.idx)))
[slope, intercept, residual, n]
f_validateEnvelope(array<Swing> points, float um, float ub, float lm, float lb, float a) =>
bool ok = points.size() >= 4 and not na(a) and a > 0 and not na(um) and not na(lm)
int lastHigh = -1000000
int lastLow = -1000000
if ok
for p in points
float upper = f_boundary(um, ub, p.idx)
float lower = f_boundary(lm, lb, p.idx)
float expected = p.isHigh ? upper : lower
int previous = p.isHigh ? lastHigh : lastLow
if upper <= lower or math.abs(p.price - expected) > touchTol * a or p.idx - previous < 3
ok := false
if p.isHigh
lastHigh := p.idx
else
lastLow := p.idx
ok
f_points(int start, int count) =>
array<Swing> result = array.new<Swing>()
if start >= 0 and start + count <= swings.size()
for i = start to start + count - 1
result.push(swings.get(i))
result
f_makePattern(string kind, array<Swing> pts, float um, float ub, float lm, float lb, int direction, float q, float apex) =>
Swing first = pts.get(0)
Swing last = pts.get(pts.size() - 1)
float hi = first.price
float lo = first.price
string id = kind
array<int> indices = array.new<int>()
array<float> prices = array.new<float>()
for p in pts
hi := math.max(hi, p.price)
lo := math.min(lo, p.price)
id += ":" + str.tostring(p.idx)
indices.push(p.idx)
prices.push(p.price)
Pattern.new(id, kind, first.idx, last.idx, last.detIdx, last.atr, um, ub, lm, lb, hi, lo, direction, "Forming", last.detIdx, q, pts.size(), apex, false, indices, prices)
f_reversalCandidate(array<Swing> pts) =>
Pattern result = na
int n = pts.size()
if n == 3 or n == 5
Swing first = pts.get(0)
Swing last = pts.get(n - 1)
float a = last.atr
int span = last.idx - first.idx
float sign = first.isHigh ? 1.0 : -1.0
if not na(a) and a > 0 and span >= 2 * strength and span <= spanMax and first.context * sign >= 2.0 * a
Swing middle = pts.get(1)
Swing third = pts.get(2)
float v0 = first.price * sign
float v1 = middle.price * sign
float v2 = third.price * sign
string kind = ""
float neckM = 0.0
float neckB = middle.price
float contactError = 0.0
float contactLimit = equalTol * a
float symmetry = 1.0
if n == 3 and showDouble
contactError := math.abs(v0 - v2)
if contactError <= contactLimit and math.min(v0, v2) - v1 >= a
kind := first.isHigh ? "Double Top" : "Double Bottom"
if n == 5
Swing fourth = pts.get(3)
float v3 = fourth.price * sign
float v4 = last.price * sign
float ratio = float(third.idx - first.idx) / math.max(1, last.idx - third.idx)
float nm = (fourth.price - middle.price) / (fourth.idx - middle.idx)
float nb = middle.price - nm * middle.idx
bool shoulders = v2 - math.max(v0, v4) >= 0.75 * a and math.abs(v0 - v4) <= 0.5 * a and v2 - f_boundary(nm, nb, third.idx) * sign >= 1.5 * a and ratio >= 0.5 and ratio <= 2.0
if shoulders and showShoulders
kind := first.isHigh ? "Head & Shoulders" : "Inverse H&S"
neckM := nm
neckB := nb
contactError := math.abs(v0 - v4)
contactLimit := 0.5 * a
symmetry := math.min(ratio, 1.0 / ratio)
else if showDouble
float spread = math.max(v0, math.max(v2, v4)) - math.min(v0, math.min(v2, v4))
if spread <= contactLimit and math.min(v0, v2) - v1 >= a and math.min(v2, v4) - v3 >= a
kind := first.isHigh ? "Triple Top" : "Triple Bottom"
neckB := first.isHigh ? math.min(middle.price, fourth.price) : math.max(middle.price, fourth.price)
contactError := spread
if kind != ""
float contactsScore = f_clamp(1.0 - contactError / math.max(contactLimit, syminfo.mintick), 0.0, 1.0)
float contextScore = f_clamp(first.context * sign / (4.0 * a), 0.0, 1.0)
float sc = 40.0 * contactsScore + 25.0 + 20.0 * contextScore + 15.0 * symmetry
float upperB = first.isHigh ? math.max(first.price, last.price) : neckB
float lowerB = first.isHigh ? neckB : math.min(first.price, last.price)
result := f_makePattern(kind, pts, first.isHigh ? 0.0 : neckM, upperB, first.isHigh ? neckM : 0.0, lowerB, first.isHigh ? -1 : 1, sc, na)
result
f_wideDouble(int firstIndex, int lastIndex) =>
Pattern result = na
Swing first = swings.get(firstIndex)
Swing last = swings.get(lastIndex)
int span = last.idx - first.idx
float sign = first.isHigh ? 1.0 : -1.0
float a = last.atr
bool valid = showDouble and first.isHigh == last.isHigh and span >= 12 and span <= spanMax and math.abs(first.price - last.price) <= equalTol * a
Swing valley = na
if valid
for i = firstIndex + 1 to lastIndex - 1
Swing inner = swings.get(i)
if inner.isHigh != first.isHigh
if na(valley)
valley := inner
else if inner.price * sign < valley.price * sign
valley := inner
else
bool overtops = inner.price * sign > math.max(first.price * sign, last.price * sign) + breakTol * a
int edge = math.max(8, int(span * 0.20))
bool centralContact = inner.price * sign >= math.min(first.price * sign, last.price * sign) - equalTol * a and inner.idx - first.idx > edge and last.idx - inner.idx > edge
if overtops or centralContact
valid := false
if valid and not na(valley)
result := f_reversalCandidate(array.from(first, valley, last))
result
f_detectReversals(array<Pattern> output) =>
for count = 3 to 5 by 2
if swings.size() >= count
Pattern candidate = f_reversalCandidate(f_points(swings.size() - count, count))
if not na(candidate)
output.push(candidate)
int n = swings.size()
if n >= 5 and showDouble
for offset = 4 to math.min(n - 1, 24) by 2
Pattern candidate = f_wideDouble(n - 1 - offset, n - 1)
if not na(candidate)
output.push(candidate)
true
f_validateBars(int startIndex, int endIndex, float um, float ub, float lm, float lb, float a) =>
bool ok = a > 0 and endIndex >= startIndex and bar_index - startIndex <= 300 and startIndex >= 0
int wickViolations = 0
int checked = 0
if ok
for x = startIndex to endIndex
int offset = bar_index - x
float upper = f_boundary(um, ub, x)
float lower = f_boundary(lm, lb, x)
if na(close[offset]) or close[offset] > upper + breakTol * a or close[offset] < lower - breakTol * a
ok := false
if high[offset] > upper + touchTol * a or low[offset] < lower - touchTol * a
wickViolations += 1
checked += 1
ok and checked > 0 and wickViolations <= checked * 0.15
f_findPole(int consolidationStart, float a) =>
bool valid = false
int direction = 0
int duration = 0
float magnitude = 0.0
int offset = bar_index - consolidationStart
if a > 0 and offset >= 0 and offset <= 300
for length = 5 to 20
if not valid and consolidationStart >= length
float delta = close[offset] - close[offset + length]
float travel = 0.0
for j = 0 to length - 1
travel += math.abs(close[offset + j] - close[offset + j + 1])
if not na(delta) and travel > 0 and math.abs(delta) >= 3.0 * a and math.abs(delta) / travel >= 0.65
valid := true
direction := delta > 0 ? 1 : -1
duration := length
magnitude := math.abs(delta)
[valid, direction, duration, magnitude]
f_geometricCandidate(array<Swing> pts, bool poleValid, int poleDir, int poleDuration, float poleMagnitude, float poleEnd) =>
Pattern result = na
int count = pts.size()
if count >= 4
Swing first = pts.get(0)
Swing last = pts.get(count - 1)
float a = last.atr
int span = last.idx - first.idx
[um, ub, ur, uc] = f_fitLine(pts, true)
[lm, lb, lr, lc] = f_fitLine(pts, false)
if not na(a) and a > 0 and span >= 6 and span <= spanMax and f_validateEnvelope(pts, um, ub, lm, lb, a)
float w0 = f_boundary(um, ub, first.idx) - f_boundary(lm, lb, first.idx)
float w1 = f_boundary(um, ub, last.idx) - f_boundary(lm, lb, last.idx)
float du = um * span
float dl = lm * span
bool flatU = math.abs(du) <= 0.25 * a
bool flatL = math.abs(dl) <= 0.25 * a
bool parallel = math.abs(du - dl) <= 0.30 * a and math.abs(w1 - w0) / w0 <= 0.20
float apex = um != lm ? (lb - ub) / (um - lm) : na
bool converging = um < lm and w1 / w0 <= 0.75 and not na(apex) and apex > last.detIdx and apex <= last.idx + span
string kind = ""
int direction = 0
float contextScore = 1.0
float lo = first.price
float hi = first.price
for p in pts
lo := math.min(lo, p.price)
hi := math.max(hi, p.price)
float retrace = poleDir > 0 ? poleEnd - lo : hi - poleEnd
bool poleContext = poleValid and poleMagnitude >= 3.0 * a and span <= math.max(20, spanMax / 3) and span <= poleDuration * 3 and retrace >= 0 and retrace <= 0.5 * poleMagnitude
if showFlags and poleContext
bool flag = parallel and ((flatU and flatL) or (du * poleDir < 0 and dl * poleDir < 0))
bool pennant = count >= 5 and converging and du < -0.25 * a and dl > 0.25 * a
if pennant or flag
kind := poleDir > 0 ? (pennant ? "Bullish Pennant" : "Bullish Flag") : (pennant ? "Bearish Pennant" : "Bearish Flag")
direction := poleDir
contextScore := f_clamp(poleMagnitude / (5.0 * a), 0.0, 1.0)
if kind == "" and span >= 12
if count >= 5 and converging
if showTriangles and flatU and dl > 0.25 * a
kind := "Ascending Triangle"
else if showTriangles and flatL and du < -0.25 * a
kind := "Descending Triangle"
else if showTriangles and du < -0.25 * a and dl > 0.25 * a
kind := "Symmetrical Triangle"
else if showWedges and du > 0.25 * a and dl > 0.25 * a
kind := "Rising Wedge"
else if showWedges and du < -0.25 * a and dl < -0.25 * a
kind := "Falling Wedge"
if kind == "" and showChannels and uc >= 3 and lc >= 3 and parallel
if flatU and flatL and w0 >= a and w0 <= 6.0 * a
kind := "Rectangle"
else if du > 0.25 * a and dl > 0.25 * a
kind := "Ascending Channel"
else if du < -0.25 * a and dl < -0.25 * a
kind := "Descending Channel"
if kind != ""
float contactScore = f_clamp(1.0 - math.max(ur, lr) / (touchTol * a), 0.0, 1.0)
float fitScore = converging ? f_clamp((1.0 - w1 / w0) / 0.50, 0.0, 1.0) : f_clamp(1.0 - math.abs(du - dl) / (0.30 * a), 0.0, 1.0)
int largestGap = 0
for i = 1 to count - 1
largestGap := math.max(largestGap, pts.get(i).idx - pts.get(i - 1).idx)
float timing = f_clamp(float(span) / ((count - 1) * math.max(1, largestGap)), 0.0, 1.0)
float q = 40.0 * contactScore + 25.0 * fitScore + 20.0 * contextScore + 15.0 * timing
result := f_makePattern(kind, pts, um, ub, lm, lb, direction, q, converging ? apex : na)
result
f_detectContinuations(array<Pattern> output) =>
int n = swings.size()
if n >= 4
for count = 4 to math.min(n, 27)
array<Swing> pts = f_points(n - count, count)
Swing first = pts.get(0)
Swing last = pts.get(count - 1)
if bar_index - first.idx <= 300 and last.idx - first.idx <= spanMax
[poleValid, poleDir, poleDuration, poleMagnitude] = f_findPole(first.idx, last.atr)
float poleEnd = close[bar_index - first.idx]
Pattern candidate = f_geometricCandidate(pts, poleValid, poleDir, poleDuration, poleMagnitude, poleEnd)
if not na(candidate)
if f_validateBars(candidate.startIndex, candidate.endIndex, candidate.upperSlope, candidate.upperIntercept, candidate.lowerSlope, candidate.lowerIntercept, candidate.atr)
output.push(candidate)
true
f_isRange(Pattern p) =>
str.contains(p.kind, "Channel") or p.kind == "Rectangle"
f_finished(Pattern p) =>
str.startswith(p.state, "Confirmed") or str.startswith(p.state, "Broken")
f_registerPatterns(array<Pattern> incoming) =>
for candidate in incoming
if patterns.size() > 0
for i = patterns.size() - 1 to 0
Pattern old = patterns.get(i)
if old.state == "Invalid" or old.state == "Expired" or candidate.detectedIndex - old.endIndex > spanMax + 30 or (f_finished(old) and candidate.detectedIndex - old.stateIndex > spanMax)
patterns.remove(i)
bool exists = false
for p in patterns
if p.id == candidate.id
exists := true
if not exists
patterns.push(candidate)
while patterns.size() > 40
int removeIndex = 0
float worst = 1000000.0
for i = 0 to patterns.size() - 1
Pattern p = patterns.get(i)
float priority = (p.state == "Invalid" or p.state == "Expired" ? -1000.0 : 0.0) + p.quality + p.endIndex * 0.001
if priority < worst
worst := priority
removeIndex := i
patterns.remove(removeIndex)
true
f_updatePatterns(float closedPrice, int currentIndex) =>
for p in patterns
if currentIndex >= p.detectedIndex
float upper = f_boundary(p.upperSlope, p.upperIntercept, currentIndex)
float lower = f_boundary(p.lowerSlope, p.lowerIntercept, currentIndex)
float buffer = p.atr * breakTol
bool isRange = f_isRange(p)
bool isContinuation = str.contains(p.kind, "Flag") or str.contains(p.kind, "Pennant")
if p.state == "Forming"
int lifetime = isRange ? 2 * lifeBars : f_isReversal(p.kind) ? math.max(lifeBars, math.min(spanMax, p.endIndex - p.startIndex)) : lifeBars
bool expired = currentIndex - (isRange ? p.endIndex : p.detectedIndex) > lifetime or (not na(p.apex) and currentIndex >= p.apex)
int direction = closedPrice > upper + buffer ? 1 : closedPrice < lower - buffer ? -1 : 0
bool reversalInvalid = p.expectedDirection == -1 and not isContinuation and closedPrice > p.extremeHigh + buffer or p.expectedDirection == 1 and not isContinuation and closedPrice < p.extremeLow - buffer
if expired or reversalInvalid
p.state := expired ? "Expired" : "Invalid"
p.stateIndex := currentIndex
else if direction != 0
if p.expectedDirection == 0 or direction == p.expectedDirection
p.state := (isRange ? "Broken " : "Confirmed ") + (direction > 0 ? "Up" : "Down")
p.stateIndex := currentIndex
else if isContinuation
p.state := "Invalid"
p.stateIndex := currentIndex
else if f_finished(p) and not p.returned and upper > lower and closedPrice <= upper and closedPrice >= lower
p.returned := true
true
f_overlap(Pattern a, Pattern b) =>
int shared = math.min(a.endIndex, b.endIndex) - math.max(a.startIndex, b.startIndex)
int shorter = math.min(a.endIndex - a.startIndex, b.endIndex - b.startIndex)
bool sharedPeak = a.kind == b.kind and str.contains(a.kind, "Double") and (a.startIndex == b.startIndex or a.startIndex == b.endIndex or a.endIndex == b.startIndex or a.endIndex == b.endIndex)
sharedPeak or (shared > 0 and shorter > 0 and float(shared) / shorter >= 0.70 and math.min(a.extremeHigh, b.extremeHigh) >= math.max(a.extremeLow, b.extremeLow))
f_specialPrecedence(Pattern a, Pattern b) =>
(str.contains(a.kind, "Flag") and str.contains(b.kind, "Channel")) or (str.contains(a.kind, "Pennant") and str.contains(b.kind, "Triangle")) or ((str.contains(a.kind, "Shoulders") or a.kind == "Inverse H&S") and str.contains(b.kind, "Triple"))
// regime context: how the pattern sits against the TRE trend and its quality
f_context(Pattern p) =>
bool ranging = quality < 25 or dir == 0
p.expectedDirection == 0 ? (ranging ? "in range" : dir == 1 ? "in uptrend" : "in downtrend") : ranging ? "in range" : p.expectedDirection == dir ? "with TRE" : "against TRE"
// swing timeframes: reversals carry more weight; patterns agreeing with the trend rank higher
f_rank(Pattern p, int currentIndex) =>
float fresh = f_finished(p) and currentIndex - p.stateIndex <= lifeBars / 2 ? 200.0 : 0.0
float reversal = f_isReversal(p.kind) ? 10.0 : 0.0
float regime = p.expectedDirection != 0 and p.expectedDirection == dir and quality >= 25 ? 10.0 : 0.0
fresh + reversal + regime + p.quality + p.endIndex * 0.0001 - (p.returned ? 20.0 : 0.0)
f_selectPatterns(int currentIndex, int limit) =>
array<int> selected = array.new<int>()
array<int> eligible = array.new<int>()
int n = patterns.size()
if n > 0
for i = 0 to n - 1
Pattern p = patterns.get(i)
if (p.state == "Forming" or f_finished(p)) and p.quality >= minQuality and currentIndex - p.endIndex <= spanMax + 30 and (not f_finished(p) or currentIndex - p.stateIndex <= spanMax)
eligible.push(i)
while eligible.size() > 0 and selected.size() < limit
int bestPos = 0
if eligible.size() > 1
for j = 1 to eligible.size() - 1
Pattern cur = patterns.get(eligible.get(j))
Pattern best = patterns.get(eligible.get(bestPos))
bool overlap = f_overlap(cur, best)
bool forceCur = overlap and f_specialPrecedence(cur, best)
bool forceBest = overlap and f_specialPrecedence(best, cur)
if forceCur or (not forceBest and f_rank(cur, currentIndex) > f_rank(best, currentIndex))
bestPos := j
int bestIndex = eligible.remove(bestPos)
bool conflict = false
for s in selected
if f_overlap(patterns.get(bestIndex), patterns.get(s))
conflict := true
if not conflict
selected.push(bestIndex)
selected
f_patternStatus(Pattern p) =>
p.returned ? "back inside" : p.state == "Forming" ? (f_isRange(p) ? "active" : "forming") : str.contains(p.state, "Up") ? "broke up" : "broke down"
bool patternFound = false
if barstate.isconfirmed
if newSwing
array<Pattern> incoming = array.new<Pattern>()
f_detectReversals(incoming)
f_detectContinuations(incoming)
for c in incoming
patternFound := patternFound or c.quality >= minQuality
f_registerPatterns(incoming)
f_updatePatterns(close, bar_index)
// ───────────────────────── Structure rendering (last bar)
var array<line> sLines = array.new<line>()
var array<box> sBoxes = array.new<box>()
var array<label> sLabels = array.new<label>()
color supplyColor = dnColor
color demandColor = upColor
color inkS = color.rgb(219, 223, 225)
f_text(int x, float y, string t, color c, string st = label.style_none) =>
sLabels.push(label.new(x, y, t, style=st, color=color.new(c, 100), textcolor=c, size=size.small))
// nearest valid zone on one side of price, skipping already-taken indices
f_nearest(array<Zone> list, bool demand, float ref, array<int> taken) =>
int best = -1
float dist = na
for i = 0 to list.size() - 1
Zone z = list.get(i)
bool side = demand ? z.top <= ref : z.bottom >= ref
float d = demand ? ref - z.top : z.bottom - ref
if z.valid and z.isDemand == demand and side and not taken.includes(i) and (na(dist) or d < dist)
dist := d
best := i
best
var float supBot = na
var float supTop = na
var float demBot = na
var float demTop = na
var int supTouches = 0
var int demTouches = 0
if barstate.islast
for x in sLines
x.delete()
for x in sBoxes
x.delete()
for x in sLabels
x.delete()
sLines.clear()
sBoxes.clear()
sLabels.clear()
int right = bar_index + extendBars
supBot := na
supTop := na
demBot := na
demTop := na
// merge overlapping same-side zones into one visual zone (keeps the widest span and most touches)
array<Zone> vis = array.new<Zone>()
for src in zones
if src.valid
Zone m = src.copy()
int j = 0
while j < vis.size()
Zone e = vis.get(j)
if e.isDemand == m.isDemand and math.min(e.top, m.top) >= math.max(e.bottom, m.bottom)
m.top := math.max(e.top, m.top)
m.bottom := math.min(e.bottom, m.bottom)
m.originIdx := math.min(e.originIdx, m.originIdx)
m.touches := math.max(e.touches, m.touches)
vis.remove(j)
j := 0
else
j += 1
vis.push(m)
array<int> taken = array.new<int>()
if vis.size() > 0
for side = 0 to 1
for k = 0 to zonesPerSide - 1
int i = f_nearest(vis, side == 0, close, taken)
if i >= 0
taken.push(i)
Zone z = vis.get(i)
if k == 0
if z.isDemand
demBot := z.bottom
demTop := z.top
demTouches := z.touches
else
supBot := z.bottom
supTop := z.top
supTouches := z.touches
if showZones
for i in taken
Zone z = vis.get(i)
color tone = z.isDemand ? demandColor : supplyColor
// soft fill, one crisp edge on the side price would meet first
sBoxes.push(box.new(z.originIdx, z.top, right, z.bottom, border_color=color.new(tone, 100), bgcolor=color.new(tone, math.min(96, 90 + 2 * z.touches))))
float edge = z.isDemand ? z.top : z.bottom
sLines.push(line.new(z.originIdx, edge, right, edge, color=color.new(tone, 50), width=1))
if showBreaks
int shown = 0
for j = events.size() - 1 to 0
if events.size() > 0 and shown < 2
StructEvent e = events.get(j)
if bar_index - e.eventIdx <= 120
sLines.push(line.new(e.originIdx, e.price, e.eventIdx, e.price, color=color.new(inkS, 55), style=line.style_dotted))
f_text(int((e.originIdx + e.eventIdx) / 2), e.price + e.dir * 0.3 * sAtr, e.kind, color.new(inkS, 35))
shown += 1
if showLiquidity
int shownL = 0
for j = pools.size() - 1 to 0
if pools.size() > 0 and shownL < 4
Liquidity lq = pools.get(j)
if lq.active
sLines.push(line.new(lq.firstIdx, lq.level, right, lq.level, color=color.new(lq.isHigh ? supplyColor : demandColor, 30), style=line.style_dashed))
f_text(right, lq.level, lq.isHigh ? "EQH" : "EQL", color.new(inkS, 40), label.style_label_left)
shownL += 1
if showHTFLevels
int left = bar_index - 30
for k = 0 to 3
float v = k == 0 ? pdh : k == 1 ? pdl : k == 2 ? pwh : pwl
string nm = k == 0 ? "PDH" : k == 1 ? "PDL" : k == 2 ? "PWH" : "PWL"
if not na(v)
sLines.push(line.new(left, v, right, v, color=color.new(inkS, k < 2 ? 60 : 35), style=k < 2 ? line.style_dotted : line.style_solid))
f_text(right, v, nm, color.new(inkS, 40), label.style_label_left)
// ───────────────────────── Pattern selection + drawing (last bar)
var array<int> active = array.new<int>()
if barstate.islast
int displayIndex = barstate.isconfirmed ? bar_index : bar_index - 1
active := f_selectPatterns(displayIndex, 3)
if drawPattern and active.size() > 0
Pattern p = patterns.get(active.get(0))
color pc = p.expectedDirection == 1 ? upColor : p.expectedDirection == -1 ? dnColor : inkS
int end = math.max(p.endIndex, math.min(displayIndex, p.state == "Forming" ? displayIndex : p.stateIndex))
if not na(p.apex)
end := math.max(p.endIndex, math.min(end, int(math.floor(p.apex)) - 1))
if f_isReversal(p.kind)
for i = 1 to p.anchorIndices.size() - 1
sLines.push(line.new(p.anchorIndices.get(i - 1), p.anchorPrices.get(i - 1), p.anchorIndices.get(i), p.anchorPrices.get(i), color=color.new(pc, 25), width=2))
bool isTop = p.expectedDirection == -1
float m = isTop ? p.lowerSlope : p.upperSlope
float b = isTop ? p.lowerIntercept : p.upperIntercept
sLines.push(line.new(p.startIndex, f_boundary(m, b, p.startIndex), end, f_boundary(m, b, end), color=color.new(pc, 35), style=line.style_dashed))
else
sLines.push(line.new(p.startIndex, f_boundary(p.upperSlope, p.upperIntercept, p.startIndex), end, f_boundary(p.upperSlope, p.upperIntercept, end), color=color.new(pc, 10), width=2))
sLines.push(line.new(p.startIndex, f_boundary(p.lowerSlope, p.lowerIntercept, p.startIndex), end, f_boundary(p.lowerSlope, p.lowerIntercept, end), color=color.new(pc, 10), width=2))
int mid = int(math.round((p.startIndex + p.endIndex) / 2.0))
f_text(mid, p.extremeHigh + p.atr * 0.9, p.kind + "\n" + f_patternStatus(p) + " · " + f_context(p) + " · Q" + str.tostring(math.round(p.quality)), pc)
// ───────────────────────── Aurora dashboard · level ladder (the chart stays clean; the detail lives here)
const int ROWS = 20
color panelBg = #0B0F17
color muted = color.rgb(107, 114, 128)
color faint = color.rgb(75, 85, 99)
color soft = color.rgb(156, 163, 175)
color bright = color.rgb(229, 231, 235)
color amber = #FBBF24
int barsSinceFlip = ta.barssince(flipUp or flipDn)
var table dash = table.new(dashPos == "Top left" ? position.top_left : dashPos == "Bottom left" ? position.bottom_left : dashPos == "Bottom right" ? position.bottom_right : position.top_right, 4, ROWS, bgcolor=panelBg, frame_color=color.new(#FFFFFF, 90), frame_width=1)
var bool stripMerged = false
int lastRow = mobile ? 8 : panelStyle == "Compact" ? 2 : ROWS - 1
f_cell3(int r, string a, color ca, string b, color cb, string c, color cc) =>
table.cell(dash, 1, r, a, text_color=ca, text_size=mobile ? size.tiny : size.small, text_halign=text.align_left, bgcolor=panelBg)
table.cell(dash, 2, r, b, text_color=cb, text_size=mobile ? size.tiny : size.small, text_halign=text.align_left, bgcolor=panelBg)
table.cell(dash, 3, r, c, text_color=cc, text_size=mobile ? size.tiny : size.small, text_halign=text.align_right, bgcolor=panelBg)
f_section(int r, string title) =>
f_cell3(r, title, faint, "", faint, "", faint)
table.cell_set_text_size(dash, 1, r, size.tiny)
f_px(float v) =>
str.tostring(v, format.mintick)
f_tf(string tf) =>
tf == "60" ? "1H" : tf == "120" ? "2H" : tf == "240" ? "4H" : tf == "D" or tf == "1D" ? "1D" : tf == "W" or tf == "1W" ? "1W" : tf
f_dirColor(int d) =>
d == 1 ? upColor : d == -1 ? dnColor : muted
if barstate.islast
bool compact = panelStyle == "Compact" or mobile
string tfName = f_tf(timeframe.period)
table.cell(dash, 0, 0, "", bgcolor=dc, width=mobile ? 0.2 : 0.3)
if not stripMerged
table.merge_cells(dash, 0, 0, 0, lastRow)
stripMerged := true
// header
f_cell3(0, dir == 1 ? "▲ TRE UP" : dir == -1 ? "▼ TRE DOWN" : "• TRE WAIT", dc, "", dc, syminfo.ticker + " · " + tfName + (na(barsSinceFlip) ? "" : "\nflipped " + str.tostring(barsSinceFlip) + " bars ago at " + f_px(flipPrice)), soft)
table.cell_set_text_size(dash, 1, 0, mobile ? size.normal : size.large)
if mobile
table.cell_set_text(dash, 3, 0, syminfo.ticker + " · " + tfName)
// trend quality meter
int filled = int(math.round(nz(quality) / 10))
string meter = ""
for i = 1 to 10
meter += i <= filled ? "■" : "□"
string qWord = quality >= 60 ? "clean" : quality >= 35 ? "moderate" : "choppy"
f_cell3(1, mobile ? "Q " + str.tostring(math.round(quality)) : "Trend quality", mobile ? (quality >= 35 ? soft : amber) : muted, meter, dc, str.tostring(math.round(quality)) + " · " + qWord, quality >= 35 ? soft : amber)
// higher timeframes
string chips = f_tf(htf1) + (htfDir1 == 1 ? " ▲" : htfDir1 == -1 ? " ▼" : " —") + " " + f_tf(htf2) + (htfDir2 == 1 ? " ▲" : htfDir2 == -1 ? " ▼" : " —")
bool aligned = not na(htfDir1) and not na(htfDir2) and htfDir1 == dir and htfDir2 == dir
bool opposed = not na(htfDir1) and not na(htfDir2) and htfDir1 == -dir and htfDir2 == -dir
f_cell3(2, mobile ? "HTF TRE" : "HTF TRE · closed", muted, chips, htfDir1 == htfDir2 ? f_dirColor(htfDir1) : amber, aligned ? "aligned" : opposed ? "against" : "mixed", aligned ? dc : amber)
if mobile
// nearest two levels above and below price, then the top pattern
array<float> mv = array.new<float>()
array<string> mn = array.new<string>()
array<color> mc = array.new<color>()
mv.push(close)
mn.push("●")
mc.push(dc)
array<float> cand = array.from(pwh, pwl, pdh, pdl, supBot, demTop)
array<string> candN = array.from("W high", "W low", "D high", "D low", "Supply", "Demand")
array<color> candC = array.from(soft, soft, soft, soft, supplyColor, demandColor)
for i = 0 to cand.size() - 1
if not na(cand.get(i))
mv.push(cand.get(i))
mn.push(candN.get(i))
mc.push(candC.get(i))
array<int> ord = mv.sort_indices(order.descending)
int pricePos = ord.indexof(0)
int r = 3
for j = math.max(0, pricePos - 2) to math.min(ord.size() - 1, pricePos + 2)
int i = ord.get(j)
bool isPrice = i == 0
float v = mv.get(i)
f_cell3(r, f_px(v), isPrice ? dc : mc.get(i), mn.get(i), isPrice ? dc : mc.get(i), isPrice ? "" : (v >= close ? "+" : "−") + str.tostring(math.abs(100 * (v / close - 1)), "0.0") + "%", muted)
if isPrice
for col = 1 to 3
table.cell_set_bgcolor(dash, col, r, color.new(dc, 88))
r += 1
while r <= 7
f_cell3(r, "", muted, "", muted, "", muted)
r += 1
if active.size() > 0
Pattern p = patterns.get(active.get(0))
color pc = p.expectedDirection == 1 ? upColor : p.expectedDirection == -1 ? dnColor : bright
f_cell3(8, "● " + p.kind, pc, "", pc, f_patternStatus(p), soft)
else
f_cell3(8, "no pattern", muted, "", muted, "", muted)
if not compact
// level ladder: every key level sorted by price, distance from price on the right
f_section(3, "LEVELS")
array<float> lv = array.new<float>()
array<string> nm = array.new<string>()
array<color> cl = array.new<color>()
lv.push(close)
nm.push("● Price")
cl.push(dc)
if not na(pwh)
lv.push(pwh)
nm.push("Week high")
cl.push(soft)
lv.push(pwl)
nm.push("Week low")
cl.push(soft)
if not na(pdh)
lv.push(pdh)
nm.push("Day high")
cl.push(soft)
lv.push(pdl)
nm.push("Day low")
cl.push(soft)
if not na(supBot)
lv.push(supBot)
nm.push("Supply · " + (supTouches > 0 ? str.tostring(supTouches) + "×" : "fresh"))
cl.push(supplyColor)
if not na(demTop)
lv.push(demTop)
nm.push("Demand · " + (demTouches > 0 ? str.tostring(demTouches) + "×" : "fresh"))
cl.push(demandColor)
float eqhAbove = na
float eqlBelow = na
for lq in pools
if lq.active
if lq.isHigh and lq.level >= close and (na(eqhAbove) or lq.level < eqhAbove)
eqhAbove := lq.level
if not lq.isHigh and lq.level <= close and (na(eqlBelow) or lq.level > eqlBelow)
eqlBelow := lq.level
if not na(eqhAbove)
lv.push(eqhAbove)
nm.push("EQH · liquidity")
cl.push(soft)
if not na(eqlBelow)
lv.push(eqlBelow)
nm.push("EQL · liquidity")
cl.push(soft)
array<int> idxs = lv.sort_indices(order.descending)
int r = 4
for i in idxs
if r <= 12
float v = lv.get(i)
bool isPrice = nm.get(i) == "● Price"
string dist = isPrice ? "" : (v >= close ? "+" : "−") + str.tostring(math.abs(100 * (v / close - 1)), "0.00") + "%"
f_cell3(r, f_px(v), isPrice ? dc : cl.get(i), nm.get(i), isPrice ? dc : cl.get(i), dist, muted)
if isPrice
for col = 1 to 3
table.cell_set_bgcolor(dash, col, r, color.new(dc, 88))
r += 1
while r <= 12
f_cell3(r, "", muted, "", muted, "", muted)
r += 1
// structure
f_section(13, "CONFIRMED SWING STRUCTURE")
[trendD, hD, lD] = f_structure(sAtr)
string hw = hD == "HH" ? "higher high" : hD == "LH" ? "lower high" : hD == "EQH" ? "equal highs" : ""
string lw = lD == "HL" ? "higher low" : lD == "LL" ? "lower low" : lD == "EQL" ? "equal lows" : ""
int swingDir = trendD == "Up" ? 1 : trendD == "Down" ? -1 : 0
string relation = swingDir == 0 or dir == 0 ? "" : swingDir == dir ? "agrees with TRE" : "differs from TRE"
f_cell3(14, trendD == "Up" ? "Rising swings" : trendD == "Down" ? "Falling swings" : "Mixed swings", bright, relation, swingDir != 0 and swingDir != dir ? amber : muted, hw == "" and lw == "" ? "building" : hw + (hw != "" and lw != "" ? " · " : "") + lw, soft)
string brk = "none recent"
color brkC = muted
if events.size() > 0
StructEvent e = events.last()
brk := e.kind + (e.dir == 1 ? " ▲ " : " ▼ ") + f_px(e.price) + " · " + str.tostring(bar_index - e.eventIdx) + " bars"
brkC := e.dir == 1 ? upColor : dnColor
f_cell3(15, "Last swing break", bright, "", bright, brk, brkC)
// patterns
f_section(16, "PATTERNS")
if active.size() == 0
f_cell3(17, "none active", muted, "", muted, "", muted)
else
for k = 0 to math.min(active.size(), 2) - 1
Pattern p = patterns.get(active.get(k))
color pc = p.expectedDirection == 1 ? upColor : p.expectedDirection == -1 ? dnColor : bright
f_cell3(17 + k, "● " + p.kind, pc, "", pc, f_patternStatus(p) + " · " + f_context(p) + " · Q" + str.tostring(math.round(p.quality)), soft)
f_cell3(19, "factor " + (na(usedFactor) ? "—" : str.tostring(usedFactor, "#.#")) + " · " + str.tostring(flipBars.size()) + " flips/100 · swing " + str.tostring(strength), faint, "", faint, "", faint)
table.cell_set_text_size(dash, 1, 19, size.tiny)
// ───────────────────────── Alerts (closed bar only)
alertcondition(flipUp, "Trend up", "TRE | UP | {{ticker}} | {{interval}} | close={{close}}")
alertcondition(flipDn, "Trend down", "TRE | DOWN | {{ticker}} | {{interval}} | close={{close}}")
alertcondition(patternFound, "New pattern found", "TRE | PATTERN | {{ticker}} | {{interval}} | close={{close}}")