本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// ══════════════════════════════════════════════════════════
// ══════════════════════════════════════════════════════════
indicator(title = "Adaptive Sweep Reclaim Pyramid", shorttitle = "ASR Pyramid", overlay = true, max_labels_count = 500)
// ══════════════════════════════════════════════════════════
// CONSTANTS
// ══════════════════════════════════════════════════════════
const string GRP_LIQ = "① Liquidity & Sweep"
const string GRP_REC = "② Reclaim Trigger"
const string GRP_FIX = "③ Weakness Fixes"
const string GRP_PYR = "④ Pyramid Orders"
const string GRP_VIS = "⑤ Visuals"
const string SRC_PREV = "HTF previous candle"
const string SRC_RANGE = "HTF rolling range"
const string SRC_PIV = "Swing pivots"
const string TRG_BAR = "Sweep-bar high/low"
const string TRG_RUN = "Opposite run open"
const string TRG_MS = "Micro structure break"
// ══════════════════════════════════════════════════════════
// INPUTS
// ══════════════════════════════════════════════════════════
// ── ① Liquidity & sweep ──
liqSourceInput = input.string(SRC_PREV, "Liquidity Source", options = [SRC_PREV, SRC_RANGE, SRC_PIV], group = GRP_LIQ,
tooltip = "HTF previous candle: last closed HTF high/low. HTF rolling range: extreme of the last N closed HTF candles. Swing pivots: latest confirmed chart-timeframe pivot high/low.")
htfAutoInput = input.bool(true, "Auto HTF", group = GRP_LIQ,
tooltip = "Choose the HTF from the chart timeframe: 1m→15m, 3m→30m, 5m→1H, 15m→4H, 1H→D, 4H→W. Off = use Manual HTF. Ignored with Swing pivots.")
htfManualInput = input.timeframe("60", "Manual HTF", group = GRP_LIQ,
tooltip = "HTF used when Auto HTF is off. Must be higher than the chart timeframe or the script stops with an error.")
rangeLenInput = input.int(3, "HTF Rolling Range Candles", minval = 2, maxval = 20, group = GRP_LIQ,
tooltip = "Closed HTF candles used by HTF rolling range. Higher = bigger, rarer liquidity pools. Lower = more frequent sweeps.")
pivLenInput = input.int(5, "Swing Pivot Strength", minval = 2, maxval = 50, group = GRP_LIQ,
tooltip = "Bars on each side required to confirm a swing pivot. Higher = more significant but later-confirmed levels. Lower = more, smaller levels.")
sweepMinInput = input.float(0.1, "Min Sweep Depth (×ATR)", minval = 0.0, maxval = 3.0, step = 0.05, group = GRP_LIQ,
tooltip = "Price must trade at least this many ATRs beyond the level to count as a sweep. Higher = only decisive stop runs. 0 = any touch beyond the level.")
sweepMaxInput = input.float(2.0, "Max Sweep Depth (×ATR)", minval = 0.0, maxval = 10.0, step = 0.1, group = GRP_LIQ,
tooltip = "If the sweep extends beyond this many ATRs, it is treated as a real breakout and the setup is cancelled. Lower = stricter. 0 = off.")
maxWaitInput = input.int(25, "Max Bars After Sweep", minval = 3, maxval = 300, group = GRP_LIQ,
tooltip = "Chart bars a sweep stays valid while waiting for the reclaim. Higher = more late signals. Lower = only fast reversals.")
// ── ② Reclaim trigger ──
triggerInput = input.string(TRG_BAR, "Reclaim Level", options = [TRG_BAR, TRG_RUN, TRG_MS], group = GRP_REC,
tooltip = "Sweep-bar: close beyond the high/low of the bar that made the sweep extreme. Run open: open of the opposite-color candle run. Micro structure: extreme of the bars before the sweep extreme.")
msLenInput = input.int(5, "Micro Structure Lookback", minval = 2, maxval = 50, group = GRP_REC,
tooltip = "Bars before the sweep extreme used by Micro structure break. Higher = deeper break required, fewer and later signals.")
dispAtrInput = input.float(0.5, "Displacement Body (×ATR)", minval = 0.0, maxval = 3.0, step = 0.05, group = GRP_REC,
tooltip = "Reclaim candle body must be at least this many ATRs. Higher = only strong displacement, fewer signals. 0 disables the check.")
closePosInput = input.float(0.6, "Min Close Location", minval = 0.0, maxval = 1.0, step = 0.05, group = GRP_REC,
tooltip = "Where the reclaim candle closes inside its range (1 = at the extreme in trade direction). Higher = demands strong closes, fewer signals. 0 = off.")
fvgInput = input.bool(false, "Require Fair Value Gap", group = GRP_REC,
tooltip = "Reclaim candle must leave a three-bar Fair Value Gap in trade direction. Confirms real displacement but removes many signals.")
atrLenInput = input.int(14, "ATR Length", minval = 2, maxval = 100, group = GRP_REC,
tooltip = "ATR period for sweep depth, displacement and the volatility filter. Higher = smoother, slower ATR. Lower = reacts faster.")
directionInput = input.string("Both", "Direction", options = ["Both", "Long only", "Short only"], group = GRP_REC,
tooltip = "Which side may produce Buy / Sell signals.")
// ── ③ Weakness fixes ──
confirmInput = input.bool(true, "FIX · Confirmed Bars Only", group = GRP_FIX,
tooltip = "Signals, adds and resets fire only on closed bars, so markers never appear then disappear (no repaint). Off = earlier but repainting signals.")
trendInput = input.bool(true, "FIX · KAMA Trend Filter", group = GRP_FIX,
tooltip = "Longs only when close is above the Kaufman Adaptive MA, shorts only below. KAMA flattens in chop and speeds up in trends, reducing lag.")
kamaLenInput = input.int(20, " KAMA Efficiency Length", minval = 2, maxval = 200, group = GRP_FIX,
tooltip = "Bars used to measure trend efficiency for KAMA. Higher = slower, steadier trend line. Lower = faster, noisier.")
kamaFastInput = input.int(2, " KAMA Fast Period", minval = 1, maxval = 50, group = GRP_FIX,
tooltip = "Speed of KAMA in clean trends. Lower = hugs price tighter when trending.")
kamaSlowInput = input.int(30, " KAMA Slow Period", minval = 5, maxval = 200, group = GRP_FIX,
tooltip = "Speed of KAMA in chop. Higher = flatter line in sideways markets, fewer trend flips.")
erInput = input.bool(true, "FIX · Efficiency Ratio Filter", group = GRP_FIX,
tooltip = "Blocks signals when the Efficiency Ratio is below the minimum, i.e. noisy sideways markets where sweeps fail often.")
erLenInput = input.int(14, " ER Length", minval = 3, maxval = 100, group = GRP_FIX,
tooltip = "Bars used for the Efficiency Ratio. Higher = slower regime detection. Lower = reacts faster but flips more.")
erMinInput = input.float(0.15, " Min Efficiency Ratio", minval = 0.0, maxval = 1.0, step = 0.05, group = GRP_FIX,
tooltip = "Minimum ER (0 = pure noise, 1 = straight line). Higher = only cleaner markets, fewer signals.")
volInput = input.bool(true, "FIX · ATR Expansion Filter", group = GRP_FIX,
tooltip = "Blocks signals when short ATR is small versus long ATR, avoiding dead, low-volatility sessions.")
volSlowInput = input.int(100, " Slow ATR Length", minval = 20, maxval = 1000, group = GRP_FIX,
tooltip = "Baseline ATR used for the expansion ratio. Higher = compares with a longer history.")
volMinInput = input.float(0.8, " Min ATR Ratio", minval = 0.1, maxval = 3.0, step = 0.05, group = GRP_FIX,
tooltip = "Minimum ATR / Slow ATR. Higher = only active, expanding markets, fewer signals. Lower = allows quieter markets.")
rvolInput = input.bool(false, "FIX · Relative Volume on Reclaim", group = GRP_FIX,
tooltip = "Reclaim candle volume must exceed its average by the multiple below. Ignored on symbols without volume.")
rvolLenInput = input.int(20, " Volume Average Length", minval = 2, maxval = 200, group = GRP_FIX,
tooltip = "Length of the volume moving average. Higher = smoother baseline.")
rvolMinInput = input.float(1.2, " Min Relative Volume", minval = 0.5, maxval = 5.0, step = 0.1, group = GRP_FIX,
tooltip = "Reclaim volume must be at least this multiple of the average. Higher = only high-participation reclaims.")
cooldownInput = input.int(5, "FIX · Cooldown Bars (same side)", minval = 0, maxval = 200, group = GRP_FIX,
tooltip = "Minimum bars between two first-order signals on the same side. Prevents clustered duplicates. 0 = off.")
conflictInput = input.string("Skip both", "FIX · Same-Bar Long & Short", options = ["Skip both", "Follow KAMA"], group = GRP_FIX,
tooltip = "When long and short signals appear on the same bar: skip both, or keep only the side on the KAMA trend side.")
invalidInput = input.bool(true, "FIX · Reset on Sweep Extreme Break", group = GRP_FIX,
tooltip = "A close beyond the sweep extreme ends the position state and pyramid count, so no orders are added into a failed setup.")
targetInput = input.bool(true, "FIX · Reset at Opposite Liquidity", group = GRP_FIX,
tooltip = "When price reaches the opposite liquidity level recorded at entry, the position state resets, so no adds are placed at the likely reaction zone.")
// ── ④ Pyramid ──
pyrOnInput = input.bool(true, "Enable Pyramid", group = GRP_PYR,
tooltip = "Allow extra add-on orders after the first Buy / Sell while the position state is open.")
pyrMaxInput = input.int(3, "Max Orders per Side", minval = 1, maxval = 10, group = GRP_PYR,
tooltip = "Total orders per side including the first signal. Higher = more scaling and exposure. 1 = no add-ons.")
pyrModeInput = input.string("ATR", "Spacing Mode", options = ["Ticks", "ATR"], group = GRP_PYR,
tooltip = "How distance between orders is measured: fixed ticks, or a multiple of ATR that adapts to volatility.")
pyrTicksInput = input.int(50, " Spacing (Ticks)", minval = 1, maxval = 100000, group = GRP_PYR,
tooltip = "Ticks mode: distance from the last order in ticks (syminfo.mintick). Higher = fewer, wider add-ons.")
pyrAtrLenInput = input.int(14, " Spacing ATR Length", minval = 2, maxval = 100, group = GRP_PYR,
tooltip = "ATR mode: ATR period used for spacing. Higher = smoother spacing.")
pyrAtrMultInput = input.float(1.0, " Spacing ATR Multiplier", minval = 0.1, maxval = 10.0, step = 0.1, group = GRP_PYR,
tooltip = "ATR mode: spacing = multiplier × ATR. Higher = wider spacing, fewer add-ons.")
pyrDirInput = input.string("Favorable", "Add When Price Moves", options = ["Favorable", "Adverse"], group = GRP_PYR,
tooltip = "Favorable: add Buy after price rises by the spacing above the last buy (Sell after it falls). Adverse: add when price moves against the last order (averaging).")
pyrGapInput = input.int(2, " Min Bars Between Adds", minval = 0, maxval = 100, group = GRP_PYR,
tooltip = "Minimum bars between consecutive orders on the same side. Higher = adds spread over time. 0 = off.")
pyrBarDirInput = input.bool(true, " Add Only on Bar Closing With Trade", group = GRP_PYR,
tooltip = "Pyramid Buy only on a bullish close, Pyramid Sell only on a bearish close. Avoids adding into momentum against the position.")
// ── ⑤ Visuals ──
showLevelsInput = input.bool(true, "Show Liquidity Levels", group = GRP_VIS,
tooltip = "Step lines at the buy-side (high) and sell-side (low) liquidity being watched for sweeps.")
showReclaimInput = input.bool(true, "Show Reclaim Level", group = GRP_VIS,
tooltip = "Dots at the level price must close beyond after a sweep to trigger a signal.")
showKamaInput = input.bool(false, "Show KAMA", group = GRP_VIS,
tooltip = "Plot the Kaufman Adaptive MA used by the trend filter.")
showStopInput = input.bool(true, "Show Sweep Extreme & Target", group = GRP_VIS,
tooltip = "Lines at the sweep extreme (invalidation) and opposite liquidity (target) of the open position state.")
showNumInput = input.bool(true, "Numbered Pyramid Labels", group = GRP_VIS,
tooltip = "Label each add-on as B2, B3… / S2, S3…. Off = small diamond markers instead.")
showDashInput = input.bool(true, "Show Dashboard", group = GRP_VIS,
tooltip = "Status table: position, orders, pending setups and filter state.")
bullColorInput = input.color(#00C853, "Buy Color", group = GRP_VIS,
tooltip = "Color of Buy signals, pyramid buys and the sell-side liquidity line.")
bearColorInput = input.color(#FF1744, "Sell Color", group = GRP_VIS,
tooltip = "Color of Sell signals, pyramid sells and the buy-side liquidity line.")
// ══════════════════════════════════════════════════════════
// HTF SELECTION & VALIDATION
// ══════════════════════════════════════════════════════════
int chartSec = timeframe.in_seconds()
string autoTF = chartSec <= 60 ? "15" : chartSec <= 180 ? "30" : chartSec <= 300 ? "60" : chartSec <= 900 ? "240" : chartSec <= 3600 ? "D" : chartSec <= 14400 ? "W" : "M"
string htfTF = htfAutoInput ? autoTF : htfManualInput
bool useHtf = liqSourceInput != SRC_PIV
if barstate.isfirst and useHtf and timeframe.in_seconds(htfTF) <= chartSec
runtime.error("HTF must be higher than the chart timeframe")
// ══════════════════════════════════════════════════════════
// HELPERS
// ══════════════════════════════════════════════════════════
// Kaufman Efficiency Ratio: net move / total path over len bars (0..1)
effRatio(int len) =>
float chg = math.abs(close - close[len])
float noise = math.sum(math.abs(close - close[1]), len)
nz(noise) > 0 ? nz(chg) / noise : 0.0
// ══════════════════════════════════════════════════════════
// CORE SERIES (computed every bar)
// ══════════════════════════════════════════════════════════
float atr = ta.atr(atrLenInput)
float atrSlow = ta.atr(volSlowInput)
float atrRatio = nz(atrSlow) > 0 ? atr / atrSlow : na
float pyrAtr = ta.atr(pyrAtrLenInput)
float volSma = ta.sma(volume, rvolLenInput)
float msHigh = ta.highest(high, msLenInput)[1]
float msLow = ta.lowest(low, msLenInput)[1]
float er = effRatio(erLenInput)
// KAMA (Kaufman Adaptive Moving Average)
float kEr = effRatio(kamaLenInput)
float fastSc = 2.0 / (kamaFastInput + 1)
float slowSc = 2.0 / (kamaSlowInput + 1)
float sc = math.pow(kEr * (fastSc - slowSc) + slowSc, 2)
var float kama = na
kama := na(kama) ? close : kama + sc * (close - kama)
// Candle quality
float rng = high - low
float clvBull = rng > 0 ? (close - low) / rng : 0.5
float clvBear = rng > 0 ? (high - close) / rng : 0.5
bool fvgBull = low > high[2]
bool fvgBear = high < low[2]
// ══════════════════════════════════════════════════════════
// LIQUIDITY: HTF AGGREGATION (from chart bars — no request.security, no lookahead)
// ══════════════════════════════════════════════════════════
var float htfH = na
var float htfL = na
var int htfCount = 0
var array<float> hHist = array.new<float>()
var array<float> lHist = array.new<float>()
bool newHtf = timeframe.change(htfTF)
if newHtf or na(htfH)
// FIX: the first aggregated HTF candle is usually partial — skip it
if not na(htfH) and htfCount > 1
hHist.push(htfH)
lHist.push(htfL)
if hHist.size() > 50
hHist.shift()
lHist.shift()
htfCount += 1
htfH := high
htfL := low
else
htfH := math.max(htfH, high)
htfL := math.min(htfL, low)
// ── Swing pivots (confirmed pivLen bars later → no repaint) ──
float ph = ta.pivothigh(high, pivLenInput, pivLenInput)
float pl = ta.pivotlow(low, pivLenInput, pivLenInput)
var float pivHigh = na
var float pivLow = na
bool newPivHigh = not na(ph)
bool newPivLow = not na(pl)
if newPivHigh
pivHigh := ph
if newPivLow
pivLow := pl
float liqHigh = na
float liqLow = na
if useHtf
int nLiq = liqSourceInput == SRC_PREV ? 1 : rangeLenInput
if hHist.size() >= nLiq
int sz = hHist.size()
liqHigh := hHist.slice(sz - nLiq, sz).max()
liqLow := lHist.slice(sz - nLiq, sz).min()
else
liqHigh := pivHigh
liqLow := pivLow
// one sweep event per liquidity level
var bool hiUsed = false
var bool loUsed = false
if useHtf ? newHtf : newPivHigh
hiUsed := false
if useHtf ? newHtf : newPivLow
loUsed := false
// ══════════════════════════════════════════════════════════
// RECLAIM LEVEL CANDIDATES
// ══════════════════════════════════════════════════════════
var float dnRunOpen = na // open of the latest run of bearish candles
var float upRunOpen = na // open of the latest run of bullish candles
var int runDir = 0
if close < open
if runDir != -1
dnRunOpen := open
runDir := -1
else if close > open
if runDir != 1
upRunOpen := open
runDir := 1
float longLvlNow = triggerInput == TRG_BAR ? high : triggerInput == TRG_RUN ? dnRunOpen : msHigh
float shortLvlNow = triggerInput == TRG_BAR ? low : triggerInput == TRG_RUN ? upRunOpen : msLow
// ══════════════════════════════════════════════════════════
// SWEEP CONTEXTS
// ══════════════════════════════════════════════════════════
var bool bActive = false
var float bExt = na
var int bStart = na
var float bLevel = na
var float bLiq = na
var bool sActive = false
var float sExt = na
var int sStart = na
var float sLevel = na
var float sLiq = na
bool allowLong = directionInput != "Short only"
bool allowShort = directionInput != "Long only"
// sell-side sweep (below liqLow) → long context
if not na(liqLow) and low < liqLow and not loUsed
if sweepMinInput == 0 or liqLow - low >= sweepMinInput * nz(atr) // FIX: shallow pokes are not sweeps
loUsed := true
if allowLong
if not bActive
bActive := true
bExt := low
bLevel := longLvlNow
bLiq := liqLow
bStart := bar_index // a fresh sweep restarts the wait window
if bActive and low < bExt // new extreme → re-anchor reclaim level
bExt := low
bLevel := longLvlNow
// buy-side sweep (above liqHigh) → short context
if not na(liqHigh) and high > liqHigh and not hiUsed
if sweepMinInput == 0 or high - liqHigh >= sweepMinInput * nz(atr)
hiUsed := true
if allowShort
if not sActive
sActive := true
sExt := high
sLevel := shortLvlNow
sLiq := liqHigh
sStart := bar_index
if sActive and high > sExt
sExt := high
sLevel := shortLvlNow
// FIX: sweep too deep = genuine breakout, not a stop hunt → cancel
if sweepMaxInput > 0 and bActive and bLiq - bExt > sweepMaxInput * nz(atr)
bActive := false
if sweepMaxInput > 0 and sActive and sExt - sLiq > sweepMaxInput * nz(atr)
sActive := false
// expiry
if bActive and bar_index - bStart > maxWaitInput
bActive := false
if sActive and bar_index - sStart > maxWaitInput
sActive := false
// ══════════════════════════════════════════════════════════
// SIGNAL CONDITIONS + FILTERS
// ══════════════════════════════════════════════════════════
var int lastBuyBar = na
var int lastSellBar = na
bool confOk = not confirmInput or barstate.isconfirmed // FIX: repaint
bool dispOk = dispAtrInput == 0 or math.abs(close - open) >= dispAtrInput * nz(atr)
bool rvolOk = not rvolInput or na(volume) or na(volSma) or volSma == 0 or volume >= rvolMinInput * volSma // FIX: participation
bool erOk = not erInput or er >= erMinInput // FIX: sideways
bool volOk = not volInput or (not na(atrRatio) and atrRatio >= volMinInput) // FIX: dead volatility
bool warmOk = bar_index > math.max(atrLenInput, erLenInput, kamaLenInput)
bool baseOk = confOk and dispOk and rvolOk and erOk and volOk and warmOk
bool longConf = clvBull >= closePosInput and (not fvgInput or fvgBull)
bool shortConf = clvBear >= closePosInput and (not fvgInput or fvgBear)
bool trendLongOk = not trendInput or close > kama // FIX: trend
bool trendShortOk = not trendInput or close < kama
bool coolLongOk = cooldownInput == 0 or na(lastBuyBar) or bar_index - lastBuyBar > cooldownInput // FIX: duplicates
bool coolShortOk = cooldownInput == 0 or na(lastSellBar) or bar_index - lastSellBar > cooldownInput
// Buy: after a sell-side sweep, a bullish displacement candle closes above the reclaim level
bool longSig = bActive and not na(bLevel) and close > bLevel and close > open and longConf and baseOk and trendLongOk and coolLongOk
// Sell: after a buy-side sweep, a bearish displacement candle closes below the reclaim level
bool shortSig = sActive and not na(sLevel) and close < sLevel and close < open and shortConf and baseOk and trendShortOk and coolShortOk
// FIX: same-bar conflict
if longSig and shortSig
bool keepLong = conflictInput == "Follow KAMA" and close > kama
bool keepShort = conflictInput == "Follow KAMA" and close < kama
longSig := keepLong
shortSig := keepShort
bActive := false
sActive := false
// ══════════════════════════════════════════════════════════
// POSITION STATE & PYRAMID
// ══════════════════════════════════════════════════════════
var int posDir = 0
var int buyCount = 0
var int sellCount = 0
var float lastBuyPx = na
var float lastSellPx = na
var float stopLvl = na
var float tgtLvl = na
var int lastAddBar = na
bool evBuy = false
bool evSell = false
bool evPyrBuy = false
bool evPyrSell = false
bool evInvalid = false
bool evTarget = false
// FIX: invalidation — close beyond the sweep extreme resets the state
if invalidInput and confOk and posDir != 0 and not na(stopLvl)
if (posDir == 1 and close < stopLvl) or (posDir == -1 and close > stopLvl)
evInvalid := true
// FIX: target — price reaches the opposite liquidity recorded at entry
if targetInput and confOk and posDir != 0 and not evInvalid and not na(tgtLvl)
if (posDir == 1 and high >= tgtLvl) or (posDir == -1 and low <= tgtLvl)
evTarget := true
if evInvalid or evTarget
posDir := 0
buyCount := 0
sellCount := 0
lastBuyPx := na
lastSellPx := na
float spacing = pyrModeInput == "Ticks" ? pyrTicksInput * syminfo.mintick : pyrAtrMultInput * nz(pyrAtr)
bool gapOk = pyrGapInput == 0 or na(lastAddBar) or bar_index - lastAddBar >= pyrGapInput
if longSig
// first Buy order — opposite side reset
evBuy := true
posDir := 1
buyCount := 1
lastBuyPx := close
sellCount := 0
lastSellPx := na
stopLvl := bExt
tgtLvl := liqHigh
lastBuyBar := bar_index
lastAddBar := bar_index
bActive := false
else if shortSig
// first Sell order — opposite side reset
evSell := true
posDir := -1
sellCount := 1
lastSellPx := close
buyCount := 0
lastBuyPx := na
stopLvl := sExt
tgtLvl := liqLow
lastSellBar := bar_index
lastAddBar := bar_index
sActive := false
else if pyrOnInput and confOk and spacing > 0 and gapOk
// Pyramid Buy — Favorable: close >= last buy + spacing (price moved UP, adding to a winner)
// Adverse: close <= last buy − spacing (price moved DOWN, averaging)
if posDir == 1 and buyCount < pyrMaxInput and (not pyrBarDirInput or close > open)
bool distOk = pyrDirInput == "Favorable" ? close >= lastBuyPx + spacing : close <= lastBuyPx - spacing
if distOk
evPyrBuy := true
buyCount += 1
lastBuyPx := close
lastAddBar := bar_index
// Pyramid Sell — Favorable: close <= last sell − spacing (price moved DOWN, adding to a winner)
// Adverse: close >= last sell + spacing (price moved UP, averaging)
else if posDir == -1 and sellCount < pyrMaxInput and (not pyrBarDirInput or close < open)
bool distOk = pyrDirInput == "Favorable" ? close <= lastSellPx - spacing : close >= lastSellPx + spacing
if distOk
evPyrSell := true
sellCount += 1
lastSellPx := close
lastAddBar := bar_index
// ══════════════════════════════════════════════════════════
// PLOTS
// ══════════════════════════════════════════════════════════
plot(showLevelsInput ? liqHigh : na, "Buy-side Liquidity", color.new(bearColorInput, 40), 1, plot.style_stepline)
plot(showLevelsInput ? liqLow : na, "Sell-side Liquidity", color.new(bullColorInput, 40), 1, plot.style_stepline)
plot(showReclaimInput and bActive ? bLevel : na, "Long Reclaim Level", color.new(bullColorInput, 20), 2, plot.style_circles)
plot(showReclaimInput and sActive ? sLevel : na, "Short Reclaim Level", color.new(bearColorInput, 20), 2, plot.style_circles)
plot(showKamaInput ? kama : na, "KAMA", color.new(color.orange, 0), 2)
plot(showStopInput and posDir != 0 ? stopLvl : na, "Sweep Extreme", color.new(color.gray, 20), 1, plot.style_linebr)
plot(showStopInput and posDir != 0 ? tgtLvl : na, "Opposite Liquidity Target", color.new(color.aqua, 30), 1, plot.style_linebr)
// first orders
plotshape(evBuy, "Buy", shape.triangleup, location.belowbar, bullColorInput, size = size.small, text = "B1", textcolor = bullColorInput)
plotshape(evSell, "Sell", shape.triangledown, location.abovebar, bearColorInput, size = size.small, text = "S1", textcolor = bearColorInput)
// pyramid adds (diamonds when numbered labels are off)
plotshape(evPyrBuy and not showNumInput, "Pyramid Buy", shape.diamond, location.belowbar, color.new(bullColorInput, 25), size = size.tiny)
plotshape(evPyrSell and not showNumInput, "Pyramid Sell", shape.diamond, location.abovebar, color.new(bearColorInput, 25), size = size.tiny)
plotshape(evInvalid, "Setup Invalidated", shape.xcross, location.abovebar, color.new(color.gray, 0), size = size.tiny)
plotshape(evTarget, "Target Reached", shape.flag, location.abovebar, color.new(color.aqua, 0), size = size.tiny)
if showNumInput and evPyrBuy
label.new(bar_index, low, "B" + str.tostring(buyCount), yloc = yloc.belowbar, style = label.style_label_up, color = color.new(bullColorInput, 25), textcolor = color.white, size = size.small)
if showNumInput and evPyrSell
label.new(bar_index, high, "S" + str.tostring(sellCount), yloc = yloc.abovebar, style = label.style_label_down, color = color.new(bearColorInput, 25), textcolor = color.white, size = size.small)
// ══════════════════════════════════════════════════════════
// DASHBOARD
// ══════════════════════════════════════════════════════════
var table dash = table.new(position.top_right, 2, 9, bgcolor = color.new(#131722, 10), border_color = color.new(#2A2E39, 0), border_width = 1)
dashRow(int r, string k, string v, color vc) =>
table.cell(dash, 0, r, k, text_color = color.new(#9E9E9E, 0), text_size = size.small, text_halign = text.align_left)
table.cell(dash, 1, r, v, text_color = vc, text_size = size.small, text_halign = text.align_right)
if showDashInput and barstate.islast
string srcStr = useHtf ? liqSourceInput + " · " + htfTF : liqSourceInput
table.cell(dash, 0, 0, "ASR Pyramid", text_color = color.white, bgcolor = color.new(#1565C0, 0), text_size = size.small)
table.merge_cells(dash, 0, 0, 1, 0)
string posStr = posDir == 1 ? "LONG ×" + str.tostring(buyCount) : posDir == -1 ? "SHORT ×" + str.tostring(sellCount) : "Flat"
color posCol = posDir == 1 ? bullColorInput : posDir == -1 ? bearColorInput : color.gray
dashRow(1, "Liquidity", srcStr, color.white)
dashRow(2, "Position", posStr, posCol)
dashRow(3, "Max Orders", pyrOnInput ? str.tostring(pyrMaxInput) : "1 (pyramid off)", color.white)
dashRow(4, "Long Setup", bActive ? "Reclaim > " + str.tostring(bLevel, format.mintick) : "—", bActive ? bullColorInput : color.gray)
dashRow(5, "Short Setup", sActive ? "Reclaim < " + str.tostring(sLevel, format.mintick) : "—", sActive ? bearColorInput : color.gray)
string trStr = not trendInput ? "Off" : close > kama ? "Bullish" : "Bearish"
dashRow(6, "KAMA Trend", trStr, trStr == "Bullish" ? bullColorInput : trStr == "Bearish" ? bearColorInput : color.gray)
dashRow(7, "Efficiency", str.tostring(er, "#.00") + (erOk ? " ✓" : " ✕"), erOk ? color.white : color.orange)
dashRow(8, "ATR Ratio", na(atrRatio) ? "—" : str.tostring(atrRatio, "#.00") + (volOk ? " ✓" : " ✕"), volOk ? color.white : color.orange)
// ══════════════════════════════════════════════════════════
// ALERTS
// ══════════════════════════════════════════════════════════
alertcondition(evBuy, "Buy", "ASR Pyramid: BUY (first order) on {{ticker}} {{interval}} @ {{close}}")
alertcondition(evSell, "Sell", "ASR Pyramid: SELL (first order) on {{ticker}} {{interval}} @ {{close}}")
alertcondition(evPyrBuy, "Pyramid Buy", "ASR Pyramid: PYRAMID BUY add-on on {{ticker}} {{interval}} @ {{close}}")
alertcondition(evPyrSell, "Pyramid Sell", "ASR Pyramid: PYRAMID SELL add-on on {{ticker}} {{interval}} @ {{close}}")
alertcondition(evInvalid, "Setup Invalidated", "ASR Pyramid: sweep extreme broken, state reset on {{ticker}} @ {{close}}")
alertcondition(evTarget, "Target Reached", "ASR Pyramid: opposite liquidity reached, state reset on {{ticker}} @ {{close}}")