HARSH PATEL SMC INDICATOR

Harrypatel7 · study · 1122 行 · 点赞 407 · TradingView 原页

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

Pine Script

//@version=6
// ╔══════════════════════════════════════════════════════════════════════╗
// ║                 SMC PRO SUITE  ·  v3.0  (Pine Script v6)             ║
// ║   Market Structure · Order Blocks · Fibonacci · Auto S/R · Trendlines║
// ║        Confluence-scored BUY / SELL signals with trade planner       ║
// ╠══════════════════════════════════════════════════════════════════════╣
// ║  • Structure  : HH/HL/LH/LL, BOS (continuation) and CHoCH (reversal) ║
// ║  • Order Block: last opposite candle before the break, auto-mitigated║
// ║  • Fibonacci  : latest swing leg, Golden Zone, Premium / Discount    ║
// ║  • S/R        : clustered swing pivots with touch count              ║
// ║  • Trendlines : rising support / falling resistance + breakouts      ║
// ║  • Signals    : 8-point confluence score, ★ = highly recommended     ║
// ║  • Positions  : auto LONG / SHORT boxes on every signal, live result ║
// ║  • Planner    : next LONG / SHORT zone with Entry / SL / TP          ║
// ║  • Short-term : EMA 9/21 + VWAP + RSI scalp signals with SL / TP     ║
// ║  • Accuracy   : displacement/FVG OBs, ADX chop filter, min SL        ║
// ║  • Dashboard  : market state, levels, plan, live win-rate            ║
// ╠══════════════════════════════════════════════════════════════════════╣
// ║  Educational tool only — not financial advice. Paper trade first.    ║
// ╚══════════════════════════════════════════════════════════════════════╝
indicator("SMC Pro Suite v6 · Structure · OB · Fib · S/R", shorttitle="SMC Pro v6", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count=500, max_bars_back=1000, dynamic_requests=true)
 
// ══════════════════════════════════════════════════════════════════════
// INPUTS
// ══════════════════════════════════════════════════════════════════════
grpT = "① Appearance"
theme      = input.string("Dark", "Theme", options=["Dark", "Light"], group=grpT, tooltip="Match your TradingView chart background.")
cBull      = input.color(#22AB94, "Bullish", inline="pal", group=grpT)
cBear      = input.color(#F7525F, "Bearish", inline="pal", group=grpT)
cAccent    = input.color(#2962FF, "Accent", inline="pal", group=grpT)
txtOpt     = input.string("Small", "Chart text size", options=["Tiny", "Small", "Normal"], group=grpT)
trendBars  = input.bool(false, "Color candles by trend", group=grpT)
 
grpS = "② Market Structure"
swingLen   = input.int(10, "Swing length", minval=2, maxval=50, group=grpS, tooltip="Bars left/right to confirm a swing. Lower = faster, higher = cleaner.")
showStruct = input.bool(true, "Show BOS / CHoCH", group=grpS)
showSwings = input.bool(false, "Show HH / HL / LH / LL labels", group=grpS)
 
grpOB = "③ Order Blocks"
showOB    = input.bool(true, "Show order blocks", group=grpOB)
obMax     = input.int(4, "Max active per side", minval=1, maxval=20, group=grpOB)
obMitig   = input.string("Close", "Mitigation source", options=["Close", "Wick"], group=grpOB)
obOpp     = input.bool(true, "Use last opposite-color candle (true SMC OB)", group=grpOB)
obOnce    = input.bool(true, "One signal per order block", group=grpOB, tooltip="The first retest is the highest-probability one.")
showMitig = input.bool(false, "Keep mitigated OBs (faded)", group=grpOB)
needDisp  = input.bool(true, "Only OBs with displacement or FVG", group=grpOB, tooltip="Accuracy: an OB is created only if the break was impulsive (big body) or left a Fair Value Gap. Weak breaks are ignored.")
dispMult  = input.float(1.0, "Displacement body (× ATR)", minval=0.1, step=0.1, group=grpOB)
 
grpF = "④ Fibonacci"
showFib = input.bool(true, "Show Fibonacci on latest leg", group=grpF)
fibKey  = input.bool(true, "Key levels only (0 · 0.5 · 0.618 · 0.786 · 1)", group=grpF)
fibExt  = input.int(20, "Extend right (bars)", minval=1, maxval=200, group=grpF)
showGZ  = input.bool(true, "Highlight Golden Zone", group=grpF)
 
grpSR = "⑤ Auto Support / Resistance"
showSR     = input.bool(true, "Show S/R zones", group=grpSR)
srLen      = input.int(15, "Pivot length", minval=2, maxval=100, group=grpSR, tooltip="Bigger = only major levels.")
srLookback = input.int(30, "Pivots to scan", minval=5, maxval=100, group=grpSR)
srTol      = input.float(0.5, "Zone height / merge tolerance (× ATR)", minval=0.1, step=0.1, group=grpSR)
srMinTouch = input.int(2, "Min touches", minval=1, maxval=10, group=grpSR)
srMaxLines = input.int(6, "Max zones shown", minval=1, maxval=20, group=grpSR)
 
grpTL = "⑥ Auto Trendlines"
showTL  = input.bool(true, "Show trendlines", group=grpTL)
tlLen   = input.int(10, "Pivot length", minval=2, maxval=100, group=grpTL)
tlKeep  = input.bool(true, "Keep broken trendlines", group=grpTL)
tlSig   = input.bool(true, "Mark breakouts", group=grpTL)
upTLCol = input.color(#00BCD4, "Rising", inline="tl", group=grpTL)
dnTLCol = input.color(#B388FF, "Falling", inline="tl", group=grpTL)
 
grpSig = "⑦ Signals"
showSig     = input.bool(true, "Show BUY / SELL signals", group=grpSig)
onlyStrong  = input.bool(false, "Show only ★ highly recommended", group=grpSig)
minScore    = input.int(3, "Min score for a signal (0-8)", minval=0, maxval=8, group=grpSig)
strongScore = input.int(6, "Min score for ★ (0-8)", minval=1, maxval=8, group=grpSig, tooltip="On symbols without volume the max is 7, so 1 point less is required automatically.")
needPD      = input.bool(true, "BUY in Discount · SELL in Premium", group=grpSig)
needSRTL    = input.bool(true, "Require S/R or trendline confluence", group=grpSig)
needGZ      = input.bool(false, "Require Fib Golden Zone (strict)", group=grpSig)
cooldown    = input.int(5, "Min bars between signals", minval=0, group=grpSig)
strongBg    = input.bool(true, "Highlight ★ signal bars", group=grpSig)
 
grpR = "⑧ Risk & Trade Planner"
posMode    = input.string("All signals", "Auto-draw LONG / SHORT positions", options=["All signals", "★ only", "Latest only", "Off"], group=grpR, tooltip="Draws a TradingView-style Long/Short position (red risk box + green reward box) automatically on every signal. It extends until TP, SL or time-out is hit and then shows the result in R.")
posMaxBars = input.int(60, "Auto-close position after (bars)", minval=5, maxval=500, group=grpR)
posMaxOpen = input.int(10, "Max open positions tracked", minval=1, maxval=50, group=grpR)
rr       = input.float(2.0, "Risk : Reward (TP1)", minval=0.5, step=0.5, group=grpR)
slBufAtr = input.float(0.2, "SL buffer (× ATR)", minval=0.0, step=0.1, group=grpR)
minSlAtr = input.float(0.5, "Min SL distance (× ATR)", minval=0.0, step=0.1, group=grpR, tooltip="Accuracy: stops that are too tight get hit by normal noise.")
 
grpE = "⑨ Trend Filters"
showEma32 = input.bool(true, "Show EMA 32", group=grpE)
ema32Len  = input.int(32, "Fast EMA length", minval=1, group=grpE)
useEma    = input.bool(false, "Use slow EMA as hard filter", group=grpE)
emaLen    = input.int(200, "Slow EMA length", minval=1, group=grpE)
htfTf     = input.timeframe("240", "Higher timeframe", group=grpE)
htfEma    = input.int(50, "HTF EMA length", minval=1, group=grpE)
useHTF    = input.bool(false, "Require HTF alignment (hard filter)", group=grpE)
useChop   = input.bool(true, "Avoid choppy market (ADX filter)", group=grpE, tooltip="Accuracy: no signals when ADX is below the threshold (sideways market).")
adxMin    = input.int(18, "Min ADX", minval=5, maxval=50, group=grpE)
 
grpV = "⑩ Volume & Session"
useVol  = input.bool(true, "Volume confirmation in score", group=grpV, tooltip="Auto-skipped on symbols with no volume (e.g. NIFTY / BANKNIFTY spot).")
volLen  = input.int(20, "Volume average length", minval=1, group=grpV)
volMult = input.float(1.0, "Volume > average ×", minval=0.1, step=0.1, group=grpV)
useSess = input.bool(false, "Signals only inside session", group=grpV)
sess    = input.session("0930-1500", "Session (exchange time)", group=grpV)
 
grpST = "⑪ Short-Term (Scalp) Signals"
showST       = input.bool(true, "Show short-term BUY / SELL", group=grpST)
stFast       = input.int(9, "Fast EMA", minval=1, inline="st", group=grpST)
stSlow       = input.int(21, "Slow EMA", minval=2, inline="st", group=grpST)
stShowEma    = input.bool(false, "Plot fast / slow EMAs", group=grpST)
stRsiLen     = input.int(14, "RSI length", minval=2, group=grpST)
stRsiMax     = input.int(70, "RSI overbought (BUY blocked above)", minval=55, maxval=90, group=grpST, tooltip="SELL is blocked below 100 − this value.")
stUseVwap    = input.bool(true, "Require price on correct side of VWAP", group=grpST)
stShowVwap   = input.bool(false, "Plot VWAP", group=grpST)
stNeedStruct = input.bool(true, "Don't trade against SMC structure", group=grpST)
stSwingLb    = input.int(5, "Stop: swing lookback (bars)", minval=2, maxval=50, group=grpST)
stMaxSlAtr   = input.float(1.5, "Stop: max distance (× ATR)", minval=0.3, step=0.1, group=grpST)
stRR         = input.float(1.5, "Risk : Reward (short-term)", minval=0.5, step=0.25, group=grpST)
stCooldown   = input.int(3, "Min bars between short-term signals", minval=0, group=grpST)
stPos        = input.bool(true, "Auto-draw short-term LONG / SHORT positions", group=grpST)
 
grpD = "⑫ Dashboard"
showDash   = input.bool(true, "Show dashboard", group=grpD)
dashLayout = input.string("Full", "Layout", options=["Full", "Compact"], group=grpD)
dashPos    = input.string("Top Right", "Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=grpD)
dashOpt    = input.string("Small", "Text size", options=["Tiny", "Small", "Normal"], group=grpD)
 
// ══════════════════════════════════════════════════════════════════════
// THEME
// ══════════════════════════════════════════════════════════════════════
isDark  = theme == "Dark"
cText   = isDark ? #D1D4DC : #131722
cMuted  = #787B86
cPanel  = isDark ? #161A25 : #FFFFFF
cHead   = isDark ? #1E222D : #F0F3FA
cBorder = isDark ? #2A2E39 : #E0E3EB
cGold   = #F5B342
cWarn   = #FF9800
clear   = color.new(color.black, 100)
txtSz   = txtOpt == "Tiny" ? size.tiny : txtOpt == "Small" ? size.small : size.normal
dashSz  = dashOpt == "Tiny" ? size.tiny : dashOpt == "Small" ? size.small : size.normal
 
// ══════════════════════════════════════════════════════════════════════
// HELPERS
// ══════════════════════════════════════════════════════════════════════
f_fib(r, hi, lo, up) => up ? hi - (hi - lo) * r : lo + (hi - lo) * r
f_px(p) => str.tostring(p, format.mintick)
 
// number of S/R pivots within `tol` of `price`
f_touches(arr, price, tol) =>
    int c = 0
    int n = array.size(arr)
    if n > 0
        for i = 0 to n - 1
            if math.abs(array.get(arr, i) - price) <= tol
                c += 1
    c
 
// nearest qualified S/R level above (above=true) or below `price`
f_nextLevel(arr, price, tol, minT, above) =>
    float best = na
    int n = array.size(arr)
    if n > 0
        for i = 0 to n - 1
            float p = array.get(arr, i)
            bool side = above ? p > price + tol : p < price - tol
            if side and (na(best) or (above ? p < best : p > best))
                if f_touches(arr, p, tol) >= minT
                    best := p
    best
 
f_stars(q, mx) =>
    string s = ""
    for i = 1 to mx
        s := s + (i <= q ? "★" : "☆")
    s
 
f_bar(q, mx) =>
    string s = ""
    for i = 1 to mx
        s := s + (i <= q ? "■" : "□")
    s
 
f_wr(w, l) => w + l == 0 ? "—" : str.tostring(math.round(100.0 * w / (w + l))) + "%  (" + str.tostring(w) + "/" + str.tostring(w + l) + ")"
 
f_why(isBuy, pd, gz, sr, tl, emaOk, htf, candle, vol, hasV) =>
    string s = (isBuy ? "BUY" : "SELL") + " CONFLUENCE\n"
    s := s + (pd ? "✓  " : "✗  ") + (isBuy ? "Discount zone" : "Premium zone") + "\n"
    s := s + (gz ? "✓  " : "✗  ") + "Fib Golden Zone\n"
    s := s + (sr ? "✓  " : "✗  ") + (isBuy ? "At support" : "At resistance") + "\n"
    s := s + (tl ? "✓  " : "✗  ") + "Trendline confluence / breakout\n"
    s := s + (emaOk ? "✓  " : "✗  ") + "EMA 32 aligned & sloping\n"
    s := s + (htf ? "✓  " : "✗  ") + "Higher-TF trend aligned\n"
    s := s + (candle ? "✓  " : "✗  ") + "Strong confirmation candle"
    s := s + (hasV ? "\n" + (vol ? "✓  " : "✗  ") + "Volume above average" : "")
    s
 
// word-wrap a string to lines of about `w` characters
f_wrap(s, w) =>
    array<string> words = str.split(s, " ")
    string out  = ""
    string line_ = ""
    for wd in words
        if str.length(line_) + str.length(wd) + 1 > w and str.length(line_) > 0
            out   := out + line_ + "\n"
            line_ := wd
        else
            line_ := str.length(line_) == 0 ? wd : line_ + " " + wd
    out + line_
 
// dashboard helpers
f_head(tb, r, title, bg, tc, sz) =>
    table.cell(tb, 0, r, title, text_color=tc, bgcolor=bg, text_size=sz, text_halign=text.align_left)
    table.cell(tb, 1, r, "", bgcolor=bg, text_size=sz)
    table.merge_cells(tb, 0, r, 1, r)
    r + 1
 
f_row(tb, r, k, v, vc, bg, kc, sz) =>
    table.cell(tb, 0, r, k, text_color=kc, bgcolor=bg, text_size=sz, text_halign=text.align_left)
    table.cell(tb, 1, r, v, text_color=vc, bgcolor=bg, text_size=sz, text_halign=text.align_right)
    r + 1
 
// ══════════════════════════════════════════════════════════════════════
// CORE SERIES
// ══════════════════════════════════════════════════════════════════════
atr = ta.atr(14)
ema = ta.ema(close, emaLen)
plot(useEma ? ema : na, "Slow EMA", color=color.new(cMuted, 0), linewidth=1)
 
ema32   = ta.ema(close, ema32Len)
ema32Up = ema32 > ema32[1]
plot(showEma32 ? ema32 : na, "EMA 32", color=ema32Up ? cBull : cBear, linewidth=2)
 
// Higher-timeframe trend (non-repainting: previous closed HTF bar)
htfDiff = request.security(syminfo.tickerid, htfTf, close[1] - ta.ema(close, htfEma)[1], lookahead=barmerge.lookahead_on)
htfBull = htfDiff > 0
htfBear = htfDiff < 0
 
// Volume (auto-disabled when the symbol has no volume data)
hasVol   = ta.cum(nz(volume)) > 0
volScore = useVol and hasVol
volOk    = nz(volume) > ta.sma(nz(volume), volLen) * volMult
maxScore = volScore ? 8 : 7
 
inSess = not useSess or not na(time(timeframe.period, sess))
 
// Trend strength (ADX) — avoid sideways chop
[diPlus, diMinus, adxV] = ta.dmi(14, 14)
chopOk = not useChop or adxV >= adxMin
 
// ══════════════════════════════════════════════════════════════════════
// MARKET STRUCTURE
// ══════════════════════════════════════════════════════════════════════
ph = ta.pivothigh(high, swingLen, swingLen)
pl = ta.pivotlow(low, swingLen, swingLen)
 
var float swHigh       = na
var int   swHighBar    = na
var bool  swHighBroken = true
var float swLow        = na
var int   swLowBar     = na
var bool  swLowBroken  = true
 
// trailing extremes of the current leg (Fibonacci / premium-discount)
var float tHigh    = na
var int   tHighBar = na
var float tLow     = na
var int   tLowBar  = na
 
var int    trend     = 0          // 1 bullish · -1 bearish · 0 undefined
var string lastEvent = "—"
 
if not na(ph)
    float prevH = swHigh
    swHigh       := ph
    swHighBar    := bar_index - swingLen
    swHighBroken := false
    tHigh        := ph
    tHighBar     := swHighBar
    if showSwings
        string t = na(prevH) ? "H" : ph > prevH ? "HH" : "LH"
        label.new(swHighBar, ph, t, style=label.style_label_down, color=clear, textcolor=color.new(cBear, 30), size=size.tiny)
 
if not na(pl)
    float prevL = swLow
    swLow       := pl
    swLowBar    := bar_index - swingLen
    swLowBroken := false
    tLow        := pl
    tLowBar     := swLowBar
    if showSwings
        string t = na(prevL) ? "L" : pl < prevL ? "LL" : "HL"
        label.new(swLowBar, pl, t, style=label.style_label_up, color=clear, textcolor=color.new(cBull, 30), size=size.tiny)
 
if not na(tHigh) and high > tHigh
    tHigh    := high
    tHighBar := bar_index
if not na(tLow) and low < tLow
    tLow    := low
    tLowBar := bar_index
 
// ══════════════════════════════════════════════════════════════════════
// ORDER BLOCKS
// ══════════════════════════════════════════════════════════════════════
var array<box>   bullOB   = array.new<box>()
var array<float> bullTop  = array.new<float>()
var array<float> bullBot  = array.new<float>()
var array<bool>  bullUsed = array.new<bool>()
var array<box>   bearOB   = array.new<box>()
var array<float> bearTop  = array.new<float>()
var array<float> bearBot  = array.new<float>()
var array<bool>  bearUsed = array.new<bool>()
 
bool bullBOS   = false
bool bullCHoCH = false
bool bearBOS   = false
bool bearCHoCH = false
 
// ── Bullish break: close above swing high
if not swHighBroken and not na(swHigh) and close > swHigh
    swHighBroken := true
    bool choch = trend == -1
    bullCHoCH := choch
    bullBOS   := not choch
    trend     := 1
    lastEvent := choch ? "Bullish CHoCH" : "Bullish BOS"
    if showStruct
        line.new(swHighBar, swHigh, bar_index, swHigh, color=color.new(cBull, 20), style=choch ? line.style_dashed : line.style_dotted, width=1)
        label.new(math.round((swHighBar + bar_index) / 2), swHigh, choch ? "CHoCH" : "BOS", style=label.style_label_down, color=clear, textcolor=cBull, size=txtSz)
    int   len   = math.min(bar_index - swHighBar, 500)
    float obBot = na
    float obTop = na
    int   obBar = na
    float aBot  = na
    float aTop  = na
    int   aBar  = na
    for i = 1 to len
        if na(aBot) or low[i] < aBot
            aBot := low[i]
            aTop := high[i]
            aBar := bar_index - i
        if obOpp and close[i] < open[i] and (na(obBot) or low[i] < obBot)
            obBot := low[i]
            obTop := high[i]
            obBar := bar_index - i
    if na(obBot)
        obBot := aBot
        obTop := aTop
        obBar := aBar
    // accuracy: was the break impulsive (displacement) or did it leave a bullish FVG?
    bool disp = math.abs(close - open) >= atr * dispMult
    bool fvg  = false
    int  fl   = math.min(len, 50)
    for i = 0 to fl - 2
        if low[i] > high[i + 2]
            fvg := true
            break
    bool obValid = not needDisp or disp or fvg
    if not na(obBot) and obValid
        box b = box.new(obBar, obTop, bar_index + 5, obBot, border_color=showOB ? color.new(cBull, 55) : clear, border_width=1, bgcolor=showOB ? color.new(cBull, 85) : clear, text=showOB ? "Bullish OB" : "", text_size=size.tiny, text_color=color.new(cBull, 10), text_halign=text.align_right, text_valign=text.align_center)
        array.push(bullOB, b)
        array.push(bullTop, obTop)
        array.push(bullBot, obBot)
        array.push(bullUsed, false)
        if array.size(bullOB) > obMax
            box.delete(array.shift(bullOB))
            array.shift(bullTop)
            array.shift(bullBot)
            array.shift(bullUsed)
 
// ── Bearish break: close below swing low
if not swLowBroken and not na(swLow) and close < swLow
    swLowBroken := true
    bool choch = trend == 1
    bearCHoCH := choch
    bearBOS   := not choch
    trend     := -1
    lastEvent := choch ? "Bearish CHoCH" : "Bearish BOS"
    if showStruct
        line.new(swLowBar, swLow, bar_index, swLow, color=color.new(cBear, 20), style=choch ? line.style_dashed : line.style_dotted, width=1)
        label.new(math.round((swLowBar + bar_index) / 2), swLow, choch ? "CHoCH" : "BOS", style=label.style_label_up, color=clear, textcolor=cBear, size=txtSz)
    int   len   = math.min(bar_index - swLowBar, 500)
    float obBot = na
    float obTop = na
    int   obBar = na
    float aBot  = na
    float aTop  = na
    int   aBar  = na
    for i = 1 to len
        if na(aTop) or high[i] > aTop
            aTop := high[i]
            aBot := low[i]
            aBar := bar_index - i
        if obOpp and close[i] > open[i] and (na(obTop) or high[i] > obTop)
            obTop := high[i]
            obBot := low[i]
            obBar := bar_index - i
    if na(obTop)
        obBot := aBot
        obTop := aTop
        obBar := aBar
    // accuracy: was the break impulsive (displacement) or did it leave a bearish FVG?
    bool disp = math.abs(close - open) >= atr * dispMult
    bool fvg  = false
    int  fl   = math.min(len, 50)
    for i = 0 to fl - 2
        if high[i] < low[i + 2]
            fvg := true
            break
    bool obValid = not needDisp or disp or fvg
    if not na(obTop) and obValid
        box b = box.new(obBar, obTop, bar_index + 5, obBot, border_color=showOB ? color.new(cBear, 55) : clear, border_width=1, bgcolor=showOB ? color.new(cBear, 85) : clear, text=showOB ? "Bearish OB" : "", text_size=size.tiny, text_color=color.new(cBear, 10), text_halign=text.align_right, text_valign=text.align_center)
        array.push(bearOB, b)
        array.push(bearTop, obTop)
        array.push(bearBot, obBot)
        array.push(bearUsed, false)
        if array.size(bearOB) > obMax
            box.delete(array.shift(bearOB))
            array.shift(bearTop)
            array.shift(bearBot)
            array.shift(bearUsed)
 
// ── Mitigation + retest detection
bool  bullTouch    = false
float touchBullBot = na
int   touchBullIdx = -1
bool  bearTouch    = false
float touchBearTop = na
int   touchBearIdx = -1
 
if array.size(bullOB) > 0
    for i = array.size(bullOB) - 1 to 0
        float t   = array.get(bullTop, i)
        float bt  = array.get(bullBot, i)
        float src = obMitig == "Close" ? close : low
        box   bx  = array.get(bullOB, i)
        if src < bt
            if showMitig and showOB
                box.set_right(bx, bar_index)
                box.set_bgcolor(bx, color.new(cMuted, 90))
                box.set_border_color(bx, color.new(cMuted, 75))
                box.set_text(bx, "")
            else
                box.delete(bx)
            array.remove(bullOB, i)
            array.remove(bullTop, i)
            array.remove(bullBot, i)
            array.remove(bullUsed, i)
            if touchBullIdx > i
                touchBullIdx -= 1
        else
            box.set_right(bx, bar_index + 5)
            if low <= t and close > bt and not (obOnce and array.get(bullUsed, i))
                bullTouch    := true
                touchBullBot := bt
                touchBullIdx := i
 
if array.size(bearOB) > 0
    for i = array.size(bearOB) - 1 to 0
        float t   = array.get(bearTop, i)
        float bt  = array.get(bearBot, i)
        float src = obMitig == "Close" ? close : high
        box   bx  = array.get(bearOB, i)
        if src > t
            if showMitig and showOB
                box.set_right(bx, bar_index)
                box.set_bgcolor(bx, color.new(cMuted, 90))
                box.set_border_color(bx, color.new(cMuted, 75))
                box.set_text(bx, "")
            else
                box.delete(bx)
            array.remove(bearOB, i)
            array.remove(bearTop, i)
            array.remove(bearBot, i)
            array.remove(bearUsed, i)
            if touchBearIdx > i
                touchBearIdx -= 1
        else
            box.set_right(bx, bar_index + 5)
            if high >= bt and close < t and not (obOnce and array.get(bearUsed, i))
                bearTouch    := true
                touchBearTop := t
                touchBearIdx := i
 
// ══════════════════════════════════════════════════════════════════════
// FIBONACCI · PREMIUM / DISCOUNT
// ══════════════════════════════════════════════════════════════════════
bool  fibOk = not na(tHigh) and not na(tLow) and tHigh > tLow
bool  upLeg = fibOk and tLowBar < tHighBar
float eq    = fibOk ? (tHigh + tLow) / 2 : na
float gz1   = fibOk ? f_fib(0.618, tHigh, tLow, upLeg) : na
float gz2   = fibOk ? f_fib(0.786, tHigh, tLow, upLeg) : na
bool  inDiscount = fibOk and close < eq
bool  inPremium  = fibOk and close > eq
bool  inGZ       = fibOk and close >= math.min(gz1, gz2) and close <= math.max(gz1, gz2)
 
var array<float> fibAll   = array.from(0.0, 0.236, 0.382, 0.5, 0.618, 0.705, 0.786, 1.0)
var array<line>  fibLines  = array.new<line>()
var array<label> fibLabels = array.new<label>()
var line legLine = na
var box  gzBox   = na
 
if barstate.islast and showFib and fibOk
    while array.size(fibLines) > 0
        line.delete(array.pop(fibLines))
    while array.size(fibLabels) > 0
        label.delete(array.pop(fibLabels))
    line.delete(legLine)
    box.delete(gzBox)
    int x1 = math.min(tHighBar, tLowBar)
    int x2 = bar_index + fibExt
    legLine := line.new(tLowBar, tLow, tHighBar, tHigh, color=color.new(cMuted, 50), style=line.style_dotted)
    for r in fibAll
        if fibKey and not (r == 0.0 or r == 0.5 or r == 0.618 or r == 0.786 or r == 1.0)
            continue
        float p = f_fib(r, tHigh, tLow, upLeg)
        color c = r == 0.5 ? cAccent : (r == 0.618 or r == 0.705 or r == 0.786) ? cGold : cMuted
        string nm = r == 0.5 ? "EQ  0.5" : str.tostring(r)
        array.push(fibLines, line.new(x1, p, x2, p, color=color.new(c, r == 0.5 ? 20 : 45), style=r == 0.5 ? line.style_dashed : line.style_dotted, width=1))
        array.push(fibLabels, label.new(x2, p, nm + "   " + f_px(p), style=label.style_label_left, color=clear, textcolor=color.new(c, 10), size=size.tiny))
    if showGZ
        gzBox := box.new(x1, math.max(gz1, gz2), x2, math.min(gz1, gz2), border_color=color.new(cGold, 80), bgcolor=color.new(cGold, 92), text="GOLDEN ZONE", text_size=size.tiny, text_color=color.new(cGold, 30), text_halign=text.align_left, text_valign=text.align_center)
 
// ══════════════════════════════════════════════════════════════════════
// AUTO SUPPORT / RESISTANCE
// ══════════════════════════════════════════════════════════════════════
srPH = ta.pivothigh(high, srLen, srLen)
srPL = ta.pivotlow(low, srLen, srLen)
 
var array<float> srPiv    = array.new<float>()
var array<int>   srPivBar = array.new<int>()
if not na(srPH)
    array.push(srPiv, srPH)
    array.push(srPivBar, bar_index - srLen)
if not na(srPL)
    array.push(srPiv, srPL)
    array.push(srPivBar, bar_index - srLen)
while array.size(srPiv) > srLookback
    array.shift(srPiv)
    array.shift(srPivBar)
 
var array<box>   srBoxes  = array.new<box>()
var array<label> srLabels = array.new<label>()
float nearSup = na
float nearRes = na
 
if barstate.islast and showSR
    while array.size(srBoxes) > 0
        box.delete(array.pop(srBoxes))
    while array.size(srLabels) > 0
        label.delete(array.pop(srLabels))
    float tol = atr * srTol
    array<float> lvl   = array.new<float>()
    array<int>   cnt   = array.new<int>()
    array<int>   fromB = array.new<int>()
    int n = array.size(srPiv)
    if n > 0
        for i = n - 1 to 0
            float p  = array.get(srPiv, i)
            int   pb = array.get(srPivBar, i)
            int found = -1
            int m = array.size(lvl)
            if m > 0
                for j = 0 to m - 1
                    if math.abs(array.get(lvl, j) - p) <= tol
                        found := j
                        break
            if found >= 0
                int c = array.get(cnt, found)
                array.set(lvl, found, (array.get(lvl, found) * c + p) / (c + 1))
                array.set(cnt, found, c + 1)
                array.set(fromB, found, math.min(array.get(fromB, found), pb))
            else
                array.push(lvl, p)
                array.push(cnt, 1)
                array.push(fromB, pb)
    int drawn = 0
    int m2 = array.size(lvl)
    if m2 > 0
        for j = 0 to m2 - 1
            int c = array.get(cnt, j)
            if c >= srMinTouch
                float lv = array.get(lvl, j)
                bool isRes = lv > close
                if isRes and (na(nearRes) or lv < nearRes)
                    nearRes := lv
                if not isRes and (na(nearSup) or lv > nearSup)
                    nearSup := lv
                if drawn < srMaxLines
                    color col = isRes ? cBear : cBull
                    array.push(srBoxes, box.new(array.get(fromB, j), lv + tol / 2, bar_index + fibExt, lv - tol / 2, border_color=color.new(col, 75), bgcolor=color.new(col, 92)))
                    array.push(srLabels, label.new(bar_index + 3, lv, (isRes ? "RES  " : "SUP  ") + f_px(lv) + "  ·  " + str.tostring(c) + "×", style=label.style_label_left, color=clear, textcolor=color.new(col, 15), size=size.tiny))
                    drawn += 1
 
// ══════════════════════════════════════════════════════════════════════
// AUTO TRENDLINES
// ══════════════════════════════════════════════════════════════════════
tlPH = ta.pivothigh(high, tlLen, tlLen)
tlPL = ta.pivotlow(low, tlLen, tlLen)
 
var float tlH1  = na
var int   tlH1b = na
var float tlH2  = na
var int   tlH2b = na
var float tlL1  = na
var int   tlL1b = na
var float tlL2  = na
var int   tlL2b = na
var line  dnTL  = na
var line  upTL  = na
var bool  dnActive = false
var bool  upActive = false
var float dnSlope  = na
var float upSlope  = na
 
if not na(tlPH)
    tlH1  := tlH2
    tlH1b := tlH2b
    tlH2  := tlPH
    tlH2b := bar_index - tlLen
    if not na(tlH1) and tlH2 < tlH1
        if not na(dnTL) and (dnActive or not tlKeep)
            line.delete(dnTL)
        dnSlope  := (tlH2 - tlH1) / (tlH2b - tlH1b)
        dnActive := true
        if showTL
            dnTL := line.new(tlH1b, tlH1, tlH2b, tlH2, extend=extend.right, color=dnTLCol, width=2)
 
if not na(tlPL)
    tlL1  := tlL2
    tlL1b := tlL2b
    tlL2  := tlPL
    tlL2b := bar_index - tlLen
    if not na(tlL1) and tlL2 > tlL1
        if not na(upTL) and (upActive or not tlKeep)
            line.delete(upTL)
        upSlope  := (tlL2 - tlL1) / (tlL2b - tlL1b)
        upActive := true
        if showTL
            upTL := line.new(tlL1b, tlL1, tlL2b, tlL2, extend=extend.right, color=upTLCol, width=2)
 
float dnVal = dnActive ? tlH2 + dnSlope * (bar_index - tlH2b) : na
float upVal = upActive ? tlL2 + upSlope * (bar_index - tlL2b) : na
bool tlBreakUp = dnActive and barstate.isconfirmed and close > dnVal
bool tlBreakDn = upActive and barstate.isconfirmed and close < upVal
 
if tlBreakUp
    dnActive := false
    if not na(dnTL)
        line.set_extend(dnTL, extend.none)
        line.set_xy2(dnTL, bar_index, dnVal)
        line.set_style(dnTL, line.style_dotted)
        line.set_color(dnTL, color.new(dnTLCol, 50))
        line.set_width(dnTL, 1)
if tlBreakDn
    upActive := false
    if not na(upTL)
        line.set_extend(upTL, extend.none)
        line.set_xy2(upTL, bar_index, upVal)
        line.set_style(upTL, line.style_dotted)
        line.set_color(upTL, color.new(upTLCol, 50))
        line.set_width(upTL, 1)
 
plotshape(showTL and tlSig and tlBreakUp, "Trendline breakout ↑", shape.triangleup, location.belowbar, color.new(upTLCol, 0), size=size.tiny)
plotshape(showTL and tlSig and tlBreakDn, "Trendline breakout ↓", shape.triangledown, location.abovebar, color.new(dnTLCol, 0), size=size.tiny)
 
bsTLUp = ta.barssince(tlBreakUp)
bsTLDn = ta.barssince(tlBreakDn)
 
// ══════════════════════════════════════════════════════════════════════
// SIGNAL ENGINE
// ══════════════════════════════════════════════════════════════════════
var int lastSigBar = na
bool canSig = na(lastSigBar) or bar_index - lastSigBar > cooldown
float cTol = atr * srTol
 
// base setup: with-trend OB retest + confirmation candle
// accuracy: confirmation candle must close in the upper (BUY) / lower (SELL) half of its range
float rngC = high - low
bool  rejB = close > open and rngC > 0 and (close - low) >= rngC * 0.5
bool  rejS = close < open and rngC > 0 and (high - close) >= rngC * 0.5
bool baseBuy  = barstate.isconfirmed and canSig and trend == 1 and bullTouch and rejB
bool baseSell = barstate.isconfirmed and canSig and trend == -1 and bearTouch and rejS
 
// S/R + trendline confluence (computed only on setup bars)
bool bAtSR = false
bool bTL   = false
bool sAtSR = false
bool sTL   = false
if baseBuy
    bAtSR := f_touches(srPiv, low, cTol) >= srMinTouch
    bTL   := (upActive and math.abs(low - upVal) <= cTol) or bsTLUp <= 10
if baseSell
    sAtSR := f_touches(srPiv, high, cTol) >= srMinTouch
    sTL   := (dnActive and math.abs(high - dnVal) <= cTol) or bsTLDn <= 10
 
// confluence score (0-8, or 0-7 without volume)
bool bCandle = close > high[1]
bool sCandle = close < low[1]
bool bEma    = close > ema32 and ema32Up
bool sEma    = close < ema32 and not ema32Up
bool vPoint  = volScore and volOk
int buyScore  = baseBuy  ? (inDiscount ? 1 : 0) + (inGZ ? 1 : 0) + (bAtSR ? 1 : 0) + (bTL ? 1 : 0) + (bEma ? 1 : 0) + (htfBull ? 1 : 0) + (bCandle ? 1 : 0) + (vPoint ? 1 : 0) : 0
int sellScore = baseSell ? (inPremium ? 1 : 0) + (inGZ ? 1 : 0) + (sAtSR ? 1 : 0) + (sTL ? 1 : 0) + (sEma ? 1 : 0) + (htfBear ? 1 : 0) + (sCandle ? 1 : 0) + (vPoint ? 1 : 0) : 0
int strongNeed = volScore ? strongScore : strongScore - 1
 
// hard filters
bool buyFilt  = inSess and chopOk and (not needPD or inDiscount) and (not needGZ or inGZ) and (not useEma or close > ema) and (not needSRTL or bAtSR or bTL) and (not useHTF or htfBull)
bool sellFilt = inSess and chopOk and (not needPD or inPremium) and (not needGZ or inGZ) and (not useEma or close < ema) and (not needSRTL or sAtSR or sTL) and (not useHTF or htfBear)
 
bool buySig  = baseBuy and buyFilt and buyScore >= minScore and (not onlyStrong or buyScore >= strongNeed)
bool sellSig = baseSell and sellFilt and sellScore >= minScore and (not onlyStrong or sellScore >= strongNeed)
 
// ★ highly recommended = high score + on S/R or trendline + with EMA 32
bool strongBuy  = buySig and buyScore >= strongNeed and (bAtSR or bTL) and bEma
bool strongSell = sellSig and sellScore >= strongNeed and (sAtSR or sTL) and sEma
 
// ══════════════════════════════════════════════════════════════════════
// AUTO LONG / SHORT POSITION ENGINE
//  Every signal opens a TradingView-style position (risk box + reward box)
//  that extends bar by bar until TP, SL or time-out, then shows the result.
// ══════════════════════════════════════════════════════════════════════
type Pos
    int   dir
    float entry
    float sl
    float tp
    int   start
    int   kind      // 0 = normal · 1 = ★ highly recommended · 2 = short-term
    box   rBox
    box   wBox
    label tag
 
var array<Pos> posList     = array.new<Pos>()
var array<Pos> lastDrawn   = array.new<Pos>()
var array<Pos> lastDrawnST = array.new<Pos>()
var int   winsAll = 0
var int   lossAll = 0
var int   winsS   = 0
var int   lossS   = 0
var int   stW     = 0
var int   stL     = 0
var float netR    = 0.0
var float netRst  = 0.0
 
f_name(k, d) => (k == 1 ? "★ " : k == 2 ? "ST " : "") + (d == 1 ? "LONG" : "SHORT")
 
// open + draw a position
f_open(list, recent, d, e, s, t, k, drawIt, latestOnly, maxOpen, tip) =>
    box   rb = na
    box   wb = na
    label tg = na
    if drawIt
        if latestOnly and array.size(recent) > 0
            Pos old = array.pop(recent)
            box.delete(old.rBox)
            box.delete(old.wBox)
            label.delete(old.tag)
        int   tr   = k == 2 ? 88 : 80
        float rMul = math.abs(t - e) / math.max(math.abs(e - s), syminfo.mintick)
        rb := box.new(bar_index, math.max(e, s), bar_index + 1, math.min(e, s), border_color=color.new(cBear, 55), bgcolor=color.new(cBear, tr), text="SL  " + f_px(s) + "   −1R", text_size=size.tiny, text_color=cBear, text_halign=text.align_left, text_valign=text.align_center)
        wb := box.new(bar_index, math.max(e, t), bar_index + 1, math.min(e, t), border_color=color.new(cBull, 55), bgcolor=color.new(cBull, tr), text="TP  " + f_px(t) + "   +" + str.tostring(rMul, "#.0") + "R", text_size=size.tiny, text_color=cBull, text_halign=text.align_left, text_valign=text.align_center)
        tg := label.new(bar_index, e, f_name(k, d) + "  " + f_px(e), style=label.style_label_right, color=color.new(d == 1 ? cBull : cBear, k == 2 ? 40 : 5), textcolor=color.white, size=size.tiny, tooltip=tip)
    Pos p = Pos.new(d, e, s, t, bar_index, k, rb, wb, tg)
    array.push(list, p)
    if drawIt
        array.push(recent, p)
        if array.size(recent) > 1
            array.shift(recent)
    if array.size(list) > maxOpen
        array.shift(list)
    true
 
// update open positions: extend, or close on TP / SL / time-out
if array.size(posList) > 0
    for i = array.size(posList) - 1 to 0
        Pos p = array.get(posList, i)
        if bar_index > p.start
            float risk0 = math.max(math.abs(p.entry - p.sl), syminfo.mintick)
            bool  hitSL = p.dir == 1 ? low <= p.sl : high >= p.sl
            bool  hitTP = p.dir == 1 ? high >= p.tp : low <= p.tp
            bool  tout  = bar_index - p.start >= posMaxBars
            if hitSL or hitTP or tout
                float res = hitSL ? -1.0 : hitTP ? math.abs(p.tp - p.entry) / risk0 : (close - p.entry) * p.dir / risk0
                bool  win = res > 0
                if p.kind == 2
                    stW    += win ? 1 : 0
                    stL    += win ? 0 : 1
                    netRst += res
                else
                    winsAll += win ? 1 : 0
                    lossAll += win ? 0 : 1
                    netR    += res
                    if p.kind == 1
                        winsS += win ? 1 : 0
                        lossS += win ? 0 : 1
                if not na(p.rBox)
                    box.set_right(p.rBox, bar_index)
                    box.set_right(p.wBox, bar_index)
                    if hitSL
                        box.set_bgcolor(p.wBox, color.new(cMuted, 92))
                        box.set_border_color(p.wBox, color.new(cMuted, 80))
                        box.set_text_color(p.wBox, cMuted)
                    if hitTP
                        box.set_bgcolor(p.rBox, color.new(cMuted, 92))
                        box.set_border_color(p.rBox, color.new(cMuted, 80))
                        box.set_text_color(p.rBox, cMuted)
                if not na(p.tag)
                    string rs = (res >= 0 ? "+" : "") + str.tostring(res, "#.0") + "R"
                    label.set_text(p.tag, f_name(p.kind, p.dir) + "   " + (hitSL ? "✗ SL" : hitTP ? "✓ TP" : "⏱ EXIT") + "  " + rs)
                    label.set_color(p.tag, hitSL ? color.new(cMuted, 15) : hitTP ? color.new(cBull, 5) : color.new(cAccent, 15))
                array.remove(posList, i)
            else if not na(p.rBox)
                box.set_right(p.rBox, bar_index + 1)
                box.set_right(p.wBox, bar_index + 1)
 
// ── state of the latest signal
var string lastSigTxt = "—"
var int    lastDir    = 0
var bool   lastStrong = false
var float  lastEntry  = na
var float  lastSL     = na
var float  lastTP     = na
var float  lastTP2    = na
var int    lastScore  = 0
 
if buySig or sellSig
    lastSigBar := bar_index
    if buySig and touchBullIdx >= 0
        array.set(bullUsed, touchBullIdx, true)
    if sellSig and touchBearIdx >= 0
        array.set(bearUsed, touchBearIdx, true)
    lastDir    := buySig ? 1 : -1
    lastStrong := strongBuy or strongSell
    lastEntry  := close
    lastSL     := buySig ? touchBullBot - atr * slBufAtr : touchBearTop + atr * slBufAtr
    float minRisk = atr * minSlAtr
    if math.abs(lastEntry - lastSL) < minRisk
        lastSL := buySig ? lastEntry - minRisk : lastEntry + minRisk
    float risk = math.abs(lastEntry - lastSL)
    lastTP     := buySig ? lastEntry + risk * rr : lastEntry - risk * rr
    lastScore  := buySig ? buyScore : sellScore
    float nxt  = f_nextLevel(srPiv, lastEntry, cTol, srMinTouch, buySig)
    lastTP2    := not na(nxt) and math.abs(nxt - lastEntry) > risk ? nxt : na
    lastSigTxt := (lastStrong ? "★ " : "") + (buySig ? "LONG" : "SHORT") + "  @ " + f_px(lastEntry)
    string why = buySig ? f_why(true, inDiscount, inGZ, bAtSR, bTL, bEma, htfBull, bCandle, vPoint, volScore) : f_why(false, inPremium, inGZ, sAtSR, sTL, sEma, htfBear, sCandle, vPoint, volScore)
    string tip = why + "\n\nScore " + str.tostring(lastScore) + "/" + str.tostring(maxScore) + "\nEntry " + f_px(lastEntry) + "\nSL " + f_px(lastSL) + "\nTP1 " + f_px(lastTP) + (na(lastTP2) ? "" : "\nTP2 (S/R) " + f_px(lastTP2))
    bool drawIt = showSig and (posMode == "All signals" or posMode == "Latest only" or (posMode == "★ only" and lastStrong))
    f_open(posList, lastDrawn, lastDir, lastEntry, lastSL, lastTP, lastStrong ? 1 : 0, drawIt, posMode == "Latest only", posMaxOpen, tip)
 
plotshape(showSig and buySig and not strongBuy, "LONG", shape.labelup, location.belowbar, color.new(cBull, 15), text="LONG", textcolor=color.white, size=size.tiny)
plotshape(showSig and sellSig and not strongSell, "SHORT", shape.labeldown, location.abovebar, color.new(cBear, 15), text="SHORT", textcolor=color.white, size=size.tiny)
plotshape(showSig and strongBuy, "★ LONG", shape.labelup, location.belowbar, cBull, text="★ LONG", textcolor=color.white, size=size.small)
plotshape(showSig and strongSell, "★ SHORT", shape.labeldown, location.abovebar, cBear, text="★ SHORT", textcolor=color.white, size=size.small)
bgcolor(showSig and strongBg and strongBuy ? color.new(cBull, 90) : showSig and strongBg and strongSell ? color.new(cBear, 90) : na, title="★ signal highlight")
barcolor(trendBars ? (trend == 1 ? cBull : trend == -1 ? cBear : cMuted) : na, title="Trend candles")
 
// ══════════════════════════════════════════════════════════════════════
// SHORT-TERM (SCALP) SIGNALS
//  BUY : fast EMA > slow EMA (cross or pullback bounce) · above EMA 32 ·
//        above VWAP · RSI 50-70 · strong close · ADX trending · volume ok
//  SELL: mirrored. Stop = recent swing (capped), target = stRR × risk.
// ══════════════════════════════════════════════════════════════════════
emaF  = ta.ema(close, stFast)
emaS  = ta.ema(close, stSlow)
rsiV  = ta.rsi(close, stRsiLen)
vwapV = ta.vwap(hlc3)
lowN  = ta.lowest(low, stSwingLb)
highN = ta.highest(high, stSwingLb)
crUp  = ta.crossover(emaF, emaS)
crDn  = ta.crossunder(emaF, emaS)
plot(showST and stShowEma ? emaF : na, "ST fast EMA", color=color.new(cAccent, 30), linewidth=1)
plot(showST and stShowEma ? emaS : na, "ST slow EMA", color=color.new(cGold, 30), linewidth=1)
plot(showST and stShowVwap and hasVol ? vwapV : na, "VWAP", color=color.new(#E040FB, 20), linewidth=1)
 
bool vwBull  = not stUseVwap or not hasVol or close > vwapV
bool vwBear  = not stUseVwap or not hasVol or close < vwapV
bool stTrigB = crUp or (emaF > emaS and low <= emaF and close > emaF)
bool stTrigS = crDn or (emaF < emaS and high >= emaF and close < emaF)
bool stVolOk = not volScore or volOk
 
var int stLastBar = na
bool stCan = na(stLastBar) or bar_index - stLastBar > stCooldown
 
bool stBuy  = showST and barstate.isconfirmed and stCan and inSess and chopOk and stTrigB and rejB and close > ema32 and rsiV > 50 and rsiV < stRsiMax and vwBull and stVolOk and (not stNeedStruct or trend != -1) and not buySig
bool stSell = showST and barstate.isconfirmed and stCan and inSess and chopOk and stTrigS and rejS and close < ema32 and rsiV < 50 and rsiV > 100 - stRsiMax and vwBear and stVolOk and (not stNeedStruct or trend != 1) and not sellSig
 
var int   stDir   = 0
var float stEntry = na
var float stSL    = na
var float stTP    = na
 
if stBuy or stSell
    stLastBar := bar_index
    stDir     := stBuy ? 1 : -1
    stEntry   := close
    float rawSL = stBuy ? lowN - atr * 0.1 : highN + atr * 0.1
    float rk    = math.max(atr * math.max(minSlAtr, 0.3), math.min(math.abs(stEntry - rawSL), atr * stMaxSlAtr))
    stSL   := stBuy ? stEntry - rk : stEntry + rk
    stTP   := stBuy ? stEntry + rk * stRR : stEntry - rk * stRR
    string stTip = "SHORT-TERM " + (stBuy ? "LONG" : "SHORT") + "\nEntry " + f_px(stEntry) + "\nSL " + f_px(stSL) + "\nTP " + f_px(stTP) + "  (" + str.tostring(stRR, "#.0#") + "R)\nRSI " + str.tostring(rsiV, "#") + " · ADX " + str.tostring(adxV, "#")
    bool stDraw = stPos and posMode != "Off" and posMode != "★ only"
    f_open(posList, lastDrawnST, stDir, stEntry, stSL, stTP, 2, stDraw, posMode == "Latest only", posMaxOpen, stTip)
 
plotshape(stBuy, "Short-term LONG", shape.labelup, location.belowbar, color.new(cAccent, 25), text="ST LONG", textcolor=color.white, size=size.tiny)
plotshape(stSell, "Short-term SHORT", shape.labeldown, location.abovebar, color.new(#FF6D00, 25), text="ST SHORT", textcolor=color.white, size=size.tiny)
 
// ══════════════════════════════════════════════════════════════════════
// TRADE PLANNER — where to BUY / SELL next
// ══════════════════════════════════════════════════════════════════════
float planBuyTop  = na
float planBuyBot  = na
float planSellTop = na
float planSellBot = na
int   planBuyQ    = 0
int   planSellQ   = 0
var label planBuyLab  = na
var label planSellLab = na
 
if barstate.islast
    int nb = array.size(bullOB)
    if nb > 0
        for i = 0 to nb - 1
            float t = array.get(bullTop, i)
            if t < close and (na(planBuyTop) or t > planBuyTop)
                planBuyTop := t
                planBuyBot := array.get(bullBot, i)
    int ns = array.size(bearOB)
    if ns > 0
        for i = 0 to ns - 1
            float bt = array.get(bearBot, i)
            if bt > close and (na(planSellBot) or bt < planSellBot)
                planSellBot := bt
                planSellTop := array.get(bearTop, i)
    if not na(planBuyTop)
        planBuyQ := (trend == 1 ? 1 : 0) + (fibOk and planBuyTop < eq ? 1 : 0) + (fibOk and planBuyBot <= math.max(gz1, gz2) and planBuyTop >= math.min(gz1, gz2) ? 1 : 0) + (f_touches(srPiv, planBuyBot, cTol) >= srMinTouch or f_touches(srPiv, planBuyTop, cTol) >= srMinTouch ? 1 : 0) + (upActive and upVal >= planBuyBot - cTol and upVal <= planBuyTop + cTol ? 1 : 0)
    if not na(planSellBot)
        planSellQ := (trend == -1 ? 1 : 0) + (fibOk and planSellBot > eq ? 1 : 0) + (fibOk and planSellBot <= math.max(gz1, gz2) and planSellTop >= math.min(gz1, gz2) ? 1 : 0) + (f_touches(srPiv, planSellBot, cTol) >= srMinTouch or f_touches(srPiv, planSellTop, cTol) >= srMinTouch ? 1 : 0) + (dnActive and dnVal >= planSellBot - cTol and dnVal <= planSellTop + cTol ? 1 : 0)
    label.delete(planBuyLab)
    label.delete(planSellLab)
    if showSig and not na(planBuyTop)
        planBuyLab := label.new(bar_index + 3, planBuyTop, "BUY ZONE  " + f_stars(planBuyQ, 5) + "\n" + f_px(planBuyBot) + " – " + f_px(planBuyTop), style=label.style_label_upper_left, color=color.new(cBull, trend == 1 ? 15 : 65), textcolor=color.white, size=size.tiny, tooltip="Limit: " + f_px(planBuyTop) + "\nSL: " + f_px(planBuyBot - atr * slBufAtr))
    if showSig and not na(planSellBot)
        planSellLab := label.new(bar_index + 3, planSellBot, "SELL ZONE  " + f_stars(planSellQ, 5) + "\n" + f_px(planSellBot) + " – " + f_px(planSellTop), style=label.style_label_lower_left, color=color.new(cBear, trend == -1 ? 15 : 65), textcolor=color.white, size=size.tiny, tooltip="Limit: " + f_px(planSellBot) + "\nSL: " + f_px(planSellTop + atr * slBufAtr))
 
// ══════════════════════════════════════════════════════════════════════
// SUGGESTION ENGINE
// ══════════════════════════════════════════════════════════════════════
string sugg    = "WAIT — market structure not defined yet"
color  suggCol = cMuted
if trend == 1
    suggCol := cBull
    if inPremium
        sugg    := "Bullish, but price is in PREMIUM — don't chase; wait for a pullback into a bullish OB"
        suggCol := cWarn
    else if inGZ
        sugg := "Bullish + Golden Zone — watch the bullish OB for a BUY confirmation candle"
    else
        sugg := "Bullish + Discount — look for a BUY on the bullish OB retest"
else if trend == -1
    suggCol := cBear
    if inDiscount
        sugg    := "Bearish, but price is in DISCOUNT — don't chase; wait for a rally into a bearish OB"
        suggCol := cWarn
    else if inGZ
        sugg := "Bearish + Golden Zone — watch the bearish OB for a SELL confirmation candle"
    else
        sugg := "Bearish + Premium — look for a SELL on the bearish OB retest"
if trend == 1 and bsTLUp <= 5
    sugg    := "Falling trendline broken with bullish structure — BUY bias, wait for OB retest"
    suggCol := cBull
if trend == -1 and bsTLDn <= 5
    sugg    := "Rising trendline broken with bearish structure — SELL bias, wait for OB retest"
    suggCol := cBear
if trend == 1 and not na(nearRes) and nearRes - close < atr
    sugg    := "Bullish, but just below RESISTANCE " + f_px(nearRes) + " — book profit or wait for breakout + retest"
    suggCol := cWarn
if trend == -1 and not na(nearSup) and close - nearSup < atr
    sugg    := "Bearish, but just above SUPPORT " + f_px(nearSup) + " — book profit or wait for breakdown + retest"
    suggCol := cWarn
if not chopOk and trend != 0
    sugg    := "Market is CHOPPY (ADX " + str.tostring(adxV, "#") + ") — stay out or reduce size"
    suggCol := cWarn
if stBuy
    sugg    := "Short-term LONG opened — TP " + f_px(stTP) + " · SL " + f_px(stSL)
    suggCol := cAccent
if stSell
    sugg    := "Short-term SHORT opened — TP " + f_px(stTP) + " · SL " + f_px(stSL)
    suggCol := #FF6D00
if buySig
    sugg    := "LONG opened — follow the position box on chart (Entry / SL / TP)"
    suggCol := cBull
if sellSig
    sugg    := "SHORT opened — follow the position box on chart (Entry / SL / TP)"
    suggCol := cBear
if strongBuy
    sugg    := "★ HIGHLY RECOMMENDED LONG — score " + str.tostring(buyScore) + "/" + str.tostring(maxScore)
    suggCol := cBull
if strongSell
    sugg    := "★ HIGHLY RECOMMENDED SHORT — score " + str.tostring(sellScore) + "/" + str.tostring(maxScore)
    suggCol := cBear
 
// ══════════════════════════════════════════════════════════════════════
// DASHBOARD
// ══════════════════════════════════════════════════════════════════════
tPos = dashPos == "Top Right" ? position.top_right : dashPos == "Top Left" ? position.top_left : dashPos == "Bottom Right" ? position.bottom_right : position.bottom_left
var table dash = table.new(tPos, 2, 40, bgcolor=cPanel, frame_color=cBorder, frame_width=1, border_color=cBorder, border_width=1)
 
if showDash and barstate.islast
    table.clear(dash, 0, 0, 1, 39)
    bool full = dashLayout == "Full"
 
    // values
    string trendTxt = trend == 1 ? "▲  BULLISH" : trend == -1 ? "▼  BEARISH" : "—  NEUTRAL"
    color  trendCol = trend == 1 ? cBull : trend == -1 ? cBear : cMuted
    string zoneTxt  = not fibOk ? "—" : (inPremium ? "PREMIUM" : "DISCOUNT") + (inGZ ? "  ·  GOLDEN" : "")
    color  zoneCol  = not fibOk ? cMuted : inPremium ? cBear : cBull
    string htfTxt   = htfBull ? "▲  BULLISH" : htfBear ? "▼  BEARISH" : "—"
    color  htfCol   = htfBull ? cBull : htfBear ? cBear : cMuted
    string emaTxt   = (close > ema32 ? "ABOVE" : "BELOW") + "  ·  " + (ema32Up ? "RISING" : "FALLING")
    color  emaCol   = close > ema32 and ema32Up ? cBull : close < ema32 and not ema32Up ? cBear : cWarn
    string upTxt    = upActive ? "active" : na(upSlope) ? "none" : "broken"
    string dnTxt    = dnActive ? "active" : na(dnSlope) ? "none" : "broken"
    color  sigCol   = lastDir == 1 ? cBull : lastDir == -1 ? cBear : cMuted
    string scoreTxt = lastDir == 0 ? "—" : f_bar(lastScore, maxScore) + "  " + str.tostring(lastScore) + "/" + str.tostring(maxScore)
    string buyZTxt  = na(planBuyTop) ? "—" : f_px(planBuyBot) + " – " + f_px(planBuyTop) + "   " + f_stars(planBuyQ, 5)
    string sellZTxt = na(planSellBot) ? "—" : f_px(planSellBot) + " – " + f_px(planSellTop) + "   " + f_stars(planSellQ, 5)
    string planTxt  = "Wait for BOS / CHoCH"
    color  planCol  = cMuted
    if trend == 1 and not na(planBuyTop)
        planTxt := "BUY LMT " + f_px(planBuyTop) + "  ·  SL " + f_px(planBuyBot - atr * slBufAtr) + "  ·  TP " + (na(nearRes) ? str.tostring(rr) + "R" : f_px(nearRes))
        planCol := cBull
    else if trend == -1 and not na(planSellBot)
        planTxt := "SELL LMT " + f_px(planSellBot) + "  ·  SL " + f_px(planSellTop + atr * slBufAtr) + "  ·  TP " + (na(nearSup) ? str.tostring(rr) + "R" : f_px(nearSup))
        planCol := cBear
 
    // header
    int r = 0
    table.cell(dash, 0, r, "SMC PRO", text_color=color.white, bgcolor=cAccent, text_size=dashSz, text_halign=text.align_left)
    table.cell(dash, 1, r, syminfo.ticker + "  ·  " + timeframe.period, text_color=color.white, bgcolor=cAccent, text_size=dashSz, text_halign=text.align_right)
    r += 1
 
    r := f_head(dash, r, "MARKET", cHead, cMuted, dashSz)
    r := f_row(dash, r, "Trend", trendTxt, trendCol, cPanel, cMuted, dashSz)
    if full
        r := f_row(dash, r, "Structure", lastEvent, cText, cPanel, cMuted, dashSz)
        r := f_row(dash, r, "HTF (" + htfTf + ")", htfTxt, htfCol, cPanel, cMuted, dashSz)
        r := f_row(dash, r, "EMA " + str.tostring(ema32Len), emaTxt, emaCol, cPanel, cMuted, dashSz)
    r := f_row(dash, r, "Price zone", zoneTxt, zoneCol, cPanel, cMuted, dashSz)
    if full
        r := f_row(dash, r, "ADX", str.tostring(adxV, "#") + (adxV >= adxMin ? "  ·  TRENDING" : "  ·  CHOPPY"), adxV >= adxMin ? cText : cWarn, cPanel, cMuted, dashSz)
 
    if full
        r := f_head(dash, r, "LEVELS", cHead, cMuted, dashSz)
        r := f_row(dash, r, "Resistance", na(nearRes) ? "—" : f_px(nearRes), cBear, cPanel, cMuted, dashSz)
        r := f_row(dash, r, "Support", na(nearSup) ? "—" : f_px(nearSup), cBull, cPanel, cMuted, dashSz)
        r := f_row(dash, r, "Trendlines", "↗ " + upTxt + "   ↘ " + dnTxt, cText, cPanel, cMuted, dashSz)
        r := f_row(dash, r, "Active OBs", str.tostring(array.size(bullOB)) + " bull  ·  " + str.tostring(array.size(bearOB)) + " bear", cText, cPanel, cMuted, dashSz)
 
    r := f_head(dash, r, "LAST SIGNAL", cHead, cMuted, dashSz)
    r := f_row(dash, r, lastStrong ? "Signal ★" : "Signal", lastSigTxt, sigCol, cPanel, cMuted, dashSz)
    r := f_row(dash, r, "Score", scoreTxt, sigCol, cPanel, cMuted, dashSz)
    if full and not na(lastEntry)
        r := f_row(dash, r, "Stop loss", f_px(lastSL), cBear, cPanel, cMuted, dashSz)
        r := f_row(dash, r, "Target 1", f_px(lastTP) + "  (" + str.tostring(rr, "#.0") + "R)", cBull, cPanel, cMuted, dashSz)
        if not na(lastTP2)
            r := f_row(dash, r, "Target 2", f_px(lastTP2) + "  (S/R)", cBull, cPanel, cMuted, dashSz)
 
    if showST
        string stBias  = emaF > emaS and vwBull and close > ema32 ? "▲  BULLISH" : emaF < emaS and vwBear and close < ema32 ? "▼  BEARISH" : "—  MIXED"
        color  stBiasC = str.contains(stBias, "BULL") ? cBull : str.contains(stBias, "BEAR") ? cBear : cMuted
        color  stCol   = stDir == 1 ? cAccent : stDir == -1 ? #FF6D00 : cMuted
        r := f_head(dash, r, "SHORT-TERM", cHead, cMuted, dashSz)
        r := f_row(dash, r, "Bias  ·  RSI " + str.tostring(rsiV, "#"), stBias, stBiasC, cPanel, cMuted, dashSz)
        r := f_row(dash, r, "Last", stDir == 0 ? "—" : (stDir == 1 ? "LONG" : "SHORT") + "  @ " + f_px(stEntry), stCol, cPanel, cMuted, dashSz)
        if full and stDir != 0
            r := f_row(dash, r, "SL  ·  TP", f_px(stSL) + "  ·  " + f_px(stTP), cText, cPanel, cMuted, dashSz)
 
    r := f_head(dash, r, "TRADE PLAN", cHead, cMuted, dashSz)
    if full
        r := f_row(dash, r, "Buy zone", buyZTxt, cBull, cPanel, cMuted, dashSz)
        r := f_row(dash, r, "Sell zone", sellZTxt, cBear, cPanel, cMuted, dashSz)
    r := f_row(dash, r, "Best plan", planTxt, planCol, cPanel, cMuted, dashSz)
 
    int nOpen = array.size(posList)
    r := f_head(dash, r, "POSITIONS  ·  TP vs SL", cHead, cMuted, dashSz)
    r := f_row(dash, r, "Open now", nOpen == 0 ? "none" : str.tostring(nOpen) + " running", nOpen == 0 ? cMuted : cAccent, cPanel, cMuted, dashSz)
    r := f_row(dash, r, "LONG/SHORT win", f_wr(winsAll, lossAll), cText, cPanel, cMuted, dashSz)
    r := f_row(dash, r, "★ win", f_wr(winsS, lossS), cGold, cPanel, cMuted, dashSz)
    if full
        r := f_row(dash, r, "Net result", (netR >= 0 ? "+" : "") + str.tostring(netR, "#.0") + " R", netR >= 0 ? cBull : cBear, cPanel, cMuted, dashSz)
    if showST
        r := f_row(dash, r, "Short-term win", f_wr(stW, stL), cAccent, cPanel, cMuted, dashSz)
        if full
            r := f_row(dash, r, "Short-term net", (netRst >= 0 ? "+" : "") + str.tostring(netRst, "#.0") + " R", netRst >= 0 ? cBull : cBear, cPanel, cMuted, dashSz)
 
    // suggestion banner
    table.cell(dash, 0, r, f_wrap(sugg, 38), text_color=suggCol, bgcolor=color.new(suggCol, 85), text_size=dashSz, text_halign=text.align_center)
    table.cell(dash, 1, r, "", bgcolor=color.new(suggCol, 85))
    table.merge_cells(dash, 0, r, 1, r)
    r += 1
    table.cell(dash, 0, r, "Educational tool · not financial advice", text_color=cMuted, bgcolor=cPanel, text_size=size.tiny, text_halign=text.align_center)
    table.cell(dash, 1, r, "", bgcolor=cPanel)
    table.merge_cells(dash, 0, r, 1, r)
 
// ══════════════════════════════════════════════════════════════════════
// ALERTS
// ══════════════════════════════════════════════════════════════════════
alertcondition(strongBuy,  "★ Highly recommended LONG",  "★ STRONG LONG · {{ticker}} {{interval}} · {{close}}")
alertcondition(strongSell, "★ Highly recommended SHORT", "★ STRONG SHORT · {{ticker}} {{interval}} · {{close}}")
alertcondition(buySig,     "LONG signal",                "LONG · {{ticker}} {{interval}} · {{close}}")
alertcondition(sellSig,    "SHORT signal",               "SHORT · {{ticker}} {{interval}} · {{close}}")
alertcondition(stBuy,      "Short-term LONG",            "Short-term LONG · {{ticker}} {{interval}} · {{close}}")
alertcondition(stSell,     "Short-term SHORT",           "Short-term SHORT · {{ticker}} {{interval}} · {{close}}")
alertcondition(bullCHoCH,  "Bullish CHoCH",             "Bullish CHoCH · {{ticker}} {{interval}}")
alertcondition(bearCHoCH,  "Bearish CHoCH",             "Bearish CHoCH · {{ticker}} {{interval}}")
alertcondition(bullBOS,    "Bullish BOS",               "Bullish BOS · {{ticker}} {{interval}}")
alertcondition(bearBOS,    "Bearish BOS",               "Bearish BOS · {{ticker}} {{interval}}")
alertcondition(tlBreakUp,  "Trendline breakout ↑",      "Falling trendline broken UP · {{ticker}} {{interval}} · {{close}}")
alertcondition(tlBreakDn,  "Trendline breakout ↓",      "Rising trendline broken DOWN · {{ticker}} {{interval}} · {{close}}")

← 返回列表