Luxy Momentum, Trend and Breakout Indicators with Multi-Timeframe Bias Table V7.1

orenluxy · study · 2272 行 · 点赞 2,599 · TradingView 原页

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

Pine Script

//@version=6
 
indicator("Luxy Momentum, Trend and Breakout Indicators with Multi-Timeframe Bias Table V7", overlay=true, max_bars_back = 1000, max_lines_count = 150, max_labels_count = 50, max_boxes_count = 50)
 
// ================================================================================
// ATTRIBUTION & CREDITS
// ================================================================================
// This indicator implements proven trading concepts using entirely original code.
//
// CONCEPTUAL INSPIRATIONS (Reimplemented from scratch):
// ------------------------------------------------------------
// • UT Bot ATR Trailing Logic
//   Original concept by @QuantNomad: https://www.tradingview.com/script/HPRRaK7c-UT-Bot-Strategy/
//   Our implementation adds: volume weighting, momentum adjustment, composite SL,
//   multi-filter system (swing, %, 2-bar, ZLSMA), and full integration with bias table.
//   NOTE: No code was copied - this is a complete reimplementation with enhancements.
//
// • Standard Technical Indicators (Public Domain Formulas):
//   - Supertrend: ATR-based trend calculation with custom gradient fills
//   - MACD: Gerald Appel's formula with separation filters
//   - RSI: J. Welles Wilder's formula with pullback zone logic
//   - ADX/DMI: Custom trend strength formula inspired by Wilder's directional movement concept, reimplemented with volume weighting and efficiency metrics
//   - ZLSMA: Zero-lag formula enhanced with Hull MA and momentum prediction
//
// ORIGINAL WORK BY AUTHOR (approximately 70% of total code):
// ------------------------------------------------------------
// • Multi-Timeframe Bias Table with dynamic columns and smart caching
// • Risk Management System with R-multiple targets and freeze-on-touch
// • Opening Range Breakout (ORB) integration with session management
// • Performance optimizations reducing load by 40-60%
// • Composite Stop Loss calculation from multiple S/R layers
// • Visual audit trail system with persistent markers
// • Integrated filter system (Volume, ADX, RSI, Donchian)
// • Custom alert framework
// • Previous Day High/Low auto-detection
// • VIX Fear Index integration
// • 3-Day, Weekly, Monthly, Quarterly bias calculations
// • Smart label management system
// • Conditional calculation framework
//
// DEVELOPMENT PROCESS:
// ------------------------------------------------------------
// • Developed over 2+ months with AI assistance (ChatGPT/Claude) for:
//   - Code generation and optimization
//   - Performance improvements
//   - Pine Script v6 compliance
// • All design decisions, trading logic, system architecture, and feature 
//   integration are original work by the author
// • AI was used as a development tool, not the designer of the trading system
//
// LICENSE: Open Source
// Please maintain attribution when reusing concepts or code
//
// VISUAL ELEMENTS & TRADINGVIEW COMPLIANCE:
// ------------------------------------------------------------
// • No emojis or special characters are used in the script title per TradingView rules
// • Visual symbols (checkmarks, crosses, etc.) appear only in the indicator body, 
//   not in the title, which complies with TradingView's 7-bit ASCII requirement for titles
// • All visual elements in tables and labels are for functional clarity within the indicator
//
// All enhancements, integrations, and optimizations are original work.
// Total lines of original code: ~1500 out of 2158
//
// LICENSE: Open Source - Feel free to learn from and improve upon this code
// Please maintain attribution when reusing components
 
//======================================================
//======================== GROUPS ======================
//======================================================
 
GROUP_MA      = "================== MOVING AVERAGE ==================="
GROUP_VWAP    = "==================== VWAP SETTINGS =================="
GROUP_MACD    = "======================== MACD ======================="
GROUP_ZLSMA   = "=============== ZLSMA - ZERO LAG SMA ================"
GROUP_UT      = "================== UT Bot Settings =================="
GROUP_SL      = "Stoploss ___________________________________________"
GROUP_TP      = "Take Profit ________________________________________"
GROUP_ST      = "===================== Supertrend ==================="
GROUP_ALERTS  = "============== LONG / SHORT Signals ================="
GROUP_ADX     = "ADX _________________________________________________"
GROUP_RSI     = "RSI _________________________________________________"
GROUP_LBL     = "==================== Extra Labels ==================="
GROUP_CNDL    = "CANDLESTICKS ________________________________________"
GROUP_BIAS    = "================ Market Bias Table ================="
GROUP_TF      = "Time Frames _________________________________________  Turn off timeframes you don't need (better performance)."
GROUP_ORB     = "ORB Indicator _______________________________________  Set your session time for Open session breakouts."
 
//======================================================
//======================== INPUTS ======================
//======================================================
 
// === MOVING AVERAGES (modular) ===
const string maInfo = "MA Types: EMA (fast), SMA (smooth), WMA (weighted), VWMA (volume), RMA (Wilder's), HMA (low lag).\n\nTypical lengths:\nScalp: 5-8 / 10-15 / 40-80 / 100-150\nDay: 8-12 / 12-21 / 60-120 / 150-200\nSwing: 10-20 / 20-34 / 100-180 / 200-400\n\nMomentum → EMA/HMA | Trend → SMA/RMA | Breakout → EMA/VWMA\n\nKeep Fast < Medium < Medium-Long < Long. Logic uses Fast/Medium/Long only."
 
// === MOVING AVERAGES (modular) ===
showMAPlots = input.bool(true, "Show all MA Lines", group=GROUP_MA, tooltip = "Master visual switch: turns all MA lines on/off (does not affect logic).")
 
showFastMA  = input.bool(true,  "Fast MA", group=GROUP_MA, inline="rowF")
maShortLen = input.int(10,      "Length",  group=GROUP_MA, inline="rowF")
maFastType  = input.string("EMA","Type",   options=["EMA","SMA","WMA","VWMA","RMA","HMA"], group=GROUP_MA, inline="rowF", tooltip=maInfo)
 
showMedMA = input.bool(true,   "Medium MA", group=GROUP_MA, inline="rowM")
maMedLen = input.int(20,      "Length",    group=GROUP_MA, inline="rowM")
maMedType = input.string("EMA","Type",      options=["EMA","SMA","WMA","VWMA","RMA","HMA"], group=GROUP_MA, inline="rowM", tooltip=maInfo)
 
showMidLongMA  = input.bool(false, "Medium-Long MA", group=GROUP_MA, inline="rowI")
maMidLongLen  = input.int(50,      "Length",     group=GROUP_MA, inline="rowI")
maMidLongType  = input.string("SMA", "Type",       options=["EMA","SMA","WMA","VWMA","RMA","HMA"], group=GROUP_MA, inline="rowI", tooltip=maInfo)
 
showLongMA = input.bool(true,  "Long MA", group=GROUP_MA, inline="rowL")
ma200Len  = input.int(200,    "Length",  group=GROUP_MA, inline="rowL")
maLongType = input.string("SMA","Type",   options=["EMA","SMA","WMA","VWMA","RMA","HMA"], group=GROUP_MA, inline="rowL", tooltip=maInfo)
 
maSwitch(_src, _len, _type) =>
    switch _type
        "EMA"  => ta.ema(_src, _len)
        "SMA"  => ta.sma(_src, _len)
        "WMA"  => ta.wma(_src, _len)
        "VWMA" => ta.vwma(_src, _len)
        "RMA"  => ta.rma(_src, _len)
        "HMA"  => ta.hma(_src, _len)
        => na
 
// VWAP
showVWAP   = input.bool(false, 'Show VWAP /', group=GROUP_VWAP, inline="vwA")
hideonDWM  = input.bool(true, "Hide VWAP on 1D or above", group=GROUP_VWAP, inline="vwA", tooltip = "Show VWAP: enables session-anchored VWAP with optional bands.\n\nHide VWAP on 1D or Above: hides VWAP on Daily+ timeframes to avoid stale anchors")
anchor     = input.string("Session", "Anchor Period", options=["Session","Day","Week","Month","Quarter","Year"], group=GROUP_VWAP, tooltip = "Anchor Period selects how VWAP resets:\nSession, Day, Week, Month, Quarter, Year. Session/Week for intraday; Month/Quarter for swing")
srcVWAP    = input(hlc3, "Source", group=GROUP_VWAP, inline="vwS")
offset     = input.int(0, "Offset", group=GROUP_VWAP, minval=0, inline="vwS", tooltip = "Source: price source for VWAP.\n\nOffset: shifts plotted VWAP/bands right by N bars for visual spacing only")
 
calcModeInput = input.string("Standard Deviation", "Bands Calculation Mode", options=["Standard Deviation","Percentage"], group=GROUP_VWAP, tooltip = "Standard Deviation: bands at k×weighted std-dev around VWAP.\nPercentage: bands at k% of VWAP. Use when volatility is non-stationary.")
bands1On      = input.bool(true,  "Show Bands", group=GROUP_VWAP, inline="vwB")
bandMult_1    = input.float(1.0,  "X1", group=GROUP_VWAP, step=0.5, minval=0, inline="vwB", tooltip = "Enable 1× band around VWAP using the selected calc mode. Good for mean-reversion targets")
bands2On      = input.bool(false, "Show Bands", group=GROUP_VWAP, inline="vwC")
bands3On      = input.bool(false, "Show Bands", group=GROUP_VWAP, inline="vwD")
bandMult_2    = input.float(2.0,  "X2", group=GROUP_VWAP, step=0.5, minval=0, inline="vwC", tooltip = "Show Bands: toggles the second band.\nX2: multiplier for band #2. Typical: 1.5–2.5")
bandMult_3    = input.float(3.0,  "X3", group=GROUP_VWAP, step=0.5, minval=0, inline="vwD", tooltip = "Show Bands: toggles the third band.\nX3: multiplier for band #3. Typical: 2–4.")
 
// MACD
macdSrc   = input.source(close, 'MACD Source', group=GROUP_MACD, tooltip = "Price source used to compute MACD on this chart’s timeframe")
macdFast  = input.int(12, 'MACD Fast', group=GROUP_MACD, inline="macd1")
macdSlow  = input.int(26, 'MACD Slow', group=GROUP_MACD, inline="macd1")
macdSig   = input.int(9,  'MACD Signal', group=GROUP_MACD, inline="macd1", tooltip = "MACD Fast: fast MA length. Typical 8–12.\n\nMACD Slow: slow MA length. Typical 21–26.\n\nSignal: MA of MACD line. Typical 9.")
 
distanceThrPct = input.float(0.2, 'Min MA Distance %', group=GROUP_MACD, tooltip = "Minimum % separation between Fast and Medium MA to consider a valid trend cross.\nHigher = stronger trends only.\nTypical: 0.1–0.5%.")
atrLen         = input.int(14,    'ATR Length (for MACD separation)', group=GROUP_MACD,tooltip = "ATR lookback used to normalize MACD/Signal separation.\nTypical: 10–20.")
macdSepFactor  = input.float(0.1, 'MACD Min Separation (×ATR)', group=GROUP_MACD, tooltip = "Minimum |MACD − Signal| in ATR units.\nFilters weak crossings. Typical: 0.05–0.25×.")
 
// ZLSMA
showZLSMA   = input.bool(false, "Show ZLSMA and choose", group=GROUP_ZLSMA, inline = "zlsA")
zlsmaSrc    = input.source(close, 'ZLSMA Source', group=GROUP_ZLSMA, inline = "zlsA", tooltip = "Plots Predictive momentum-based average for smoother trend following without extra lag.\n\nSource: price series used for ZLSMA.")
zlsmaLength = input.int(75, 'ZLSMA Length', group=GROUP_ZLSMA, inline="zls")
zlsmaOffset = input.int(0,  'ZLSMA Offset', group=GROUP_ZLSMA, inline="zls", tooltip = "Length: lookback for ZLSMA.\nLonger = smoother, more lag.\nTypical: Scalp 25–50, Day 50–100, Swing 75–150.\n\nOffset: visual shift.\nKeep 0 unless you deliberately offset the curve.")
 
// UT Bot
utShowLine   = input.bool(false, "Show UT Bot Line", group=GROUP_UT, inline="utA")
utShowLabels = input.bool(true,  "Show Buy/Sell Labels", group=GROUP_UT, inline="utA", tooltip = "Show UT Bot Line: plots the ATR trailing line.\nBuy/Sell labels are controlled separately, When BUY/SELL is ON, draws an ENTRY marker at the signal bar close") 
entryShow    = input.bool(false, "Show Entry Label on Graph", group=GROUP_UT, inline="utB", tooltip = "Momentum-weighted trailing system with ATR base.\nSignal triggers on directional flip.\nSL = Dynamic trail line...\nFilter: ADX ≥ 25 and DI aligned (+DI>−DI long, −DI>+DI short).\nTP 1:2–1:3.")
drawUtvizOnClose = input.bool(true, "Draw UT visuals only on bar close", group=GROUP_UT, inline="utC", tooltip="When ON, UT-Bot visuals (SL/TP/ENTRY) are drawn/updated only after the bar closes.\n\nTrading impact: NONE — all UT logic, trailing, freeze, and alerts still run intrabar.\n\nSuggested: ON on slower machines.")
utKey        = input.float(1.2,  "Sensitivity (Key×ATR) /", group=GROUP_UT, step=0.1, minval=0.1, inline="utAT")
utAtrPeriod  = input.int(7,      "Period", group=GROUP_UT, minval=1, inline="utAT", tooltip = "Sensitivity (Key×ATR): multiplier of ATR used for the UT trailing stop.\nHigher = wider stop, fewer flips.\n\nPeriod: ATR length for UT.\n\n\nScalp (1–5m):\nKey 0.9–1.2, ATR 5–7.\nConfirm=ON.\nEnter on flip or close beyond ORB.\n\nIntraday (5–15m / 1h):\nBalanced: Key 1.3–1.6, ATR 7–10.\nConservative: Key 1.7–2.2, ATR 10–14.\nEnter only on close outside ORB + rising ADX + DI alignment.\n\nSwing (D/W/M):\nDaily: Key 1.7–2.2, ATR 10–14.\nWeekly: Key 2.0–2.6, ATR 14–21.\nMonthly: Key 2.5–3.0, ATR 21–30.")
utColorBars  = input.bool(false, "Color bars by UT trend", group=GROUP_UT, tooltip = "Colors candles aqua/orange by UT direction for quick regime reading. Visual only.")
 
// UT Filters
utUsePctFilter  = input.bool(false, "Use % Change Filter / ", group=GROUP_UT, inline="utF")
utPctThr        = input.float(0.05, "Min % Change", step=0.05, minval=0, group=GROUP_UT, inline="utF", tooltip = "Use % Change Filter: require minimal bar-to-bar % change before accepting a flip.\n\nMin % Change: threshold in percent.\nTypical: 0.1–0.5% intraday, 0.3–1.0% swing.")
utUseSwingFilter= input.bool(true, "Use Swing Filter /", group=GROUP_UT, inline="utS")
swingLen        = input.int(8,      "Lookback", minval=1, group=GROUP_UT, inline="utS", tooltip = "Use Swing Filter: only take flips aligned with recent swing structure.\n\nLookback: bars used to define swing high/low.\nTypical: 5–10 scalp/day, 10–20 swing.")
utUseDelay      = input.bool(false, "Require 2-Bar Trend Confirmation", group=GROUP_UT, tooltip = "Delay validation until 2 consecutive bars confirm the UT side.\nLowers noise, increases lag.")
utUseZlsmaFilter = input.bool(false, "Filter UT labels by ZLSMA alignment", group=GROUP_UT, tooltip="Buy label only if close > ZLSMA, Sell only if close < ZLSMA. Visual filter only; core UT logic unchanged.")
 
// SL visuals
slShow     = input.bool(true,  "Suggested Stop Loss", group=GROUP_SL, inline="sl")
slLimit10  = input.bool(true,  "Limit to 10 bars",    group=GROUP_SL, inline="sl", tooltip = "Shows the computed SL line from layered supports (UT line, ST, VWAP, Donchian/Swings, MA 200, ATR floor).\n\nLimit to 10 bars: trims SL line length for clutter control.")
slExtraTicks = input.int(0,    "Extra ticks for protection", minval=0, group=GROUP_SL, tooltip = "Adds/subtracts N ticks to the suggested SL for execution buffer")
 
// TP visuals
tpShow    = input.bool(true,  "Show Take Profits", group=GROUP_TP, inline="tpG")
tpLimit10 = input.bool(true,  "Limit to 10 bars",  group=GROUP_TP, inline="tpG", tooltip = "Shows fixed-R targets (1.0, 1.5, 2.0, 3.0) from entry vs. initial risk.\n\nLimit to 10 bars: trims TP line length for decluttering.")
tp1On     = input.bool(true,   "Take Profit Rx1",  group=GROUP_TP, inline="tpA")
tp15On    = input.bool(false,  "TP Rx1.5",         group=GROUP_TP, inline="tpA")
tp2On     = input.bool(true,   "TP Rx2",           group=GROUP_TP, inline="tpA")
tp3On     = input.bool(false,  "TP Rx3",           group=GROUP_TP, inline="tpA", tooltip = "Enables which R-multiple target lines are drawn: R1, R1.5, R2, R3.\nTypical: intraday scale-out at R1/R1.5; swing at R2+.")
tpFreezeOnTouch = input.bool(true, "Freeze TP when touched", group=GROUP_TP, tooltip = "When ON, marks TP as hit and stops moving its label, for audit clarity.")
 
// Supertrend
stShow         = input.bool(true, "Show Supertrend", group=GROUP_ST, inline="stON")
stHideDWM      = input.bool(true, "Hide on 1D or above", group=GROUP_ST, inline="stON", tooltip = "When ON, Supertrend visuals are hidden automatically on Daily/Weekly/Monthly charts. Intraday visuals are unaffected.")
stFillOn       = input.bool(true, "Fill the background", group=GROUP_ST, inline="stZ", tooltip = "Background ribbon from the Supertrend line TOWARD candles.\n\nDisplays a one-sided, layered ribbon. Works for both up/down regimes.")
stSrc          = input.source(hl2, "Source", group=GROUP_ST, tooltip = "Price source used as the Supertrend baseline.")
stAtrPeriod    = input.int(10, "ATR Period", minval=1, group=GROUP_ST, inline="stA")
stMult         = input.float(2.0, "/ ATR Multiplier", step=0.1, group=GROUP_ST, inline="stA", tooltip = "ATR Period: volatility lookback for ST.\n\nATR Multiplier: distance from source to build the stop channel.\nHigher = wider bands, fewer flips.\nTypical: Scalp 1.5–2.0, Day 2.0–3.0, Swing 2.5–4.0.")
stUseATR       = input.bool(true, "ATR Calculation Mode:", group=GROUP_ST, inline="stB")
stNeutralBars  = input.int(0, " Neutral bars after a flip", minval=0, group=GROUP_ST, inline="stB", tooltip = "ATR Calculation Mode: ATR vs. SMA(TR) baseline.\nATR reacts faster; SMA(TR) is smoother.\n\n\Neutral bars after a flip: suppress ST colors and fills for N bars immediately.")
 
// Alerts + filters
showBaseSignals = input.bool(true, "Show Base LONG/SHORT signals", group=GROUP_ALERTS, tooltip = "Shows the base crossover signals (MA cross + optional filters).\nVisual only unless used for alerts.")
macdAboveZero   = input.bool(false,  "Allow LONG only if MACD is above zero",  group=GROUP_ALERTS, tooltip = "When ON, long entries require MACD > 0 (bullish momentum regime).\nReduces counter-trend longs")
macdBelowZero   = input.bool(false,  "Allow SHORT only if MACD is below zero", group=GROUP_ALERTS, tooltip = "When ON, short entries require MACD < 0 (bearish momentum regime).\nReduces counter-trend shorts.")
useVolFilter    = input.bool(false,"Filter entries by relative volume", group=GROUP_ALERTS, tooltip = "When ON: require current bar volume ≥ SMA(volume, N) × K before allowing entries.\nN set by Volume SMA Length; K set by the multiplier below.\nFilters low liquidity noise and emphasizes genuine breakouts.\nSuggested: N≈20, K=1.2–2.0 for intraday (use lower K on illiquid symbols).\nNote: this filter gates Base Long/Short only; UT logic is unchanged.")
volLookback     = input.int(20, "Volume SMA Length", minval=1, group=GROUP_ALERTS, inline="v")
volMinFactor    = input.float(1.2, "×", step=0.1, group=GROUP_ALERTS, inline="v", tooltip = "Filter entries by relative volume: require volume ≥ k×SMA(volume).\n\nVolume SMA Length: lookback for average volume.\n\n×: minimum multiple of average volume.\nTypical: 1.2–2.0.")
useAdxFilter = input.bool(false, "Filter entries by ADX/DI", group=GROUP_ADX, tooltip="When enabled, entries are allowed only when ADX is above your minimum threshold AND the directional indicators agree with the trade direction.\n\nFor LONG: requires +DI > -DI\nFor SHORT: requires -DI > +DI\n\nThis helps filter out entries during weak or choppy trends.")
adxLen          = input.int(14, "ADX Length", minval=2, group=GROUP_ADX, inline="adx")
adxMin          = input.float(20.0, "Min", step=0.5, group=GROUP_ADX, inline="adx", tooltip = "ADX Length: lookback for ADX.\n\nMin: minimum ADX to allow entries.\nTypical: 15–25 intraday, 20–30 swing.")
 
useRsiPullback = input.bool(false, "Require RSI pullback zone", group=GROUP_RSI, tooltip="When enabled, entries are allowed only when RSI is within your configured buy or sell zones.\n\nBuy zone: RSI between Buy Min and Buy Max (typically 40-55)\nSell zone: RSI between Sell Min and Sell Max (typically 45-60)\n\nThis helps ensure you enter on pullbacks rather than chasing extended moves.")
rsiLenM         = input.int(14, "RSI Length", minval=2, group=GROUP_RSI, inline="rsiA")
rsiSrcM         = input.source(close, "RSI Source", group=GROUP_RSI, inline="rsiA", tooltip = "RSI Length: RSI period.\n\nRSI Source: input series for RSI.")
rsiBuyMin       = input.float(40.0, "Buy Min", step=0.5, group=GROUP_RSI, inline="rb")
rsiBuyMax       = input.float(55.0, "Buy Max", step=0.5, group=GROUP_RSI, inline="rb", tooltip = "Buy Min/Max: RSI window for LONG pullbacks.\nTypical: 40–55 in uptrends (adjust per asset).")
rsiSellMin      = input.float(45.0, "Sell Min", step=0.5, group=GROUP_RSI, inline="rs")
rsiSellMax      = input.float(60.0, "Sell Max", step=0.5, group=GROUP_RSI, inline="rs", tooltip = "Sell Min/Max: RSI window for SHORT pullbacks.\nTypical: 45–60 in downtrends.")
 
showDeltaOpen = input.bool(true, "Change from Open % Label |", group=GROUP_LBL, inline="dOpen",tooltip="")
deltaOpenDec  = input.int(2, "Select Decimals", minval=0, maxval=6, group=GROUP_LBL, inline="dOpen", tooltip="Shows current percent change versus the session open on intraday timeframes, and versus today's open on D/W/M.\nGreen if positive, red if negative.\n\nChoose the number of decimals for the ΔOpen% label.\nSuggested: 2 for most assets.")
 
showPDHL = input.bool(false, "Show Previous Day High/Low", group=GROUP_LBL, inline="pdhl")
pdhlLightTheme = input.bool(true, "Light Theme Colors", group=GROUP_LBL, inline="pdhl", tooltip="Displays horizontal lines marking yesterday's high and low levels on the right side of the chart.\n\nThese levels often act as support and resistance zones.\n\nLight Theme Colors: when ON, uses dark colors for light backgrounds. When OFF, uses light colors for dark backgrounds.\n\nThe lines update once per day and are hidden automatically on Daily/Weekly/Monthly charts.")
 
showAdxBadge = input.bool(false, "Show ADX Label", group=GROUP_LBL, inline="lblADX", tooltip="Displays a small badge showing the current ADX value at the bottom of the most recent bar.\n\nThe badge is colored green when ADX is above your minimum threshold (strong trend) and red when below (weak trend).\n\nThis is purely visual and does not affect entry signals.")
showRsiBadge = input.bool(false, "Show RSI Label", group=GROUP_LBL, inline="lblRSI", tooltip="Displays a small badge showing the current RSI value at the top of the most recent bar.\n\nThe badge shows whether RSI is in your configured buy zone (green), sell zone (red), or neutral (yellow).\n\nThis is purely visual and does not affect entry signals.")
 
// Candlestick Patterns
showCandlePatterns = input.bool(false, "Show Candlestick Patterns", group=GROUP_CNDL, tooltip="Master toggle for all candlestick pattern detection. Turn OFF to completely disable all pattern calculations and visuals.")
showBullEngulf   = input.bool(false, "Bullish Engulfing", group=GROUP_CNDL, inline="cndl1")
showBearEngulf   = input.bool(false, "Bearish Engulfing", group=GROUP_CNDL, inline="cndl1", tooltip="Bullish Engulfing:\nA large green candle completely engulfs the prior red candle's body.\n\nStrong bullish reversal signal when it appears after a downtrend or at support.\nThe second candle opens at or below the close of the first and closes above the open of the first.\n\nTrading: Consider long entries when pattern appears at key support levels with volume confirmation.\n\nBearish Engulfing:\nA large red candle completely engulfs the prior green candle's body.\n\nStrong bearish reversal signal when it appears after an uptrend or at resistance.\nThe second candle opens at or above the close of the first and closes below the open of the first.\n\nTrading: Consider short entries or profit-taking when pattern appears at key resistance levels.")
showHammer       = input.bool(false, "Hammer", group=GROUP_CNDL, inline="cndl2")
showShootingStar = input.bool(false, "Shooting Star", group=GROUP_CNDL, inline="cndl2", tooltip="Hammer:\nA candle with a small body at the top and a long lower wick (at least 2x the body size).\n\nBullish reversal pattern that appears at the bottom of downtrends.\nShows rejection of lower prices as buyers stepped in aggressively.\nMost reliable when the body is green and appears near support.\n\nTrading: Wait for confirmation (next candle closes higher) before entering long.\n\nShooting Star:\nA candle with a small body at the bottom and a long upper wick (at least 2x the body size).\n\nBearish reversal pattern that appears at the top of uptrends.\nShows rejection of higher prices as sellers stepped in aggressively.\nMost reliable when the body is red and appears near resistance.\n\nTrading: Wait for confirmation (next candle closes lower) before entering short.")
showMorningStar  = input.bool(false, "Morning Star", group=GROUP_CNDL, inline="cndl3")
showEveningStar  = input.bool(false, "Evening Star", group=GROUP_CNDL, inline="cndl3", tooltip="Morning Star (3-candle pattern):\nCandle 1: Large red candle (downtrend continuation)\nCandle 2: Small-bodied candle (indecision, can be any color)\nCandle 3: Large green candle closing well into the first candle's body\n\nVery strong bullish reversal signal at the end of downtrends.\nThe middle candle represents sellers losing momentum.\n\nTrading: Enter long on or after the third candle. Best at major support zones.\n\nEvening Star (3-candle pattern):\nCandle 1: Large green candle (uptrend continuation)\nCandle 2: Small-bodied candle (indecision, can be any color)\nCandle 3: Large red candle closing well into the first candle's body\n\nVery strong bearish reversal signal at the end of uptrends.\nThe middle candle represents buyers losing momentum.\n\nTrading: Enter short on or after the third candle. Best at major resistance zones.")
minCandleBodyPct = input.float(0.1, "Min candle body % to filter noise", minval=0.01, maxval=0.20, step=0.01, group=GROUP_CNDL, tooltip="Minimum candle body size as a percentage of price to filter out tiny/noisy candles.\n\nHigher values = fewer but stronger signals.\nLower values = more signals but may include noise.\n\nTypical: 0.05-0.10% for stocks, 0.10-0.20% for crypto.\n\nThis filter applies to all candlestick patterns.")
 
// BIAS Table
showTable     = input.bool(true, "Show Table   | ", group=GROUP_BIAS, inline="tblC")
tableBgColor  = input.color(color.new(color.rgb(35,38,43),0), "and select background color", group=GROUP_BIAS, inline="tblC", tooltip = "Show Table: toggles the bias dashboard.\n\nBackground Color: table background color used for header and rows.")
hideBiasOnDplus = input.bool(false, "Hide BIAS table on 1D or above", group=GROUP_BIAS, inline="tbl1D", tooltip="When ON, the BIAS table is disabled on Daily/Weekly/Monthly and all its computations are skipped.")
textSize      = input.string(size.small, "Text Size", options=[size.tiny,size.small,size.normal,size.large], group=GROUP_BIAS, inline="tblA")
tablePosLabel = input.string("Top Right", "Table Position", options=["Top Left","Top Right","Middle Left","Middle Right","Bottom Left","Bottom Right"], group=GROUP_BIAS, inline="tblA", tooltip = "Text Size: overall table font size.\n\nTable Position: anchor corner for the dashboard.\n\nDO NOT use the same position for the Bias Table and the Watchlist table, or it will not show them both")
rowBias3D     = input.bool(true, "3 Day |",                          group=GROUP_BIAS, inline="tblE")
rowBiasWeekly = input.bool(true, "Weekly |",                          group=GROUP_BIAS, inline="tblE")
rowBiasMonth  = input.bool(true, "Monthly |",                           group=GROUP_BIAS, inline="tblE")
rowBiasQuarter = input.bool(true, "Quarterly Bias",                  group=GROUP_BIAS, inline="tblE", tooltip = "Calculations:\n\n3 Day Bias 1H based on fixed-window slope of close. Window equals the last 3 regular sessions on 1h\n\nWeekly Bias 4H based on fixed-window slope of close. Window equals the last 5 regular sessions on 4h.\n\nMonthly Bias 1D based on fixed-window slope of close over the last 30 daily bars.\n\nQuarterly Bias 1W based on fixed-window slope of close over the last 13 Weekly bars.\n\nBullish when slope positive.\nBearish when negative.\nNeutral when zero or data insufficient.")
rowVIX        = input.bool(true, "VIX Fear Index Bias",               group=GROUP_BIAS, inline="tblG", tooltip="Show a daily VIX-based market regime row in the BIAS table.\n\nLogic:\nBULLISH if VIX < 18\nNEUTRAL if 18 ≤ VIX ≤ 22\nBEARISH if VIX > 22.")
rowORB        = input.bool(true, "Opening Range Breakout",            group=GROUP_BIAS,inline="orb",  tooltip="Intraday only: this row is hidden automatically on Daily/Weekly/Monthly charts.\n\nSuggested use:\nLeave ON for intraday equities/indices.")
rowMA        = input.bool(true,  "Fast MA > Slow MA |",              group=GROUP_BIAS, inline="tblB")
rowMA200     = input.bool(true,  "Price > MA 200",                   group=GROUP_BIAS, inline="tblB", tooltip = "Fast MA > Slow MA: short/long MA cross per TF cells.\n\nPrice > MA 200: close vs. MA 200 per TF cells.")
rowVWAP       = input.bool(true,  "Price > VWAP |",                   group=GROUP_BIAS, inline="tblD")
useAnchoredVWAPinTable = input.bool(false, "Use anchored VWAP in table", group=GROUP_BIAS, inline="tblD",tooltip = "Price > VWAP: per-TF comparison in the Bias table.\n\nHTF defaults when OFF:\n• D → Week\n• W → Month\n• M → Year\n\nWhen ON, the selected anchor is used but never shorter than the TF minimum above (e.g., Day/Session clamp to Week on D). Intraday keeps your chosen anchor or plain VWAP.")
rowMACD       = input.bool(true,  "MACD > Signal",                    group=GROUP_BIAS, inline="tblMACD", tooltip = "MACD > Signal: MACD line above signal per TF cells.")
rowST         = input.bool(true,  "Show: Supertrend Bullish / Bearish", group=GROUP_BIAS, tooltip = "Displays ST direction per TF cells")
rowZLSMA      = input.bool(true,  "Show: Zero-Lag SMA Rising",        group=GROUP_BIAS, tooltip = "ZLSMA slope rising per TF cells.")
rowRSI        = input.bool(true,  "RSI In Zone |",                    group=GROUP_BIAS, inline="tblF")
rowADX        = input.bool(true,  "ADX ≥ Minimum",                    group=GROUP_BIAS, inline="tblX", tooltip = "RSI In Zone: RSI within configured buy/sell windows per TF cells.\n\nADX ≥ Minimum: ADX above threshold per TF cells.")
 
const string vixSymbol = "TVC:VIX"
const string vixTF = "D"
 
//======================================================
//================= CORE CALCULATIONS ==================
//======================================================
 
// Selected MAs
maShort    = maSwitch(close, maShortLen,   maFastType)
maMedium   = maSwitch(close, maMedLen,     maMedType)
maMidLong  = maSwitch(close, maMidLongLen, maMidLongType)
maLong      = maSwitch(close, ma200Len,     maLongType)
 
// MACD and ATR separation
[macdLine, signalLine, _macdh] = ta.macd(macdSrc, macdFast, macdSlow, macdSig)
atrNow   = ta.atr(atrLen)
maBase = not na(maMedium) ? maMedium : na
maDistanceOk = not na(maBase) and math.abs(maShort - maBase) / maBase * 100 > distanceThrPct
macdSepOk     = math.abs(macdLine - signalLine) > atrNow * macdSepFactor
 
// Returns true only when the chosen anchor resets on the CURRENT context TF.
anchor_reset(string how) =>
    (how == "Session"   ? session.isfirstbar :
     how == "Day"       ? timeframe.change("D") :
     how == "Week"      ? timeframe.change("W") :
     how == "Month"     ? timeframe.change("M") :
     how == "Quarter"   ? timeframe.change("3M") :
     how == "Year"      ? timeframe.change("12M") :
     false)
 
// === VWAP Period Detection (before VWAP calc) ===
bool vwActive = showVWAP and not (hideonDWM and timeframe.isdwm)
bool isNewPeriod = anchor_reset(anchor)
 
// === VWAP + Bands (volume-weighted, robust to toggles) ===
float vwapValue        = na
float upperBandValue1  = na
float lowerBandValue1  = na
float upperBandValue2  = na
float lowerBandValue2  = na
float upperBandValue3  = na
float lowerBandValue3  = na
 
// persistent accumulators (volume-weighted)
var float _sumPV  = 0.0      // Σ(price * vol)
var float _sumV   = 0.0      // Σ(vol)
var float _sumP2V = 0.0      // Σ(price^2 * vol)  -> enables weighted variance
 
bool _startNew = isNewPeriod
 
if vwActive
    // start/restart period
    if _startNew
        _sumPV  := 0.0
        _sumV   := 0.0
        _sumP2V := 0.0
 
    float _p = srcVWAP
    float _v = volume
 
    // Enhanced VWAP with micro-structure noise reduction
    float volumeFiltered = volume > ta.sma(volume, 20) * 0.1 ? volume : 0
    _sumPV  += _p * volumeFiltered
    _sumV   += volumeFiltered  
    vwapValue := _sumV > 0 ? _sumPV / _sumV : na
 
    // weighted variance around VWAP: E[p^2] – (E[p])^2  with weights = volume
    float _var = _sumV != 0 ? (_sumP2V / _sumV) - (vwapValue * vwapValue) : na
    // Custom volatility-adjusted bands
    float _wStd = na(_var) ? na : math.sqrt(math.max(0.0, _var)) * (1 + ta.atr(10)/close * 0.1)    
 
 
    float _bandBasis = calcModeInput == "Standard Deviation" ? _wStd : vwapValue * 0.01
 
    upperBandValue1 := na(_bandBasis) ? na : vwapValue + _bandBasis * bandMult_1
    lowerBandValue1 := na(_bandBasis) ? na : vwapValue - _bandBasis * bandMult_1
    upperBandValue2 := na(_bandBasis) ? na : vwapValue + _bandBasis * bandMult_2
    lowerBandValue2 := na(_bandBasis) ? na : vwapValue - _bandBasis * bandMult_2
    upperBandValue3 := na(_bandBasis) ? na : vwapValue + _bandBasis * bandMult_3
    lowerBandValue3 := na(_bandBasis) ? na : vwapValue - _bandBasis * bandMult_3
else
    // when VWAP is inactive on this TF or hidden, output NA and do not keep accumulating
    vwapValue        := na
    upperBandValue1  := na
    lowerBandValue1  := na
    upperBandValue2  := na
    lowerBandValue2  := na
    upperBandValue3  := na
    lowerBandValue3  := na
 
//======================================================
//================= BASE CONDITIONS ====================
//======================================================
vwOkLong  = vwActive ? (close > vwapValue) : true
vwOkShort = vwActive ? (close < vwapValue) : true
 
longCond_base  = ta.crossover(maShort, maMedium) and vwOkLong  and macdSepOk and maDistanceOk and close > open and (not macdAboveZero or macdLine > 0)
shortCond_base = ta.crossunder(maShort, maMedium) and vwOkShort and macdSepOk and maDistanceOk and close < open and (not macdBelowZero or macdLine < 0)
 
//======================================================
//====================== ZLSMA =========================
// Enhanced Zero-Lag SMA with Predictive Elements
zlsma_calc(src, length, zls_offset) =>
    float ema_fast = ta.ema(src, length/2)
    float ema_slow = ta.ema(src, length)
    float momentum_rate = (ema_fast - ema_slow) / length
    float hull_ma = ta.hma(src, length)
    float prediction = hull_ma + momentum_rate * (length/4)
    float final = (prediction * 0.4 + ema_fast * 0.6)
    final + zls_offset
 
bool needZlsmaMain = showZLSMA or utUseZlsmaFilter or rowZLSMA
var float zlsma = na
if needZlsmaMain
    zlsma := zlsma_calc(zlsmaSrc, zlsmaLength, zlsmaOffset)
bool zlsmaAgreeBuy  = not utUseZlsmaFilter or na(zlsma) or close > zlsma
bool zlsmaAgreeSell = not utUseZlsmaFilter or na(zlsma) or close < zlsma
 
// Custom Momentum-Weighted Trailing System
srcUT = close
xATR   = ta.atr(utAtrPeriod)
 
// Unique momentum-based trail calculation
var float xATRTrailingStop = na
float momentum = ta.mom(srcUT, 5) / srcUT
float volRatio = volume / ta.sma(volume, 20)
float adaptiveKey = utKey * (1 + math.abs(momentum) * 2) * math.max(0.8, math.min(1.2, volRatio))
float trailDist = xATR * adaptiveKey
 
if na(xATRTrailingStop)
    xATRTrailingStop := srcUT
else
    float targetTrail = srcUT > xATRTrailingStop ? srcUT - trailDist : srcUT + trailDist
    float smoothing = 0.3
    xATRTrailingStop := xATRTrailingStop * (1 - smoothing) + targetTrail * smoothing
 
above = ta.crossover(srcUT, xATRTrailingStop) and volRatio > 0.8
below = ta.crossunder(srcUT, xATRTrailingStop) and volRatio > 0.8
 
// Guard extremely small prices from exploding percentage
atrPct = srcUT != 0 ? (xATR / srcUT * 100.0) : 0.0
float atrPctSafe = math.min(atrPct, 20.0)
kUT    = 0.50
thr    = math.max(utPctThr, atrPctSafe * kUT)
 
//rawBuy  = srcUT > xATRTrailingStop and above
//rawSell = srcUT < xATRTrailingStop and below
barbuy  = srcUT > xATRTrailingStop
barsell = srcUT < xATRTrailingStop
 
chgOk     = not utUsePctFilter or (math.abs(srcUT - srcUT[1]) / srcUT[1] * 100.0 > thr)
 
// Momentum structure validation
float _lo = na
float _hi = na
if utUseSwingFilter
    _lo := ta.lowest(srcUT, swingLen)
    _hi := ta.highest(srcUT, swingLen)
 
swingOkBuy  = not utUseSwingFilter or srcUT > _lo * 1.01
swingOkSell = not utUseSwingFilter or srcUT < _hi * 0.99
 
// Volume filter - compute only when enabled
float _vma = na
if useVolFilter
    _vma := ta.sma(volume, volLookback)
 
volOK = useVolFilter ? (na(_vma) or volume >= _vma * volMinFactor) : true
 
// 2-bar delay
delayOkBuy  = not utUseDelay or ((bar_index > 0 ? barbuy[1]  : false) and (bar_index > 1 ? barbuy[2]  : false))
delayOkSell = not utUseDelay or ((bar_index > 0 ? barsell[1] : false) and (bar_index > 1 ? barsell[2] : false))
flipUp = above
flipDn = below
utBuy  = (utUseDelay ? ((bar_index > 1 ? flipUp[2]  : false) and (bar_index > 0 ? barbuy[1]  : false) and (bar_index > 1 ? barbuy[2]  : false)) : flipUp)  and chgOk and swingOkBuy
utSell = (utUseDelay ? ((bar_index > 1 ? flipDn[2]  : false) and (bar_index > 0 ? barsell[1] : false) and (bar_index > 1 ? barsell[2] : false)) : flipDn) and chgOk and swingOkSell
 
confirmRealBuy  = close > xATRTrailingStop
confirmRealSell = close < xATRTrailingStop
 
utBuy  := utBuy  and confirmRealBuy
utSell := utSell and confirmRealSell
if utUseZlsmaFilter
    utBuy  := utBuy  and zlsmaAgreeBuy
    utSell := utSell and zlsmaAgreeSell
 
bool utVizGate = not drawUtvizOnClose ? true : (barstate.isconfirmed or not barstate.isrealtime)
 
// Feature ON/OFF
bool slFeatureOn    = slShow and utShowLabels
bool tpFeatureOn    = tpShow and utShowLabels
bool entryFeatureOn = entryShow 
 
// Creates SL line/label if missing and returns them
ensureSLObjects(line _ln, label _lb, int _x, float _y, color _c) =>
    line ln_result = _ln
    label lb_result = _lb
    if na(ln_result) and not na(_x) and not na(_y)
        ln_result := line.new(_x, _y, _x, _y, xloc=xloc.bar_index, extend=extend.none, color=_c, width=1)
    if na(lb_result) and not na(_x) and not na(_y)
        lb_result := label.new(_x, _y, "Suggested Stop Loss", xloc=xloc.bar_index, style=label.style_label_left, textcolor=color.white, color=_c)
    [ln_result, lb_result]
 
// Forward state flags used by visual gates
var bool legDone     = false
var int  legDoneBar  = na
var bool slFrozen    = false
var int  slFrozenBar = na
var bool entryFrozen = false
var bool tp1Frozen   = false
var bool tp15Frozen  = false
var bool tp2Frozen   = false
var bool tp3Frozen   = false
 
// Visual gates (allow forced draw on touch/freeze even if "draw on close" is ON)
bool slShowVis    = slFeatureOn    and (utVizGate or slFrozen or legDone)
bool tpShowVis    = tpFeatureOn    and (utVizGate or tp1Frozen or tp15Frozen or tp2Frozen or tp3Frozen or legDone)
bool entryShowVis = entryFeatureOn and (utVizGate or entryFrozen or legDone)
 
// mark TP hits so labels can show ✅ even if they were off and later re-shown
var bool tp1Hit  = false
var bool tp15Hit = false
var bool tp2Hit  = false
var bool tp3Hit  = false
 
// cap helper: do not extend objects past the bar where the leg ended
capX2(int x) =>
    not na(legDoneBar) ? math.min(x, legDoneBar) : x
 
//======================================================
//============== PREVIOUS DAY HIGH/LOW =================
//======================================================
 
bool pdhlActive = showPDHL and timeframe.isintraday
float pdh = na
float pdl = na
 
// Define colors based on theme toggle
color pdhlLineColor = pdhlLightTheme ? color.new(color.black, 0) : color.new(color.white, 0)
color pdhlTextColor = pdhlLightTheme ? color.new(color.black, 0) : color.new(color.white, 0)
 
if pdhlActive
    // Get COMPLETED previous day high/low (offset [1] INSIDE security call)
    pdh := request.security(syminfo.tickerid, "D", high[1], barmerge.gaps_off, barmerge.lookahead_on)
    pdl := request.security(syminfo.tickerid, "D", low[1], barmerge.gaps_off, barmerge.lookahead_on)
 
// Draw lines and labels
var line pdhLine = na
var line pdlLine = na
var label pdhLabel = na
var label pdlLabel = na
 
if pdhlActive and barstate.islast
    int x1 = bar_index + 1
    int x2 = bar_index + 6
    
    // Delete old objects
    if not na(pdhLine)
        line.delete(pdhLine)
    if not na(pdlLine)
        line.delete(pdlLine)
    if not na(pdhLabel)
        label.delete(pdhLabel)
    if not na(pdlLabel)
        label.delete(pdlLabel)
    
    // Create new lines
    pdhLine := line.new(x1, pdh, x2, pdh, xloc=xloc.bar_index, color=pdhlLineColor, width=1, style=line.style_solid)
    pdlLine := line.new(x1, pdl, x2, pdl, xloc=xloc.bar_index, color=pdhlLineColor, width=1, style=line.style_solid)
    
    // Create labels above/below the lines
    float labelOffset = (high - low) * 0.001
    int xMid = int((x1 + x2) / 2)
    pdhLabel := label.new(xMid, pdh + labelOffset, "PREVIOUS DAY HIGH ⭡", xloc=xloc.bar_index, style=label.style_none, textcolor=pdhlTextColor, size=size.small, textalign=text.align_center)
    pdlLabel := label.new(xMid, pdl - labelOffset, "PREVIOUS DAY LOW ⭣", xloc=xloc.bar_index, style=label.style_none, textcolor=pdhlTextColor, size=size.small, textalign=text.align_center)
 
else if not pdhlActive
    // Clean up when disabled
    if not na(pdhLine)
        line.delete(pdhLine), pdhLine := na
    if not na(pdlLine)
        line.delete(pdlLine), pdlLine := na
    if not na(pdhLabel)
        label.delete(pdhLabel), pdhLabel := na
    if not na(pdlLabel)
        label.delete(pdlLabel), pdlLabel := na
//======================================================
//================ VOLUME / DMI / RSI / DON ============
//======================================================
 
// Custom Trend Strength Measurement
// Inspired by Wilder's ADX concept but using volume-weighted pressure
// and efficiency-based calculation instead of traditional +DI/-DI smoothing
 
dmi_local(int _len) =>
    float priceMove = close - close[_len]
    float avgRange = ta.sma(high - low, _len)
    float efficiency = avgRange > 0 ? math.abs(priceMove) / (avgRange * _len) : 0
    
    float upPressure = math.max(0, high - high[1]) * volume
    float dnPressure = math.max(0, low[1] - low) * volume
    
    float smoothUp = ta.hma(upPressure, _len)
    float smoothDn = ta.hma(dnPressure, _len)
    float totalPressure = ta.hma(upPressure + dnPressure, _len)
    
    float diP = totalPressure > 0 ? 100 * smoothUp / totalPressure : 50
    float diM = totalPressure > 0 ? 100 * smoothDn / totalPressure : 50
    float adxv = 100 * efficiency * math.abs(diP - diM) / 100
    
    [math.min(100, adxv), diP, diM]
 
// === DMI/ADX (current TF) for base entries & badge ===
bool needDMIrt = useAdxFilter or showAdxBadge
 
float adxVal   = na
float diP_rt   = na
float diM_rt   = na
bool  adxAgreeLong  = true
bool  adxAgreeShort = true
bool  adxOk         = true
 
if needDMIrt
    // Single Wilder compute on the current TF (no security() on same TF)
    [adx_local, diP_local, diM_local] = dmi_local(adxLen)
    adxVal   := adx_local
    diP_rt   := diP_local
    diM_rt   := diM_local
 
    adxOk         := adxVal >= adxMin
    adxAgreeLong  := diP_rt >  diM_rt
    adxAgreeShort := diM_rt >  diP_rt
 
longCond_base  := longCond_base  and (not useAdxFilter or (adxOk and adxAgreeLong))
shortCond_base := shortCond_base and (not useAdxFilter or (adxOk and adxAgreeShort))
 
 
// RSI pullback — compute only if needed
bool needRSIrt = useRsiPullback or showRsiBadge
float rsiV = na
if needRSIrt
    rsiV := ta.rsi(rsiSrcM, rsiLenM)
 
bool rsiOkLong  = not useRsiPullback or (rsiV >= math.min(rsiBuyMin, rsiBuyMax)  and rsiV <= math.max(rsiBuyMin,  rsiBuyMax))
bool rsiOkShort = not useRsiPullback or (rsiV >= math.min(rsiSellMin, rsiSellMax) and rsiV <= math.max(rsiSellMin, rsiSellMax))
longCond_base  := longCond_base  and rsiOkLong
shortCond_base := shortCond_base and rsiOkShort
 
useClassicRSIBias = input.bool(true, "Use classic RSI 30/70 for Bias row", group=GROUP_BIAS, inline ="tblF", tooltip="When Off, the RSI row in the Bias table will use your RSI setup from above.\n\nWhen ON, the RSI row in the Bias table uses classic thresholds:\n<30 = Bullish (🟩), >70 = Bearish (🟥), else Neutral (🟡).\n\nThis does NOT change your entry filters; only the table row.")
 
// Donchian — compute only if needed
useDonchian = input.bool(false, "Require Donchian breakout |", group=GROUP_ALERTS, inline="docA")
donLen      = input.int(20, "Length", minval=1, group=GROUP_ALERTS, inline="docA", tooltip = "Require Donchian breakout: only allow entries when price breaks Donchian high/low.\n\nLength: lookback for Donchian channel.\nTypical: 20–55 trend following.")
 
float donHigh = na
float donLow = na
if useDonchian
    donHigh := ta.highest(high, donLen)
    donLow  := ta.lowest(low,  donLen)
 
bool donOkLong  = not useDonchian ? true : (not na(donHigh) and close > donHigh)
bool donOkShort = not useDonchian ? true : (not na(donLow)  and close < donLow)
 
longCond_base  := longCond_base  and donOkLong  and volOK
shortCond_base := shortCond_base and donOkShort and volOK
 
//======================================================
//====================== VISUALS =======================
//======================================================
 
plot(showMAPlots and showFastMA    ? maShort    : na, "Fast MA",     color=color.rgb(51,204,214), linewidth=2)
plot(showMAPlots and showMedMA     ? maMedium   : na, "Medium MA",   color=color.rgb(230,5,255),  linewidth=2, linestyle=plot.linestyle_dashed)
plot(showMAPlots and showMidLongMA ? maMidLong : na, "Medium-Long MA", color=color.rgb(170, 0, 255), linewidth=3, linestyle=plot.linestyle_dashed)
plot(showMAPlots and showLongMA    ? maLong     : na, "Long MA",     color=color.rgb(0, 0, 0, 40),      linewidth=3, linestyle=plot.linestyle_dashed)
 
plot(vwActive ? vwapValue : na, "VWAP", color=color.rgb(6,58,245), linewidth=2, linestyle = plot.linestyle_dotted, offset=offset)
 
upperBand_1 = plot(vwActive and bands1On and not na(upperBandValue1) ? upperBandValue1 : na, "Upper Band #1", color=color.lime, display=display.all, offset=offset)
lowerBand_1 = plot(vwActive and bands1On and not na(lowerBandValue1) ? lowerBandValue1 : na, "Lower Band #1", color=color.lime, display=display.all, offset=offset)
fill(upperBand_1, lowerBand_1, title="VWAP Band 1 Background", color=color.new(color.lime, 98))
 
upperBand_2 = plot(vwActive and bands2On and not na(upperBandValue2) ? upperBandValue2 : na, "Upper Band #2", color=color.olive, display=display.all, offset=offset)
lowerBand_2 = plot(vwActive and bands2On and not na(lowerBandValue2) ? lowerBandValue2 : na, "Lower Band #2", color=color.olive, display=display.all, offset=offset)
fill(upperBand_2, lowerBand_2, title="VWAP Band 2 Background", color=color.new(color.olive, 98), display=display.all)
 
upperBand_3 = plot(vwActive and bands3On and not na(upperBandValue3) ? upperBandValue3 : na, "Upper Band #3", color=color.teal, display=display.all, offset=offset)
lowerBand_3 = plot(vwActive and bands3On and not na(lowerBandValue3) ? lowerBandValue3 : na, "Lower Band #3", color=color.teal, display=display.all, offset=offset)
fill(upperBand_3, lowerBand_3, title="VWAP Band 3 Background", color=color.new(color.teal, 98), display=display.all)
 
plot(showZLSMA ? zlsma : na, "ZLSMA", color=color.yellow, linewidth=2)
 
plot(utShowLine ? xATRTrailingStop : na, title="UT Trailing Stop", color=color.orange, linewidth=2)
plotshape(utShowLabels and utVizGate and utBuy,  title="Buy",  text="Buy",  style=shape.labelup,   location=location.belowbar, color=color.aqua,   textcolor=color.white, size=size.tiny)
plotshape(utShowLabels and utVizGate and utSell, title="Sell", text="Sell", style=shape.labeldown, location=location.abovebar, color=color.orange, textcolor=color.white, size=size.tiny)
barcolor(utColorBars ? (barbuy ? color.aqua : barsell ? color.orange : na) : na)
 
//======================================================
//================= SUPERTREND (on-chart) ==============
//======================================================
bool stActive = stShow and not (stHideDWM and timeframe.isdwm)
 
//==================== BEHAVIOR INPUTS =================
dynCapATR     = input.float(0.60, "Strength cap (×ATR)",  minval=0.05, step=0.05, group=GROUP_ST, tooltip = "Defines the maximum normalized strength used to scale thickness. \nExpressed as a multiple of ATR.\nTypical: 0.5–1.0 for intraday, 1.0–2.0 for swing. \nHigher cap makes fewer bars hit the maximum width.")
dynSmoothLen  = input.int(3,      "Strength smoothing (EMA)", minval=1, maxval=10, group=GROUP_ST, tooltip = "Smooths the raw strength signal before mapping to line width. \nUses an EMA of the chosen length. Low values (1–2) react faster but can look noisy. \nHigher values (5–10) give steadier, cleaner transitions.")
dynLookback   = input.int(200,    "Max segments to keep", minval=50, maxval=500, group=GROUP_ST, tooltip = "Limits how many historical SuperTrend segments (lines) remain drawn on chart. \nHelps performance and avoids clutter. \nRecommended: 100–200 for normal use, up to 500 if you need long history.")
 
// Adaptive Volatility Channel System 
tr    = ta.tr
atrS  = stUseATR ? ta.atr(stAtrPeriod) : ta.sma(tr, stAtrPeriod)
 
// Custom volatility bands with volume weighting
float volWeight = volume / ta.sma(volume, stAtrPeriod)
float trendStrength = math.abs(ta.correlation(close, bar_index, stAtrPeriod))
float adaptiveMult = stMult * (0.8 + trendStrength * 0.4) * math.sqrt(volWeight)
 
var float upLine = na
var float dnLine = na
 
float upRaw = stSrc - atrS * adaptiveMult
float dnRaw = stSrc + atrS * adaptiveMult
 
if na(upLine[1])
    upLine := upRaw
    dnLine := dnRaw
else
    float smooth = 0.15
    upLine := close > upLine[1] ? upLine[1] * (1-smooth) + upRaw * smooth : upRaw
    dnLine := close < dnLine[1] ? dnLine[1] * (1-smooth) + dnRaw * smooth : dnRaw
 
// Direction state + neutral window
const int A1 = 30, A2 = 40, A3 = 50, A4 = 60, A5 = 70, A6 = 80
const color ST_BULL = color.new(color.green, 20)
const color ST_BEAR = color.new(color.red,   20)
const color STB_A2 = color.new(ST_BULL, A2)
const color STB_A3 = color.new(ST_BULL, A3)
const color STB_A4 = color.new(ST_BULL, A4)
const color STB_A5 = color.new(ST_BULL, A5)
const color STB_A6 = color.new(ST_BULL, A6)
 
const color STR_A2 = color.new(ST_BEAR, A2)
const color STR_A3 = color.new(ST_BEAR, A3)
const color STR_A4 = color.new(ST_BEAR, A4)
const color STR_A5 = color.new(ST_BEAR, A5)
const color STR_A6 = color.new(ST_BEAR, A6)
 
var int stDir = na
stDir := na(stDir[1]) ? (close >= stSrc ? 1 : -1) : stDir[1]
stDir := stDir == -1 and close > dnLine[1] ?  1 :
         stDir ==  1 and close < upLine[1] ? -1 : stDir
 
bool stFlip        = stDir != stDir[1]
bool neutral = false
if stNeutralBars > 0
    int barsSinceFlip = ta.barssince(stFlip)
    neutral := barsSinceFlip >= 0 and barsSinceFlip < stNeutralBars
 
//bool stVizGate = utVizGate and stActive and not neutral
bool stLogicGate = stActive and not neutral
bool stFillGate = stLogicGate and stFillOn 
 
float upSeg = (stActive and stDir ==  1 and not neutral) ? upLine : na
float dnSeg = (stActive and stDir == -1 and not neutral) ? dnLine : na
 
// === ST Fan Rendering (one-sided ribbon toward candles) ===
bool stFanGate = stActive and not neutral and stFillOn
const float stNearPadATR = 0.12
 
// Strength: distance from line normalized by ATR, then capped & smoothed
gap    = stDir == 1 ? (close - upLine) : (dnLine - close)
float fanPad  = stFanGate ? atrS * stNearPadATR : 0.0
float fanGap  = math.max(0.0, gap - fanPad)
rawStr = stShow and not neutral and atrS > 0 and not na(gap) ? math.max(0.0, gap / atrS) : na
capS   = na(rawStr) ? na : math.min(rawStr, dynCapATR)
sStr   = na(capS)   ? na : ta.ema(capS, dynSmoothLen)
norm   = na(sStr)   ? 0.0 : math.max(0.0, math.min(1.0, sStr / dynCapATR))
 
// Far cap lines for a soft haze (one per side)
float uFar = stFanGate and stDir ==  1 ? upLine + math.min(gap, atrS * dynCapATR) : na
float dFar = stFanGate and stDir == -1 ? dnLine - math.min(gap, atrS * dynCapATR) : na
 
pUfar = plot(uFar, title="ST Up Haze Line",   style=plot.style_stepline, display=display.none, editable=false)
pDfar = plot(dFar, title="ST Down Haze Line", style=plot.style_stepline, display=display.none, editable=false)
 
// STYLE-safe base plots (linewidth constant → users can style colors)
int stLineWidth = stFillOn ? 2 : 4
stUpPlot = plot(stActive ? upSeg : na, title="Supertrend Up",   style=plot.style_linebr, linewidth=stLineWidth, color=ST_BULL, editable=false)
stDnPlot = plot(stActive ? dnSeg : na, title="Supertrend Down", style=plot.style_linebr, linewidth=stLineWidth, color=ST_BEAR, editable=false)
 
// very transparent base haze
fill(stUpPlot, pUfar, color = stFillGate ? color.new(ST_BULL, 92) : na, title="ST Up Haze",   editable=false)
fill(stDnPlot, pDfar, color = stFillGate ? color.new(ST_BEAR, 92) : na, title="ST Down Haze", editable=false)
 
// Flip markers
plotshape(stShow and stFlip and  not (stHideDWM and timeframe.isdwm) and stDir ==  1 ? upLine : na, title="ST Bull Start", location=location.absolute, style=shape.circle, size=size.tiny, color=ST_BULL, editable=false)
plotshape(stShow and stFlip and  not (stHideDWM and timeframe.isdwm) and stDir == -1 ? dnLine : na, title="ST Bear Start", location=location.absolute, style=shape.circle, size=size.tiny, color=ST_BEAR, editable=false)
 
// === ST Fan Levels (one-sided ribbon toward candles) ===
st_fan_levels(float up_line, float dn_line, int dir, float gap, float atr, float cap_mult) =>
    float  g = na(gap) ? na : math.max(0.0, gap)
    float  dcap = g
    float  l1 = na 
    float  l2 = na
    float  l3 = na
    float  l4 = na
    float  l5 = na
 
    if not na(dcap) and dir != 0
        float p1 = 0.12
        float p2 = 0.27
        float p3 = 0.41
        float p4 = 0.61
        float p5 = 1.00
 
        if dir == 1
            l1 := up_line + dcap * p1
            l2 := up_line + dcap * p2
            l3 := up_line + dcap * p3
            l4 := up_line + dcap * p4
            l5 := up_line + dcap * p5
        else
            l1 := dn_line - dcap * p1
            l2 := dn_line - dcap * p2
            l3 := dn_line - dcap * p3
            l4 := dn_line - dcap * p4
            l5 := dn_line - dcap * p5
    [l1, l2, l3, l4, l5]
 
//================= DYNAMIC THICKNESS OVERLAY =========
 
 
//[fan1, fan2, fan3, fan4, fan5] = st_fan_levels(upLine, dnLine, stDir, gap, atrS, dynCapATR)
[fan1, fan2, fan3, fan4, fan5] = st_fan_levels(upLine, dnLine, stDir, fanGap, atrS, dynCapATR)
 
// Side-specific series
float u0 = stFanGate and stDir ==  1 ? upLine : na
float u1 = stFanGate and stDir ==  1 ? fan1 : na
float u2 = stFanGate and stDir ==  1 ? fan2 : na
float u3 = stFanGate and stDir ==  1 ? fan3 : na
float u4 = stFanGate and stDir ==  1 ? fan4 : na
float u5 = stFanGate and stDir ==  1 ? fan5 : na
 
float d0 = stFanGate and stDir == -1 ? dnLine : na
float d1 = stFanGate and stDir == -1 ? fan1 : na
float d2 = stFanGate and stDir == -1 ? fan2 : na
float d3 = stFanGate and stDir == -1 ? fan3 : na
float d4 = stFanGate and stDir == -1 ? fan4 : na
float d5 = stFanGate and stDir == -1 ? fan5 : na
 
// Hidden guides
pU0 = plot(u0, title="ST Up Fan L0",  style=plot.style_stepline, display=display.none, editable=false)
pU1 = plot(u1, title="ST Up Fan L1", style=plot.style_stepline, display=display.none, editable=false)
pU2 = plot(u2, title="ST Up Fan L2", style=plot.style_stepline, display=display.none, editable=false)
pU3 = plot(u3, title="ST Up Fan L3", style=plot.style_stepline, display=display.none, editable=false)
pU4 = plot(u4, title="ST Up Fan L4", style=plot.style_stepline, display=display.none, editable=false)
pU5 = plot(u5, title="ST Up Fan L5", style=plot.style_stepline, display=display.none, editable=false)
 
pD0 = plot(d0, title="ST Down Fan L0",style=plot.style_stepline, display=display.none, editable=false)
pD1 = plot(d1, title="ST Down Fan L1", style=plot.style_stepline,display=display.none, editable=false)
pD2 = plot(d2, title="ST Down Fan L2", style=plot.style_stepline,display=display.none, editable=false)
pD3 = plot(d3, title="ST Down Fan L3", style=plot.style_stepline,display=display.none, editable=false)
pD4 = plot(d4, title="ST Down Fan L4", style=plot.style_stepline,display=display.none, editable=false)
pD5 = plot(d5, title="ST Down Fan L5", style=plot.style_stepline,display=display.none, editable=false)
 
// 5 layers (0→1, 1→2, 2→3, 3→4, 4→5)
fill(pU0, pU1, color = stFillGate ? STB_A2 : na, title="ST Up Fan 1", editable=false)
fill(pU1, pU2, color = stFillGate ? STB_A3 : na, title="ST Up Fan 2", editable=false)
fill(pU2, pU3, color = stFillGate ? STB_A4 : na, title="ST Up Fan 3", editable=false)
fill(pU3, pU4, color = stFillGate ? STB_A5 : na, title="ST Up Fan 4", editable=false)
fill(pU4, pU5, color = stFillGate ? STB_A6 : na, title="ST Up Fan 5", editable=false)
 
fill(pD0, pD1, color = stFillGate ? STR_A2 : na, title="ST Down Fan 1", editable=false)
fill(pD1, pD2, color = stFillGate ? STR_A3 : na, title="ST Down Fan 2", editable=false)
fill(pD2, pD3, color = stFillGate ? STR_A4 : na, title="ST Down Fan 3", editable=false)
fill(pD3, pD4, color = stFillGate ? STR_A5 : na, title="ST Down Fan 4", editable=false)
fill(pD4, pD5, color = stFillGate ? STR_A6 : na, title="ST Down Fan 5", editable=false)
 
 
//======================================================
//==================== BASE SIGNALS ====================
//======================================================
plotshape(showBaseSignals and longCond_base,  "Market LONG",  text="Market is LONG",  style=shape.labeldown,   location=location.abovebar, color=color.green, textcolor=color.white, size=size.tiny)
plotshape(showBaseSignals and shortCond_base, "Market SHORT", text="Market is SHORT", style=shape.labelup,     location=location.belowbar,  color=color.red,  textcolor=color.white, size=size.tiny)
 
// Donchian visuals to STYLE tab
plot(donHigh, "Donchian High", display=display.none)
plot(donLow,  "Donchian Low",  display=display.none)
 
//======================================================
//====================== ENTRY LINE ====================
//======================================================
var line  entryLine = na
var label entryLbl  = na
var float entryPx   = na
var int   entryBar  = na
var color entryCol  = na
 
//======================================================
//============== STOP LOSS & Trailing STOP =============
//======================================================
// --- SL core state ---
var line  slLine     = na
var label slLbl      = na
var int   slStartBar = na
var float slPrice    = na
var color slColor    = na
var float baseSl     = na
 
// --- TF core state ---
const float TP1   = 1.0
const float TP1_5 = 1.5
const float TP2   = 2.0
const float TP3   = 3.0
 
// State
var line  tp1Line  = na
var line  tp15Line = na
var line  tp2Line  = na
var line  tp3Line  = na
var label tp1Lbl   = na
var label tp15Lbl  = na
var label tp2Lbl   = na
var label tp3Lbl   = na
var float tp1Y     = na
var float tp15Y    = na
var float tp2Y     = na
var float tp3Y     = na
var float tpInitRisk = na
 
// buffer used by SL logic (also used by trailing candidate)
slBuf = xATR * 0.10
 
// ----- SL calculators (LONG / SHORT) -----
calcLongSL(_entry) =>
    stFloor  = stActive and stDir == 1 ? upLine : na
    vwFloor  = vwActive ? vwapValue : na
    donFloor = useDonchian ? donLow : ta.lowest(low, swingLen)
    emaFloor = maLong
    atrFloor = xATRTrailingStop
    float sl = na
    sl := not na(atrFloor) and atrFloor  < _entry ? atrFloor : sl
    sl := not na(stFloor)  and stFloor   < _entry ? na(sl) ? stFloor  : math.max(sl, stFloor)  : sl
    sl := not na(vwFloor)  and vwFloor   < _entry ? na(sl) ? vwFloor  : math.max(sl, vwFloor)  : sl
    sl := not na(donFloor) and donFloor  < _entry ? na(sl) ? donFloor : math.max(sl, donFloor) : sl
    sl := not na(emaFloor) and emaFloor  < _entry ? na(sl) ? emaFloor : math.max(sl, emaFloor) : sl
    sl := na(sl) ? _entry - xATR * 1.50 : sl
    sl - slBuf
 
calcShortSL(_entry) =>
    stCeil  = stActive and stDir == -1 ? dnLine : na
    vwCeil  = vwActive ? vwapValue : na
    donCeil = useDonchian ? donHigh : ta.highest(high, swingLen)
    emaCeil = maLong
    atrCeil = xATRTrailingStop
    float sl = na
    sl := not na(atrCeil) and atrCeil  > _entry ? atrCeil : sl
    sl := not na(stCeil)  and stCeil   > _entry ? na(sl) ? stCeil  : math.min(sl, stCeil)  : sl
    sl := not na(vwCeil)  and vwCeil   > _entry ? na(sl) ? vwCeil  : math.min(sl, vwCeil)  : sl
    sl := not na(donCeil) and donCeil  > _entry ? na(sl) ? donCeil : math.min(sl, donCeil) : sl
    sl := not na(emaCeil) and emaCeil  > _entry ? na(sl) ? emaCeil : math.min(sl, emaCeil) : sl
    sl := na(sl) ? _entry + xATR * 1.50 : sl
    sl + slBuf
 
// --- Leg state (reset on every UT flip) ---
var int   tradeDir   = na
bool commitFlip = (utBuy or utSell) and (not drawUtvizOnClose or barstate.isconfirmed)
 
rtFlipAlerts = input.bool(false, "Send real-time alert() on UT flip", group=GROUP_ALERTS, tooltip = "If enabled, the script will trigger a real-time alert() whenever the indicator flips direction (BUY → SELL or SELL → BUY).\n\nThis is useful for traders who want immediate notifications on UT trend changes without having to watch the chart constantly.\n\nRecommended:\n• ON if you are actively monitoring and trading intraday signals.\n• OFF if you only use the indicator as a visual guide or prefer end-of-day analysis.")
var int lastFlipBar = na
if rtFlipAlerts and commitFlip and lastFlipBar != bar_index
    lastFlipBar := bar_index
    string side = utBuy ? "BUY" : "SELL"
    alert("UT FLIP " + side + " | " + syminfo.ticker + " " + timeframe.period + " | Close: " + str.tostring(close), alert.freq_once_per_bar_close)
 
// --- build SL on UT flip ---
var float entry = na
if commitFlip
    if not na(slLine)
        line.delete(slLine), slLine := na
    if not na(slLbl)
        label.delete(slLbl), slLbl := na
 
    // new state
    slStartBar := bar_index
    entry      := close
    baseSl     := utBuy ? calcLongSL(entry) : calcShortSL(entry)
 
    float extra = slExtraTicks * syminfo.mintick
    slPrice    := utBuy ? (baseSl - extra) : (baseSl + extra)
    slColor    := utBuy ? color.aqua : color.orange
 
    // Sanity: keep SL on the correct side of entry (handles rare wrong-side floors)
    float minFloor = xATR * 1.50 + slBuf + extra
    if utBuy and slPrice >= entry
        slPrice := entry - minFloor
    if utSell and slPrice <= entry
        slPrice := entry + minFloor
        
    // reset leg state + TP flags
    legDone    := false
    legDoneBar := na
    tp1Hit := false, tp15Hit := false, tp2Hit := false, tp3Hit := false
 
    // establish trade direction and reset run trackers early (before any inLeg/inLegNow usage)
    tradeDir   := utBuy ? 1 : -1
 
    // initial render
    if slShowVis
        slLine := line.new(slStartBar, slPrice, slStartBar, slPrice, xloc=xloc.bar_index, extend=extend.none, color=slColor, width=1)
        slLbl  := label.new(slStartBar, slPrice, "Suggested Stop Loss", xloc=xloc.bar_index, style=label.style_label_left, textcolor=color.white, color=slColor)
 
// are we  inside an active UT leg?
inLeg = not na(tradeDir)
 
// --- leg start bar (for safe SL-touch detection) ---
var int legStartBar = na
if commitFlip
    legStartBar := bar_index
      
// helper flags for this bar
bool inLegNow = not na(tradeDir)  
int  dirNow   = na(tradeDir) ? 0 : tradeDir 
 
// SL freeze-on-touch (final after all intrabar updates)
if inLegNow and not slFrozen and not na(slPrice) and not na(slStartBar)
    float _tol = syminfo.mintick * 0.51
    bool wickHit = (dirNow == 1 ? low <= slPrice + _tol : high >= slPrice - _tol)
    if wickHit
        slFrozen    := true
        slFrozenBar := bar_index
        legDone     := true
        legDoneBar  := bar_index
        entryFrozen := true
 
        [slLine, slLbl] = ensureSLObjects(slLine, slLbl, slStartBar, slPrice, slColor)
        int x2c_live = (slLimit10 or tpLimit10) ? math.min(bar_index, slStartBar + 10) : bar_index
        int x2c      = capX2(x2c_live)
        if slShowVis and not na(slLine)
            line.set_x2(slLine, x2c)
            line.set_y1(slLine, slPrice)
            line.set_y2(slLine, slPrice)
        if slShowVis and not na(slLbl)
            label.set_x(slLbl, x2c)
            label.set_text(slLbl, "SL Touched ❌")
            label.set_style(slLbl, label.style_label_left)
        if not na(entryLine) and not na(entryBar)
            int xe_live = tpLimit10 ? math.min(bar_index, entryBar + 10) : bar_index
            int xe_cap  = capX2(xe_live)
            line.set_x2(entryLine, xe_cap)
            if not na(entryLbl)
                label.set_x(entryLbl, xe_cap)
                label.set_style(entryLbl, label.style_label_left)
        if not na(tp1Line)
            line.set_x2(tp1Line, x2c)
            if not tp1Frozen
                tp1Frozen := true
            if not na(tp1Lbl)
                label.set_x(tp1Lbl, x2c)
                label.set_style(tp1Lbl, label.style_label_left)
        if not na(tp15Line)
            line.set_x2(tp15Line, x2c)
            if not tp15Frozen
                tp15Frozen := true
            if not na(tp15Lbl)
                label.set_x(tp15Lbl, x2c)
                label.set_style(tp15Lbl, label.style_label_left)
        if not na(tp2Line)
            line.set_x2(tp2Line, x2c)
            if not tp2Frozen
                tp2Frozen := true
            if not na(tp2Lbl)
                label.set_x(tp2Lbl, x2c)
                label.set_style(tp2Lbl, label.style_label_left)
        if not na(tp3Line)
            line.set_x2(tp3Line, x2c)
            if not tp3Frozen
                tp3Frozen := true
            if not na(tp3Lbl)
                label.set_x(tp3Lbl, x2c)
                label.set_style(tp3Lbl, label.style_label_left)
 
// freeze/cap X when SL is frozen or leg is done
if slShowVis and not na(slLine) and (slFrozen or legDone)
    int x2 = capX2(slLimit10 ? math.min(bar_index, slStartBar + 10) : bar_index)
    line.set_x2(slLine, x2)
    if not na(slLbl)
        label.set_x(slLbl, x2)
 
// maintain SL line/label (cap X2 on legDone; do not update Y when frozen/done)
if not na(slLine) and not na(slStartBar)
    int x2_any = slLimit10 ? math.min(bar_index, slStartBar + 10) : bar_index
    line.set_x1(slLine, slStartBar)
    line.set_x2(slLine, capX2(x2_any))
    if slShowVis and not (slFrozen or legDone) and not na(slPrice)
        bool _sl_changed = na(slPrice[1]) or slPrice != slPrice[1]
        if _sl_changed
            line.set_y1(slLine, slPrice)
            line.set_y2(slLine, slPrice)
 
    if slShowVis and not na(slLbl)
        label.set_x(slLbl, capX2(x2_any))
        if not (slFrozen or legDone) and not na(slPrice)
            bool _sl_changed2 = na(slPrice[1]) or slPrice != slPrice[1]
            if _sl_changed2
                label.set_y(slLbl, slPrice)
 
if not slFeatureOn
    if not na(slLine)
        line.delete(slLine), slLine := na
    if not na(slLbl)
        label.delete(slLbl), slLbl := na
 
//======================================================
//==================== TAKE PROFITS ====================
//======================================================
 
clearLine(line l) =>
    if not na(l)
        line.delete(l)
    l
clearLabel(label lb) =>
    if not na(lb)
        label.delete(lb)
    lb
 
// Build new on UT flip
if commitFlip and not na(baseSl)
 
    // logic/state reset
    clearLine(tp1Line),  tp1Line  := na
    clearLine(tp15Line), tp15Line := na
    clearLine(tp2Line),  tp2Line  := na
    clearLine(tp3Line),  tp3Line  := na
    clearLabel(tp1Lbl),  tp1Lbl := na
    clearLabel(tp15Lbl), tp15Lbl := na
    clearLabel(tp2Lbl),  tp2Lbl := na
    clearLabel(tp3Lbl),  tp3Lbl := na
    tp1Y := na, tp15Y := na, tp2Y := na, tp3Y := na
    tp1Frozen := false, tp15Frozen := false, tp2Frozen := false, tp3Frozen := false
 
    tpInitRisk := math.abs(entry - baseSl)
    float _pad = 0.0
    _col = slColor
    int _x2 = bar_index
 
    if utBuy
        tp1Y  := tp1On  ? entry + tpInitRisk * TP1   + _pad : na
        tp15Y := tp15On ? entry + tpInitRisk * TP1_5 + _pad : na
        tp2Y  := tp2On  ? entry + tpInitRisk * TP2   + _pad : na
        tp3Y  := tp3On  ? entry + tpInitRisk * TP3   + _pad : na
    else
        tp1Y  := tp1On  ? entry - tpInitRisk * TP1   - _pad : na
        tp15Y := tp15On ? entry - tpInitRisk * TP1_5 - _pad : na
        tp2Y  := tp2On  ? entry - tpInitRisk * TP2   - _pad : na
        tp3Y  := tp3On  ? entry - tpInitRisk * TP3   - _pad : na
 
    // render (include ✅ if a hit was already recorded)
    if tpShowVis
        if tp1On  and not na(tp1Y)
            tp1Line := line.new(slStartBar, tp1Y, _x2, tp1Y, xloc=xloc.bar_index, extend=extend.none, color=_col, width=1)
            tp1Lbl  := label.new(_x2, tp1Y, (tp1Hit ? "TP1 ✅"  : "TP1"),  xloc=xloc.bar_index, style=label.style_label_right, textcolor=color.white, color=_col, size=size.small)
        if tp15On and not na(tp15Y)
            tp15Line := line.new(slStartBar, tp15Y, _x2, tp15Y, xloc=xloc.bar_index, extend=extend.none, color=_col, width=1)
            tp15Lbl  := label.new(_x2, tp15Y, (tp15Hit ? "TP1.5 ✅" : "TP1.5"), xloc=xloc.bar_index, style=label.style_label_right, textcolor=color.white, color=_col, size=size.small)
        if tp2On  and not na(tp2Y)
            tp2Line := line.new(slStartBar, tp2Y, _x2, tp2Y, xloc=xloc.bar_index, extend=extend.none, color=_col, width=1)
            tp2Lbl  := label.new(_x2, tp2Y, (tp2Hit ? "TP2 ✅"  : "TP2"),  xloc=xloc.bar_index, style=label.style_label_right, textcolor=color.white, color=_col, size=size.small)
        if tp3On  and not na(tp3Y)
            tp3Line := line.new(slStartBar, tp3Y, _x2, tp3Y, xloc=xloc.bar_index, extend=extend.none, color=_col, width=1)
            tp3Lbl  := label.new(_x2, tp3Y, (tp3Hit ? "TP3 ✅"  : "TP3"),  xloc=xloc.bar_index, style=label.style_label_right, textcolor=color.white, color=_col, size=size.small)
 
// Single maintenance block (RENDER ONLY)
int _x2bRaw = tpLimit10 and not na(slStartBar) ? math.min(bar_index, slStartBar + 10) : bar_index
int _x2b    = capX2(_x2bRaw)
 
// TP1
if not na(tp1Line)
    line.set_x2(tp1Line, _x2b)
    if tpShowVis and not (legDone or tp1Frozen) and not na(tp1Y)
        line.set_y1(tp1Line, tp1Y), line.set_y2(tp1Line, tp1Y)
    if tpShowVis and not na(tp1Lbl)
        label.set_x(tp1Lbl, _x2b)
        if not (legDone or tp1Frozen) and not na(tp1Y)
            label.set_y(tp1Lbl, tp1Y)
        label.set_style(tp1Lbl, label.style_label_left)
 
// TP1.5
if not na(tp15Line)
    line.set_x2(tp15Line, _x2b)
    if tpShowVis and not (legDone or tp15Frozen) and not na(tp15Y)
        line.set_y1(tp15Line, tp15Y), line.set_y2(tp15Line, tp15Y)
    if tpShowVis and not na(tp15Lbl)
        label.set_x(tp15Lbl, _x2b)
        if not (legDone or tp15Frozen) and not na(tp15Y)
            label.set_y(tp15Lbl, tp15Y)
        label.set_style(tp15Lbl, label.style_label_left)
 
// TP2
if not na(tp2Line)
    line.set_x2(tp2Line, _x2b)
    if tpShowVis and not (legDone or tp2Frozen) and not na(tp2Y)
        line.set_y1(tp2Line, tp2Y), line.set_y2(tp2Line, tp2Y)
    if tpShowVis and not na(tp2Lbl)
        label.set_x(tp2Lbl, _x2b)
        if not (legDone or tp2Frozen) and not na(tp2Y)
            label.set_y(tp2Lbl, tp2Y)
        label.set_style(tp2Lbl, label.style_label_left)
 
// TP3
if not na(tp3Line)
    line.set_x2(tp3Line, _x2b)
    if tpShowVis and not (legDone or tp3Frozen) and not na(tp3Y)
        line.set_y1(tp3Line, tp3Y), line.set_y2(tp3Line, tp3Y)
    if tpShowVis and not na(tp3Lbl)
        label.set_x(tp3Lbl, _x2b)
        if not (legDone or tp3Frozen) and not na(tp3Y)
            label.set_y(tp3Lbl, tp3Y)
        label.set_style(tp3Lbl, label.style_label_left)
 
// --- TP freeze-on-touch (keeps working even when lines limited to 10 bars) ---
if tpFreezeOnTouch and not legDone and (not na(entryBar) and bar_index > entryBar)
    if tp1On  and not tp1Frozen  and not na(tp1Y)  and ((tradeDir == 1 and high >= tp1Y) or (tradeDir == -1 and low <= tp1Y))
        tp1Frozen := true, tp1Hit := true
        if tpFeatureOn and not na(tp1Lbl)
            label.set_text(tp1Lbl, "TP1 ✅"), label.set_style(tp1Lbl, label.style_label_left)
 
    if tp15On and not tp15Frozen and not na(tp15Y) and ((tradeDir == 1 and high >= tp15Y) or (tradeDir == -1 and low <= tp15Y))
        tp15Frozen := true, tp15Hit := true
        if tpFeatureOn and not na(tp15Lbl)
            label.set_text(tp15Lbl, "TP1.5 ✅"), label.set_style(tp15Lbl, label.style_label_left)
 
    if tp2On  and not tp2Frozen  and not na(tp2Y)  and ((tradeDir == 1 and high >= tp2Y) or (tradeDir == -1 and low <= tp2Y))
        tp2Frozen := true, tp2Hit := true
        if tpFeatureOn and not na(tp2Lbl)
            label.set_text(tp2Lbl, "TP2 ✅"), label.set_style(tp2Lbl, label.style_label_left)
 
    if tp3On  and not tp3Frozen  and not na(tp3Y)  and ((tradeDir == 1 and high >= tp3Y) or (tradeDir == -1 and low <= tp3Y))
        tp3Frozen := true, tp3Hit := true
        if tpFeatureOn and not na(tp3Lbl)
            label.set_text(tp3Lbl, "TP3 ✅"), label.set_style(tp3Lbl, label.style_label_left)
 
// --- close the leg when the farthest enabled TP is touched (unified) ---
float farTP  = na
float nearTP = na
 
// compute farthest TP level in the active direction
if tradeDir == 1
    if tp1On  and not na(tp1Y)
        farTP  := na(farTP) ? tp1Y  : math.max(farTP, tp1Y)
        nearTP := na(nearTP) ? tp1Y  : math.min(nearTP, tp1Y)
    if tp15On and not na(tp15Y)
        farTP  := na(farTP) ? tp15Y : math.max(farTP, tp15Y)
        nearTP := na(nearTP) ? tp15Y : math.min(nearTP, tp15Y)
    if tp2On  and not na(tp2Y)
        farTP  := na(farTP) ? tp2Y  : math.max(farTP, tp2Y)
        nearTP := na(nearTP) ? tp2Y  : math.min(nearTP, tp2Y)
    if tp3On  and not na(tp3Y)
        farTP  := na(farTP) ? tp3Y  : math.max(farTP, tp3Y)
        nearTP := na(nearTP) ? tp3Y  : math.min(nearTP, tp3Y)
else if tradeDir == -1
    if tp1On  and not na(tp1Y)
        farTP  := na(farTP) ? tp1Y  : math.min(farTP, tp1Y)
        nearTP := na(nearTP) ? tp1Y  : math.max(nearTP, tp1Y)
    if tp15On and not na(tp15Y)
        farTP  := na(farTP) ? tp15Y : math.min(farTP, tp15Y)
        nearTP := na(nearTP) ? tp15Y : math.max(nearTP, tp15Y)
    if tp2On  and not na(tp2Y)
        farTP  := na(farTP) ? tp2Y  : math.min(farTP, tp2Y)
        nearTP := na(nearTP) ? tp2Y  : math.max(nearTP, tp2Y)
    if tp3On  and not na(tp3Y)
        farTP  := na(farTP) ? tp3Y  : math.min(farTP, tp3Y)
        nearTP := na(nearTP) ? tp3Y  : math.max(nearTP, tp3Y)
 
// unified detection & handling (symmetric time rule: require bar after entry)
bool canCheckFar = not na(entryBar) and bar_index > entryBar and not na(farTP) and not legDone
bool touchedFar  = canCheckFar and ((tradeDir == 1 and high >= farTP) or (tradeDir == -1 and low <= farTP))
 
if touchedFar
    // mark all closer/equal TPs as hit/frozen (ensures TP1/TP2 get ✅ when TP3 is hit directly)
    if tradeDir == 1
        if tp1On  and not tp1Frozen  and not na(tp1Y)  and tp1Y  <= farTP
            tp1Frozen := true, tp1Hit := true
            if tpFeatureOn and not na(tp1Lbl)
                label.set_text(tp1Lbl, "TP1 ✅"), label.set_style(tp1Lbl, label.style_label_left)
        if tp15On and not tp15Frozen and not na(tp15Y) and tp15Y <= farTP
            tp15Frozen := true, tp15Hit := true
            if tpFeatureOn and not na(tp15Lbl)
                label.set_text(tp15Lbl, "TP1.5 ✅"), label.set_style(tp15Lbl, label.style_label_left)
        if tp2On  and not tp2Frozen  and not na(tp2Y)  and tp2Y  <= farTP
            tp2Frozen := true, tp2Hit := true
            if tpFeatureOn and not na(tp2Lbl)
                label.set_text(tp2Lbl, "TP2 ✅"), label.set_style(tp2Lbl, label.style_label_left)
        if tp3On  and not tp3Frozen  and not na(tp3Y)  and tp3Y  <= farTP
            tp3Frozen := true, tp3Hit := true
            if tpFeatureOn and not na(tp3Lbl)
                label.set_text(tp3Lbl, "TP3 ✅"), label.set_style(tp3Lbl, label.style_label_left)
    else
        if tp1On  and not tp1Frozen  and not na(tp1Y)  and tp1Y  >= farTP
            tp1Frozen := true, tp1Hit := true
            if tpFeatureOn and not na(tp1Lbl)
                label.set_text(tp1Lbl, "TP1 ✅"), label.set_style(tp1Lbl, label.style_label_left)
        if tp15On and not tp15Frozen and not na(tp15Y) and tp15Y >= farTP
            tp15Frozen := true, tp15Hit := true
            if tpFeatureOn and not na(tp15Lbl)
                label.set_text(tp15Lbl, "TP1.5 ✅"), label.set_style(tp15Lbl, label.style_label_left)
        if tp2On  and not tp2Frozen  and not na(tp2Y)  and tp2Y  >= farTP
            tp2Frozen := true, tp2Hit := true
            if tpFeatureOn and not na(tp2Lbl)
                label.set_text(tp2Lbl, "TP2 ✅"), label.set_style(tp2Lbl, label.style_label_left)
        if tp3On  and not tp3Frozen  and not na(tp3Y)  and tp3Y  >= farTP
            tp3Frozen := true, tp3Hit := true
            if tpFeatureOn and not na(tp3Lbl)
                label.set_text(tp3Lbl, "TP3 ✅"), label.set_style(tp3Lbl, label.style_label_left)
 
    // freeze SL/ENTRY and end leg
    legDone     := true
    legDoneBar  := bar_index
    slFrozen    := true
    entryFrozen := true
 
    // lock ENTRY X at freeze bar (respect 10-bar limit)
    if not na(entryLine) and not na(entryBar)
        bool limit10 = tpLimit10
        int  x2f = limit10 ? math.min(bar_index, entryBar + 10) : bar_index
        line.set_x2(entryLine, x2f)
        if not na(entryLbl)
            label.set_x(entryLbl, x2f)
 
    // update SL label text
    if slFeatureOn and not na(slLbl)
        label.set_text(slLbl, "SL Frozen"), label.set_style(slLbl, label.style_label_left)
 
// capture entry state on flip (logic always)
if commitFlip
    if not na(entryLine)
        line.delete(entryLine), entryLine := na
    if not na(entryLbl)
        label.delete(entryLbl), entryLbl := na
    entryPx  := close
    entryBar := bar_index
    entryCol := slColor
    entryFrozen := false
 
    // create immediately when feature is ON (independent of utVizGate)
    if entryFeatureOn
        entryLine := line.new(entryBar, entryPx, entryBar, entryPx,
                              xloc=xloc.bar_index, extend=extend.none, color=entryCol, width=1)
        entryLbl  := label.new(entryBar, entryPx, "ENTRY",
                               xloc=xloc.bar_index, style=label.style_label_right,
                               textcolor=color.white, color=entryCol, size=size.small)
 
// render (gated)
if not na(entryLine) and not na(entryBar) and not na(entryPx)
    bool limit10  = tpLimit10
    int  x2_live  = limit10 ? math.min(bar_index, entryBar + 10) : bar_index
    int  x2_frozen = not na(legDoneBar) ? (limit10 ? math.min(legDoneBar, entryBar + 10) : legDoneBar) : x2_live
    int  x2_final  = (entryFrozen or legDone) ? x2_frozen : x2_live
    line.set_x2(entryLine, x2_final)
    if entryShowVis and not (entryFrozen or legDone)
        line.set_x1(entryLine, entryBar)
        line.set_y1(entryLine, entryPx)
        line.set_y2(entryLine, entryPx)
    if entryShowVis
        if na(entryLbl)
            entryLbl := label.new(entryBar, entryPx, "ENTRY",
                                  xloc=xloc.bar_index, style=label.style_label_right,
                                  textcolor=color.white, color=entryCol, size=size.small)
        if not (entryFrozen or legDone)
            label.set_y(entryLbl, entryPx)
        label.set_x(entryLbl, x2_final)
        label.set_style(entryLbl, label.style_label_left)
        label.set_text(entryLbl, "ENTRY")
else
    if not entryShow and not na(entryLine)
        line.delete(entryLine), entryLine := na
    if not entryShow and not na(entryLbl)
        label.delete(entryLbl), entryLbl := na
 
//======================================================
//======================= ALERTS =======================
//======================================================
utBuyBar  = utBuy
utSellBar = utSell
alertcondition(utBuyBar,  title="✅Momentum Buy Signal✅",  message="✅Momentum Buy Signal✅  | {{ticker}} {{interval}} | Close: {{close}}")
alertcondition(utSellBar, title="❌Momentum Sell Signal❌", message="❌Momentum Sell Signal❌ | {{ticker}} {{interval}} | Close: {{close}}")
alertcondition(longCond_base,  title="Base Long (with optional filters)",  message="Base Long")
alertcondition(shortCond_base, title="Base Short (with optional filters)", message="Base Short")
 
// Optional badges (current TF; reuse labels instead of delete/new each bar)
var label rsiLbl = na
var label adxLbl = na
 
if barstate.islast // and barstate.isconfirmed
    // RSI badge
    if showRsiBadge
        // thresholds
        float _bMin = useClassicRSIBias ?  0.0  : math.min(rsiBuyMin,  rsiBuyMax)
        float _bMax = useClassicRSIBias ? 30.0  : math.max(rsiBuyMin,  rsiBuyMax)
        float _sMin = useClassicRSIBias ? 70.0  : math.min(rsiSellMin, rsiSellMax)
        float _sMax = useClassicRSIBias ? 100.0 : math.max(rsiSellMin, rsiSellMax)
 
        bool longZone    = (rsiV >  _bMin and rsiV <  _bMax)
        bool shortZone   = (rsiV >= _sMin and rsiV <= _sMax)
        bool neutralRSI  = not (longZone or shortZone)
 
        color rsiBg = neutralRSI ? color.new(color.yellow, 0) : longZone ? color.new(color.green, 0) : color.new(color.red, 0)
        color rsiFg = neutralRSI ? color.black : color.white
        string rsiTxt = "RSI " + str.tostring(rsiV, "#.##") + (neutralRSI ? " (neutral)" : longZone ? " (long zone)" : " (short zone)")
 
        if na(rsiLbl)
            rsiLbl := label.new(bar_index, high, "", style=label.style_label_down, textcolor=rsiFg, color=rsiBg)
 
        // maintain: move to current bar and update visuals (same pattern as ADX)
        label.set_x(rsiLbl, bar_index)
        label.set_y(rsiLbl, high)
        label.set_style(rsiLbl, label.style_label_down)
        label.set_size(rsiLbl, size.small)
        label.set_color(rsiLbl, rsiBg)
        label.set_textcolor(rsiLbl, rsiFg)
        label.set_text(rsiLbl, rsiTxt)
 
    else
        if not na(rsiLbl)
            label.delete(rsiLbl), rsiLbl := na
 
    // ADX badge
    if showAdxBadge //and barstate.isconfirmed
        color adxBg = adxVal >= adxMin ? color.new(color.lime, 0) : color.new(color.red, 0)
        if na(adxLbl)
            adxLbl := label.new(bar_index, low, "", style=label.style_label_up, textcolor=color.white, color=adxBg)
        label.set_x(adxLbl, bar_index)
        label.set_y(adxLbl, low)
        label.set_color(adxLbl, adxBg)
        label.set_style(adxLbl, label.style_label_up)
        label.set_size(adxLbl, size.small)
        label.set_text(adxLbl, "ADX " + str.tostring(nz(adxVal), "#.##"))
    else
        if not na(adxLbl)
            label.delete(adxLbl), adxLbl := na
 
// --- ΔOpen% state and computation (last-bar only) ---
var label deltaOpenLbl = na
const int DELTA_X_BARS = 1
float yMid = (high + low) * 0.5
 
// Determine reference open based on timeframe
float ref_open = na
if timeframe.isintraday
    // Intraday: use today's session open (handles extended hours)
    ref_open := request.security(syminfo.tickerid, "D", open, barmerge.gaps_off, barmerge.lookahead_off)
else
    // HTF (D/W/M): always use today's open (last calendar day)
    ref_open := request.security(syminfo.tickerid, "D", open, barmerge.gaps_off, barmerge.lookahead_off)
 
// Render only on the very last bar
if showDeltaOpen and barstate.islast and not na(ref_open) and ref_open != 0
    float d_pct = (close - ref_open) / ref_open * 100.0
    string sgn = d_pct >= 0 ? "+" : ""
    string txt = "Δ Chg from Open " + sgn + str.tostring(d_pct, "0." + str.repeat("0", deltaOpenDec)) + "%"
 
    color fg = color.white
    color bg = d_pct >= 0 ? color.rgb(1,131,6) : color.red
 
    if na(deltaOpenLbl)
        deltaOpenLbl := label.new(bar_index, yMid, txt, xloc=xloc.bar_index, style=label.style_label_left, textcolor=fg, color=bg, size=size.normal)
 
    label.set_x(deltaOpenLbl, bar_index + DELTA_X_BARS)
    label.set_y(deltaOpenLbl, yMid)
    label.set_text(deltaOpenLbl, txt)
    label.set_textcolor(deltaOpenLbl, fg)
    label.set_color(deltaOpenLbl, bg)
else
    if not na(deltaOpenLbl)
        label.delete(deltaOpenLbl), deltaOpenLbl := na
 
//======================================================
//============== CANDLESTICK PATTERNS ==================
//======================================================
 
// Helper: body size as % of price
if showCandlePatterns
    
    float bodySize = math.abs(close - open)
    float bodyPct = close != 0 ? (bodySize / close * 100.0) : 0.0
    bool bodyMeetsMin = bodyPct >= minCandleBodyPct
 
// === MOMENTUM REVERSAL PATTERN ===
    bool bullEngulf = false
    if showBullEngulf and bar_index > 0 and bodyMeetsMin
        float rsiVal = ta.rsi(close, 5)
        bool oversold = rsiVal < 35
        bool momentumShift = close > open and volume > ta.sma(volume, 10) * 1.3
        bool priceExpansion = (high - low) > ta.atr(5) * 1.5
        bullEngulf := oversold and momentumShift and priceExpansion
 
// === EXHAUSTION TOP PATTERN ===
    bool bearEngulf = false
    if  showBearEngulf and bar_index > 0 and bodyMeetsMin
        float rsiVal = ta.rsi(close, 5)
        bool overbought = rsiVal > 65
        bool volumeExhaustion = volume < ta.sma(volume, 10) * 0.8
        bool priceRejection = high > ta.highest(high[1], 5) and close < (high + low) / 2
        bool momentumLoss = ta.mom(close, 3) < 0
        bearEngulf := overbought and volumeExhaustion and priceRejection and momentumLoss
 
// === SUPPORT BOUNCE PATTERN ===
    bool hammer = false
    if showHammer and bodyMeetsMin
        float atrVal = ta.atr(10)
        bool nearSupport = low <= ta.lowest(low[1], 20) * 1.02
        bool priceRecovery = close > (high + low * 2) / 3
        float buyPressure = (close - low) / (high - low + 0.0001)
        bool volumeIncrease = volume > ta.sma(volume, 5)
        bool rsiTurning = ta.rsi(close, 7) > ta.rsi(close[1], 7)
        hammer := nearSupport and priceRecovery and buyPressure > 0.6 and volumeIncrease and rsiTurning
 
    // === RESISTANCE REJECTION PATTERN  ===
    bool shootingStar = false
    if showShootingStar and bodyMeetsMin
        float atrVal = ta.atr(10)
        bool nearResistance = high >= ta.highest(high[1], 20) * 0.98
        bool priceRejected = close < (low + high * 2) / 3
        float sellPressure = (high - close) / (high - low + 0.0001)
        bool volumeFade = volume < ta.sma(volume, 5) * 1.1
        bool rsiDeclining = ta.rsi(close, 7) < ta.rsi(close[1], 7)
        shootingStar := nearResistance and priceRejected and sellPressure > 0.6 and volumeFade and rsiDeclining
 
    // === MOMENTUM REVERSAL BOTTOM ===
    bool morningStar = false
    if showMorningStar and bar_index > 2 and bodyMeetsMin
        // Three-bar momentum shift detection
        float momentum3bar = (close - close[2]) / close[2] * 100
        bool oversoldZone = ta.rsi(close[2], 14) < 35
        bool volumePattern = volume[1] < ta.sma(volume, 20) * 0.7 and volume > ta.sma(volume, 20) * 1.2
        bool macdTurning = ta.crossover(macdLine, signalLine)
        bool priceStructure = low[1] < low[2] and close > high[1]
        morningStar := oversoldZone and momentum3bar > 1.5 and volumePattern and priceStructure and (macdTurning or close > maMedium)
 
    // === MOMENTUM REVERSAL TOP ===
    bool eveningStar = false
    if showEveningStar and bar_index > 2 and bodyMeetsMin
        // Three-bar momentum shift detection
        float momentum3bar = (close - close[2]) / close[2] * 100
        bool overboughtZone = ta.rsi(close[2], 14) > 65
        bool volumePattern = volume[1] < ta.sma(volume, 20) * 0.7 and volume > ta.sma(volume, 20) * 1.2
        bool macdDeclining = ta.crossunder(macdLine, signalLine)
        bool priceStructure = high[1] > high[2] and close < low[1]
        eveningStar := overboughtZone and momentum3bar < -1.5 and volumePattern and priceStructure and (macdDeclining or close < maMedium)
 
    // Custom pattern visualization
    if bullEngulf
        label.new(bar_index, low, "🔺", yloc=yloc.belowbar, style=label.style_none, color=color.new(color.green, 100), textcolor=color.green, size=size.large, tooltip="Momentum Reversal\n\nOversold + Volume surge + Price expansion\nConsider long entry with proper risk management")
                
    if bearEngulf
        label.new(bar_index, high, "🔻", yloc=yloc.abovebar, style=label.style_none,  color=color.new(color.red, 100), textcolor=color.red, size=size.large, tooltip="Exhaustion Top\n\nOverbought + Volume exhaustion + Price rejection\nConsider taking profits or short entry")
                
    if hammer
        label.new(bar_index, low, "🔨", yloc=yloc.belowbar, style=label.style_none, color=color.new(color.yellow, 100), textcolor=color.yellow, size=size.large, tooltip="Support Bounce\n\nPrice at support + Recovery + Volume confirmation\nWait for next bar confirmation")
                
    if shootingStar
        label.new(bar_index, high, "🌠", yloc=yloc.abovebar, style=label.style_none, color=color.new(color.orange, 100), textcolor=color.orange, size=size.large, tooltip="Resistance Rejection\n\nPrice at resistance + Rejection + Volume fade\nPotential reversal warning")
                
    if morningStar
        label.new(bar_index, low, "🌅", yloc=yloc.belowbar, style=label.style_none, color=color.new(color.lime, 100), textcolor=color.lime, size=size.large, tooltip="Momentum Bottom Reversal\n\n3-bar reversal from oversold\nStrong bullish signal with volume")
                
    if eveningStar
        label.new(bar_index, high, "🌆", yloc=yloc.abovebar, style=label.style_none, color=color.new(color.maroon, 100), textcolor=color.maroon, size=size.large, tooltip="Momentum Top Reversal\n\n3-bar reversal from overbought\nStrong bearish signal with volume")
 
//======================================================
//==================== BIAS TABLE ======================
//======================================================
var table fullTable = na
 
_hdrBg = tableBgColor
 
// Daily refresh gate for HTF work (cache-based) - uses real calendar day change
var int _last_update_day = na
int current_day = dayofmonth
bool bias_htf_update = na(_last_update_day) or current_day != _last_update_day
if bias_htf_update
    _last_update_day := current_day
 
// Returns [cached_value, updated_this_bar] per unique key (TF+bars)
// Helper function that calculates the slope (runs in requested TF context)
bias_slope_calc(int bars) =>
    float lr_now = ta.linreg(close, bars, 0)
    float lr_prev = ta.linreg(close, bars, 1)
    lr_now - lr_prev
 
bias_step_cached(string tf, int bars, string key) =>
    var string[] _keys = array.new_string()
    var float[]  _vals = array.new_float()
    var int[]    _times = array.new_int()
 
    int idx = array.indexof(_keys, key)
    if idx == -1
        array.push(_keys, key)
        array.push(_vals, na)
        array.push(_times, na)
        idx := array.size(_keys) - 1
 
    float cached = array.get(_vals, idx)
    int   cached_time = array.get(_times, idx)
    
    // Get the timestamp of the last completed bar of the requested TF
    int ref_time = request.security(syminfo.tickerid, tf, time[1], barmerge.gaps_off, barmerge.lookahead_off)
    
    // Only update if we have a NEW completed bar (time changed)
    bool need_update_local = na(cached_time) or ref_time != cached_time
 
    float step_close = na
    if need_update_local
        // Now calculate slope at the SAME timestamp for all chart TFs
        step_close := request.security(
             syminfo.tickerid, tf,
             bias_slope_calc(bars)[1],
             barmerge.gaps_off, barmerge.lookahead_off)
        
        array.set(_times, idx, ref_time)
 
    var bool updated = false
    if not na(step_close)
        array.set(_vals, idx, step_close)
        cached := step_close
        updated := true
 
    [cached, updated]
 
// Map numeric slope to label
bias_label_from(float v) =>
    na(v) ? "NEUTRAL⚠️" : v > 0 ? "BULLISH✔️" : v < 0 ? "BEARISH✖️" : "NEUTRAL⚠️"
 
// Parse session string like "0930-1600" or "0900-1130,1230-1500" into total minutes
sess_minutes(string s) =>
    int total = 0
    string[] segs = str.split(s, ",")
    for i = 0 to array.size(segs) - 1
        string seg = array.get(segs, i)
        string[] ends = str.split(seg, "-")
        if array.size(ends) == 2
            string a = array.get(ends, 0)
            string b = array.get(ends, 1)
 
            float ahf = str.tonumber(str.substring(a, 0, 2))
            float amf = str.tonumber(str.substring(a, 2, 4))
            float bhf = str.tonumber(str.substring(b, 0, 2))
            float bmf = str.tonumber(str.substring(b, 2, 4))
 
            int ah = na(ahf) ? 0 : int(ahf)
            int am = na(amf) ? 0 : int(amf)
            int bh = na(bhf) ? 0 : int(bhf)
            int bm = na(bmf) ? 0 : int(bmf)
 
            total += (bh * 60 + bm) - (ah * 60 + am)
 
    total == 0 ? 390 : total
 
// Helpers
getEmoji(_ok) => _ok ? "🟩" : "🟥"
const color BG_HEADER = color.new(color.rgb(35,38,43), 0)
const color BG_CELL_DARK = color.new(color.black, 10)
biasBg(b) =>
    str.startswith(b, "ABOVE") ? color.rgb(1,131,6) : str.startswith(b, "BELOW") ? color.rgb(209,0,0) : b == "BULLISH✔️" ? color.rgb(1,131,6) : b == "BEARISH✖️" ? color.rgb(209,0,0) :color.rgb(160,159,159)
biasFg(b) => color.white
const int WARMUP_BARS = 600
int adaptiveWarmup = timeframe.isdwm ? 
     (timeframe.period == "M" ? 60 : timeframe.period == "W" ? 120 : 250) : 
     WARMUP_BARS
 
orb_to_bias(s) =>
    str.startswith(s, "ABOVE") ? "BULLISH✔️" : str.startswith(s, "BELOW") ? "BEARISH✖️" : "Not Open" 
 
getBias(tf, shortLen) =>
    [emaS, emaL] = request.security(syminfo.tickerid, tf, [ta.ema(close, shortLen), ta.ema(close, shortLen * 2)], barmerge.gaps_off, barmerge.lookahead_off)
    emaS > emaL ? "BULLISH✔️" : emaS < emaL ? "BEARISH✖️" : "NEUTRAL⚠️"
 
// === Deferred headline biases; computed only when the table updates ===
var string bias3D      = na
var string biasWeek    = na
var string biasMon     = na
var string biasQuarter = na
 
// === Vix Settings
const float VIX_LOW  = 18.0
const float VIX_HIGH = 22.0
var string vixBias   = "NEUTRAL⚠️"
 
// === Behavioral settings
tf1mOn  = input.bool(true,  "1 minute",  group=GROUP_TF, inline="tf1")
tf5mOn  = input.bool(true,  "5 minutes",  group=GROUP_TF, inline="tf1")
tf15mOn = input.bool(true,  "15 minutes", group=GROUP_TF, inline="tf1")
tf30mOn = input.bool(true,  "30 minutes", group=GROUP_TF, inline="tf2")
tf1hOn  = input.bool(true,  "1 hour",  group=GROUP_TF, inline="tf2")
tf2hOn  = input.bool(true,  "2 hours",  group=GROUP_TF, inline="tf2")
tf4hOn  = input.bool(true,  "4 hours",  group=GROUP_TF, inline="tf2")
 
// guards for the bias table: show only when enabled, and skip on D/W/M if that option is on
bool bias_guard = showTable and not (hideBiasOnDplus and timeframe.isdwm)
 
// Dongle: skip BIAS table and all its computations on Daily+ when ON
var string _lastPos = na
var int _lastMask = na
tablePosition = switch tablePosLabel
    "Top Left"       => position.top_left
    "Top Right"      => position.top_right
    "Middle Left"    => position.middle_left
    "Middle Right"   => position.middle_right
    "Bottom Left"    => position.bottom_left
    "Bottom Right"   => position.bottom_right
    => position.top_right
 
int tfEnabledCount = (tf1mOn ? 1 : 0) + (tf5mOn ? 1 : 0) + (tf15mOn ? 1 : 0) + (tf30mOn ? 1 : 0) + (tf1hOn ? 1 : 0) + (tf2hOn ? 1 : 0) + (tf4hOn ? 1 : 0)
int curMask = timeframe.isdwm ? 999 : (tf1mOn ? 1 : 0) + (tf5mOn ? 2 : 0) + (tf15mOn ? 4 : 0) + (tf30mOn ? 8 : 0) + (tf1hOn ? 16 : 0) + (tf2hOn ? 32 : 0) + (tf4hOn ? 64 : 0)
int dynCols = 1 + (timeframe.isdwm ? 3 : tfEnabledCount) + 1
 
if bias_guard
    if na(fullTable) or tablePosLabel != _lastPos or na(_lastMask) or curMask != _lastMask
        _lastPos := tablePosLabel
        _lastMask := curMask
        if not na(fullTable)
            table.delete(fullTable)
        fullTable := table.new(tablePosition, dynCols, 20, border_width=0)
else
    if not na(fullTable)
        table.delete(fullTable)
        fullTable := na
 
// Dynamic arrays sized to the number/order of active TFs
var bool[] crossDyn     = array.new_bool()
var bool[] above200Dyn  = array.new_bool()
var int[]  macdStateDyn = array.new_int()
var bool[] vwapAboveDyn = array.new_bool()
var bool[] zlsmaUpDyn   = array.new_bool()
var bool[] adxStrongDyn = array.new_bool()
var int[]  stStateDyn   = array.new_int()
var int[]  rsiStateDyn  = array.new_int()
 
// HTF cache - stores confirmed bar data to avoid recalculation
var bool[] crossDyn_htfCache     = array.new_bool()
var bool[] above200Dyn_htfCache  = array.new_bool()
var int[]  macdStateDyn_htfCache = array.new_int()
var bool[] vwapAboveDyn_htfCache = array.new_bool()
var bool[] zlsmaUpDyn_htfCache   = array.new_bool()
var bool[] adxStrongDyn_htfCache = array.new_bool()
var int[]  stStateDyn_htfCache   = array.new_int()
var int[]  rsiStateDyn_htfCache  = array.new_int()
 
// Clears all dynamic arrays used by the BIAS table before each refresh
clear_bias_arrays() =>
    array.clear(crossDyn)
    array.clear(above200Dyn)
    array.clear(macdStateDyn)
    array.clear(vwapAboveDyn)
    array.clear(zlsmaUpDyn)
    array.clear(adxStrongDyn)
    array.clear(stStateDyn)
    array.clear(rsiStateDyn)
 
// ---- Active RSI thresholds (respect the 70/30 checkbox) ----
float bMin = useClassicRSIBias ?  0.0 : math.min(rsiBuyMin,  rsiBuyMax)
float bMax = useClassicRSIBias ? 30.0 : math.max(rsiBuyMin,  rsiBuyMax)
float sMin = useClassicRSIBias ? 70.0 : math.min(rsiSellMin, rsiSellMax)
float sMax = useClassicRSIBias ? 100.0: math.max(rsiSellMin, rsiSellMax)
 
//var int[] zlsmaState = array.new_int(6, 0)
 
// Tooltip string for the RSI row (single line)
var string rsiTip = ""
rsiTip := "RSI zones:\nLong: " + str.tostring(bMin) + "–" + str.tostring(bMax) + "\nShort: " + str.tostring(sMin) + "–" + str.tostring(sMax)
 
// Anchored VWAP for the BIAS table (time-anchors only; no event anchors)
anchored_vwap_basic(string how, float src) =>
    var float sum_pv = 0.0
    var float sum_v  = 0.0
 
    // Normalize aliases: allow "D"/"W"/"M" to map to time-anchors
    string key = how == "D" ? "Day" : how == "W" ? "Week" : how == "M" ? "Month" : how
 
    // Reset accumulator when the selected anchor boundary is hit
    bool reset = anchor_reset(key)
    if reset
        sum_pv := 0.0
        sum_v  := 0.0
 
    // Accumulate and return anchored VWAP
    sum_pv += src * volume
    sum_v  += volume
    sum_v != 0 ? sum_pv / sum_v : na
 
// Returns "close > VWAP" boolean for a given TF, honoring HTF minimum anchors:
// D→Week, W→Month, M→Year. When use_anchor is ON, the chosen anchor is clamped
// to that minimum. Intraday keeps user's choice or plain VWAP.
vwap_above_for_tf(string _tf, float _close, bool use_anchor, string user_anchor, float _srcVWAP) =>
    bool _isD = _tf == "D"
    bool _isW = _tf == "W"
    bool _isM = _tf == "M"
    bool _isIntraday = not (_isD or _isW or _isM)
 
    float vwap_now = na
    if _isIntraday
        vwap_now := request.security(syminfo.tickerid, _tf, use_anchor ? anchored_vwap_basic(user_anchor, _srcVWAP) : ta.vwap)
    else
        string min_anchor = _isD ? "Week" : _isW ? "Month" : "Year"
        string desired = use_anchor ? user_anchor : min_anchor
        int r_des = desired == "Session" ? 0 : desired == "Day" ? 1 : desired == "Week" ? 2 : desired == "Month" ? 3 : desired == "Quarter" ? 4 : desired == "Year" ? 5 : 1
        int r_min = _isD ? 2 : _isW ? 3 : 5
        string final_anchor = r_des < r_min ? min_anchor : desired
        vwap_now := request.security(syminfo.tickerid, _tf, anchored_vwap_basic(final_anchor, _srcVWAP))
 
    not na(vwap_now) and _close > vwap_now
 
/// --- helpers
macd_line(src, fast, slow, sig)  => [l, s, _] = ta.macd(src, fast, slow, sig), l
macd_signal(src, fast, slow, sig)=> [l, s, _] = ta.macd(src, fast, slow, sig), s
 
// One-liner state:  1 = long zone (buy), -1 = short zone (sell), 0 = neutral
rsi_state_inline(float v, float _bMin, float _bMax, float _sMin, float _sMax) =>
    na(v) ? 0 : (v >= _sMin and v <= _sMax ? -1 : (v > _bMin and v < _bMax ? 1 : 0))
 
// --- SHIMS for bias table ---
 
st_state_tf(_src, _atrPeriod, _mult, _useATR, _neutralBars) =>
    float _tr    = ta.tr
    float _atr   = _useATR ? ta.atr(_atrPeriod) : ta.sma(_tr, _atrPeriod)
    float _upRaw = _src - _mult * _atr
    float _dnRaw = _src + _mult * _atr
 
    var float _upL = na
    var float _dnL = na
    _upL := na(_upL[1]) ? _upRaw : (close[1] > _upL[1] ? math.max(_upRaw, _upL[1]) : _upRaw)
    _dnL := na(_dnL[1]) ? _dnRaw : (close[1] < _dnL[1] ? math.min(_dnRaw, _dnL[1]) : _dnRaw)
 
    var int _dir = na
    _dir := na(_dir[1]) ? (close >= _src ? 1 : -1) : _dir[1]
    _dir := _dir == -1 and close > _dnL[1] ?  1 : _dir ==  1 and close < _upL[1] ? -1 : _dir 
 
    int  _ago = ta.barssince(_dir != _dir[1])
    bool _neu = _neutralBars > 0 and _ago >= 0 and _ago < int(_neutralBars)
    _neu ? 0 : _dir
 
// Tooltip for the ST row
var string stTip = "Supertrend: green=up, red=down, neutral for N bars after a flip."
 
// Build tuple in ONE line (no line breaks)
pack_expr() =>
    bool requireConfirmed = not timeframe.isdwm
    bool is_confirmed = barstate.isconfirmed or barstate.islast or not barstate.isrealtime
    // Detect which rows are enabled to avoid unnecessary calculations
    bool needEMA   = rowMA or rowMA200
    bool needMACD  = rowMACD
    bool needVWAP  = rowVWAP
    bool needZLSMA = rowZLSMA
    bool needST    = rowST
    bool needRSI   = rowRSI
    bool needADX   = rowADX
 
    // If intraday and not confirmed, return NA to prevent repainting
    if requireConfirmed and not is_confirmed
        [na, na, na, na, na, na, na, na, na, na, na, na]
    else
        float es   = na
        float el   = na
        float e200 = na
        float cl   = na
        if needEMA
            es   := maSwitch(close, maShortLen, maFastType)
            el   := maSwitch(close, maMedLen,  maMedType)
            e200 := maSwitch(close, ma200Len,  maLongType)
            cl   := close
 
        [mL, mS, _mh] = ta.macd(macdSrc, macdFast, macdSlow, macdSig)
 
        float z  = na
        float zp = na
        if needZLSMA
            z  := zlsma_calc(zlsmaSrc, zlsmaLength, zlsmaOffset)
            zp := z[1]
 
        float a = na
        if needADX
            [a_calc, _, _] = dmi_local(adxLen)
            a := a_calc
 
        float r = na
        if needRSI
            r := ta.rsi(rsiSrcM, rsiLenM)
 
        float v = na
        if needVWAP
            string tfp = timeframe.period
            bool isD = tfp == "D"
            bool isW = tfp == "W"
            bool isM = tfp == "M"
            bool isIntraday = not (isD or isW or isM)
 
            if isIntraday
                v := useAnchoredVWAPinTable ? anchored_vwap_basic(anchor, srcVWAP) : ta.vwap
            else
                string min_anchor = isD ? "Week" : isW ? "Month" : "Year"
                string desired = useAnchoredVWAPinTable ? anchor : min_anchor
                int r_des = desired == "Session" ? 0 : desired == "Day" ? 1 : desired == "Week" ? 2 : desired == "Month" ? 3 : desired == "Quarter" ? 4 : desired == "Year" ? 5 : 1
                int r_min = min_anchor == "Week" ? 2 : min_anchor == "Month" ? 3 : 5
                string final_anchor = r_des < r_min ? min_anchor : desired
                v := anchored_vwap_basic(final_anchor, srcVWAP)
 
        float st = na
        st := needST ? float(st_state_tf(stSrc, stAtrPeriod, stMult, stUseATR, stNeutralBars)) : na
 
        [es, el, e200, cl, mL, mS, z, zp, a, r, v, st]
 
// Single-call per TF (also ONE line)
pack_all(tf) => 
    request.security(syminfo.tickerid, tf, pack_expr(), 
                     barmerge.gaps_off, 
                     barmerge.lookahead_off, 
                     calc_bars_count = adaptiveWarmup,
                     ignore_invalid_symbol = true)
 
collectTF(string _tf) =>
    [es, el, e200, cl, mL, mS, z, zp, a, r, v, st] = pack_all(_tf)
    if rowMA or rowMA200
        array.push(crossDyn, es > el)
        array.push(above200Dyn, cl > e200)
    if rowMACD
        array.push(macdStateDyn, (na(mL) or na(mS)) ? 0 : (mL > mS ? 1 : -1))
    if rowVWAP
        array.push(vwapAboveDyn, vwap_above_for_tf(_tf, cl, useAnchoredVWAPinTable, anchor, srcVWAP))
    if rowZLSMA
        array.push(zlsmaUpDyn, z > zp)
    if rowST
        array.push(stStateDyn, int(st))
    if rowRSI
        array.push(rsiStateDyn, rsi_state_inline(r, bMin, bMax, sMin, sMax))
    if rowADX
        array.push(adxStrongDyn, a >= adxMin)
 
// Collect for D/W/M timeframes (must stay as literals)
collect_dwm() =>
    collectTF("D")
    collectTF("W")
    collectTF("M")
 
 
// Collect for intraday timeframes (each call keeps a literal TF)
collect_intraday(bool tf1mOn, bool tf5mOn, bool tf15mOn, bool tf30mOn, bool tf1hOn, bool tf2hOn, bool tf4hOn) =>
    if tf1mOn
        collectTF("1")
    if tf5mOn
        collectTF("5")
    if tf15mOn
        collectTF("15")
    if tf30mOn
        collectTF("30")
    if tf1hOn
        collectTF("60")
    if tf2hOn
        collectTF("120")
    if tf4hOn
        collectTF("240")
 
//=== ORB session preset (hours are interpreted in the symbol's EXCHANGE timezone)
string sessPreset = input.string(defval="New York (NYSE 09:30-16:00)", title="ORB session preset", group=GROUP_ORB, options=["New York (NYSE 09:30-16:00)", "London (LSE 08:00-16:30)", "Tokyo (TSE 09:00-11:30,12:30-15:00)", "Custom"], tooltip="Presets are in the exchange timezone. For exact local hours use Custom. (Crypto/24h disabled)")
string sessCustom = input.session("0930-1600", "Custom ORB hours", group=GROUP_ORB, tooltip="Set your desired time for market session. Full-day (24/7) sessions are not supported.")
 
// Map preset -> Pine session string (no Crypto)
string sessStrRaw =
     sessPreset == "New York (NYSE 09:30-16:00)"         ? "0930-1600" :
     sessPreset == "London (LSE 08:00-16:30)"            ? "0800-1630" :
     sessPreset == "Tokyo (TSE 09:00-11:30,12:30-15:00)" ? "0900-1130,1230-1500" :
     sessPreset == "Custom"                              ? sessCustom :
     sessCustom
 
// Guard: block full-day sessions (treat ≥1435 minutes as 24h and fallback to NYSE)
bool _is_full_day = sess_minutes(sessStrRaw) >= 1435
string sessStr    = _is_full_day ? "0930-1600" : sessStrRaw
 
// How many bars are needed to cover N sessions on a given intraday TF
bars_for_days(tf_min, days, sess_min) =>
    math.max(1, int(math.ceil(days * sess_min / tf_min)))
int sessMin   = sess_minutes(sessStr)   // derives minutes/day from your preset
int len3D_1H  = bars_for_days(60,  3.0, sessMin)
int lenW_4H   = bars_for_days(240, 5.0, sessMin)
int lenM_D  = bars_for_days(1440, 30.0, sessMin)
int lenQ_W  = bars_for_days(10080, 13.0, sessMin)
 
// Cache headline bias slopes - recalculate only once per day
var float cached_slope3D  = na
var float cached_slopeW   = na
var float cached_slopeM   = na
var float cached_slopeQ   = na
var int last_bias_update_day = na
 
bool should_update_bias = na(last_bias_update_day) or current_day != last_bias_update_day
 
if should_update_bias
    // Point-to-point comparison using tuple to minimize request.security calls
    [close3D_now, close3D_then]   = request.security(syminfo.tickerid, "60",  [close, close[len3D_1H]], barmerge.gaps_off, barmerge.lookahead_off)
    [closeW_now, closeW_then]     = request.security(syminfo.tickerid, "240", [close, close[lenW_4H]],  barmerge.gaps_off, barmerge.lookahead_off)
    [closeM_now, closeM_then]     = request.security(syminfo.tickerid, "D",   [close, close[15]],       barmerge.gaps_off, barmerge.lookahead_off)
    [closeQ_now, closeQ_then]     = request.security(syminfo.tickerid, "W",   [close, close[13]],       barmerge.gaps_off, barmerge.lookahead_off)
    
    cached_slope3D := close3D_now - close3D_then
    cached_slopeW  := closeW_now - closeW_then
    cached_slopeM  := closeM_now - closeM_then
    cached_slopeQ  := closeQ_now - closeQ_then
    last_bias_update_day := current_day
 
bias3D      := bias_label_from(cached_slope3D)
biasWeek    := bias_label_from(cached_slopeW)
biasMon     := bias_label_from(cached_slopeM)
biasQuarter := bias_label_from(cached_slopeQ)
 
if rowVIX and bias_htf_update
    float vixD = request.security(vixSymbol, vixTF, close, barmerge.gaps_off, barmerge.lookahead_off)
    vixBias := vixD < VIX_LOW ? "BULLISH✔️" : vixD > VIX_HIGH ? "BEARISH✖️" : "NEUTRAL⚠️"
 
// Used for the header "green dot"
bool need_update = bias_guard and barstate.islast
 
// Bias row tooltips (fixed-window slope)
string tipBias3D   = "3 Day Bias 1H:\nUses linear-regression slope of close over the last 3 regular sessions on 1h.\nBars used: " + str.tostring(len3D_1H)
string tipBiasWeek = "Weekly Bias 4H:\nUses linear-regression slope of close over the last 5 regular sessions on 4h.\nBars used: " + str.tostring(lenW_4H)
string tipBiasMon  = "Monthly Bias 1D:\nUses linear-regression slope of close over the last 30 daily bars (1 month)"
string qTip        = "Quarterly bias:\nlinear-regression slope of close over the last 13 weekly bars (13 months)."
 
or_bias_band_status_series() =>
    // Return "Not Open" on non-intraday charts
    if not timeframe.isintraday
        "Not Open"
    else
        bool reg_open = session.isfirstbar_regular
        bool in_sess  = not na(time(timeframe.period, sessStr))
        bool new_day  = ta.change(time("D")) != 0
        bool s_open   = in_sess and not in_sess[1] and new_day
 
        // Unified open event: either regular or custom
        bool open_evt = reg_open or s_open
 
        // Time-based elapsed minutes since session open (robust to missing bars/halts)
        var int _open_time = na
        if open_evt
            _open_time := time
 
        int mins_since = in_sess and not na(_open_time) ? int(math.floor((time - _open_time) / 60000)) : na
 
        // Completion flags by real minutes (not bar count)
        bool d5  = in_sess and mins_since >= 5
        bool d15 = in_sess and mins_since >= 15
        bool d30 = in_sess and mins_since >= 30
        bool d60 = in_sess and mins_since >= 60
 
        // Persistent H/L per window; cleared every open
        var float h5  = na
        var float l5  = na
        var float h15 = na
        var float l15 = na
        var float h30 = na
        var float l30 = na
        var float h60 = na
        var float l60 = na
 
        if open_evt
            h5  := na, l5  := na
            h15 := na, l15 := na
            h30 := na, l30 := na
            h60 := na, l60 := na
 
        if in_sess
            if not d5
                h5 := na(h5) ? high : math.max(h5, high)
                l5 := na(l5) ? low  : math.min(l5, low)
            if not d15
                h15 := na(h15) ? high : math.max(h15, high)
                l15 := na(l15) ? low  : math.min(l15, low)
            if not d30
                h30 := na(h30) ? high : math.max(h30, high)
                l30 := na(l30) ? low  : math.min(l30, low)
            if not d60
                h60 := na(h60) ? high : math.max(h60, high)
                l60 := na(l60) ? low  : math.min(l60, low)
 
        // Priority: 5 → 15 → 30 → 60 
        string st = "BUILDING"
        if d5 and not d15
            st := close > h5  ? "ABOVE  5" : close < l5  ? "BELOW  5" : "INSIDE 5"
        else if d15 and not d30
            st := close > h15 ? "ABOVE 15" : close < l15 ? "BELOW 15" : "INSIDE15"
        else if d30 and not d60
            st := close > h30 ? "ABOVE 30" : close < l30 ? "BELOW 30" : "INSIDE30"
        else if d60
            st := close > h60 ? "ABOVE 60" : close < l60 ? "BELOW 60" : "INSIDE60"
        st
 
//helpers
string vixTip = "VIX Bias:\n\nBULLISH if VIX < 18\nNEUTRAL if 18 ≤ VIX ≤ 22\nBEARISH if VIX > 22."
string orbTip = "Opening Range Bias (intraday only; hidden on D/W/M).\n\nAbove 05/15/30/60 = close is above the completed OR high of 5/15/30/60m, same for Bellow\n\nBetween means were inside the ORB range"
string orBand = (rowORB and timeframe.isintraday) ? or_bias_band_status_series() : "Not Open"
 
// --- Short label used on D/W/M timeframes for the Bias row
bias_label_compact(string raw) =>
    string r = str.lower(raw)
    r := str.replace_all(r, " ", "")
    r := str.replace_all(r, "bias", "")
    // map common Bias-row names to a very short token
    if      str.contains(r, "3day") or str.contains(r, "3d")
        "3D"
    else if str.contains(r, "weekly") or str.contains(r, "week")
        "W"
    else if str.contains(r, "monthly") or str.contains(r, "month")
        "M"
    else if str.contains(r, "quarter")
        "Q"
    else
        // fallback: 3-char uppercase from the original label
        str.upper(str.substring(raw, 0, math.min(3, str.length(raw))))
 
// Dynamic band (fills across active TF columns + AVG)
drawBiasBandDyn(_table, _row, _label, _rawTxt, _bgHdr, _textSize, _kCols, _tip) =>
    table.cell(_table, 0, _row, _label, text_color=color.white, bgcolor=_bgHdr, text_size=_textSize, text_halign=text.align_left, tooltip=_tip)
    word = timeframe.isdwm ? str.replace_all(str.replace_all(str.replace_all(str.upper(_rawTxt), "✔️", ""), "✖️", ""), "!", "") : str.upper(_rawTxt)
    bbg  = biasBg(_rawTxt)
    bfg  = biasFg(_rawTxt)
    wlen = str.length(word)
    int cols = 1 + _kCols
    int start = 0
    for c = 1 to 1 + _kCols
        idx = c - 1
        ch  = (idx >= 0 and idx < wlen) ? str.substring(word, idx, idx + 1) : ""
        table.cell(_table, c, _row, ch, text_color=bfg, bgcolor=bbg, text_size=_textSize, tooltip=_rawTxt)
    _row + 1
 
//================= OPENING RANGE (OR) BIAS — BAND STATUS =================
 
// Dynamic boolean row (per-TF cells + AVG)
drawRowDyn(_table, _row, _label, _arr, _tip, _bg, _textSize, _kCols) =>
    table.cell(_table, 0, _row, _label, text_color=color.white, bgcolor=_bg, text_size=_textSize, text_halign=text.align_left, tooltip=_tip)
    int k = array.size(_arr)
    int limit = math.min(_kCols, k) 
    int green = 0
    int valid = 0
    for i = 0 to limit - 1
        bool  ok    = array.get(_arr, i)
        float okNum = ok ? 1.0 : 0.0
        string cellTxt = na(okNum) ? "-" : getEmoji(ok)
        if not na(okNum)
            valid += 1
            if ok
                green += 1
        table.cell(_table, i + 1, _row, cellTxt, text_color=color.white, bgcolor=_bg, text_size=_textSize, tooltip=_tip)
 
    string avgTxt = valid > 0 ? str.tostring(math.round(100.0 * green / valid)) + "%" : "-"
    table.cell(_table, 1 + _kCols, _row, avgTxt, text_color=color.white, bgcolor=_bg, text_size=_textSize, tooltip="Average of green cells across active TFs")
    _row + 1
 
// Dynamic tri-state row (-1,0,1) with emojis + weighted AVG
drawTriRowDyn(table _table, int _row, string _label, int[] _stateArr, color _bg, string _textSize, string _tip, int _kCols, float neutralWeight) =>
    table.cell(_table, 0, _row, _label, text_color=color.white, bgcolor=_bg, text_size=_textSize, text_halign=text.align_left, tooltip=_tip)
 
    int   k      = array.size(_stateArr)
    int   limit  = math.min(_kCols, k)
    float score  = 0.0
    int valid = 0
 
    for i = 0 to limit - 1
        int state = array.get(_stateArr, i)
        string e  = na(state) ? "–" : (state == 1 ? "🟩" : state == -1 ? "🟥" : "🟡")
        if not na(state)
            valid += 1
            score += (state == 1 ? 1.0 : state == 0 ? neutralWeight : 0.0)
        table.cell(_table, i + 1, _row, e, text_color=color.white, bgcolor=_bg, text_size=_textSize, tooltip=_tip)
 
    string avgTxt = valid > 0 ? str.tostring(math.round(100.0 * score / valid)) + "%" : "-"
    table.cell(_table, 1 + _kCols, _row, avgTxt,text_color=color.white, bgcolor=_bg,
               text_size=_textSize, tooltip=_tip)
    _row + 1
 
// Gate and run the whole bias-table pipeline only on confirmed last bar
bool needBias = bias_guard and (not barstate.isrealtime or barstate.islast)
bool needAnyIndicatorRow = rowMA or rowMA200 or rowMACD or rowVWAP or rowZLSMA or rowST or rowRSI or rowADX
bool needAnyHeadlineRow  = rowBias3D or rowBiasWeekly or rowBiasMonth or rowBiasQuarter or rowVIX or (rowORB and timeframe.isintraday)
bool needAnyRow          = needAnyIndicatorRow or needAnyHeadlineRow
 
// === Dynamic row labels based on user settings ===
string maFastLabel = maFastType + " " + str.tostring(maShortLen)
string maMedLabel = maMedType + " " + str.tostring(maMedLen)
string maLongLabel = maLongType + " " + str.tostring(ma200Len)
 
string rowLabelMACross = maFastLabel + " > " + maMedLabel
string rowLabelMA200 = "Price > " + maLongLabel
 
renderBiasAndIndicators() =>
    if bias_guard
        int kCols = timeframe.isdwm ? 3 : tfEnabledCount
        int wantCols = 1 + kCols
        if not na(fullTable)
            table.clear(fullTable, 0, 0, dynCols - 1, 14)
        int col_idx = 1
 
        string _hdrTitleCore = timeframe.isdwm ? "LONG BIAS" : "BIAS INDICATOR", 
        string updateIndicator = need_update ? " ●" : ""  // Simple o instead of emoji
        color updateColor = need_update ? color.white : color.lime
        string _hdrTitle = _hdrTitleCore + updateIndicator
 
        table.cell(fullTable, 0, 0, _hdrTitle,  bgcolor=_hdrBg,  text_color=updateColor,   text_halign=text.align_center, text_size=textSize) 
        table.merge_cells(fullTable, 0, 0, dynCols - 1, 0)
  
 
        int rowIdx = 1
        if rowBias3D
            rowIdx := drawBiasBandDyn(fullTable, rowIdx, "3 Day Bias", bias3D, _hdrBg, textSize, kCols, tipBias3D)
        if rowBiasWeekly
            rowIdx := drawBiasBandDyn(fullTable, rowIdx, "Weekly Bias", biasWeek, _hdrBg, textSize, kCols, tipBiasWeek)
        if rowBiasMonth
            rowIdx := drawBiasBandDyn(fullTable, rowIdx, "Monthly Bias", biasMon, _hdrBg, textSize, kCols, tipBiasMon)
        if rowBiasQuarter
            rowIdx := drawBiasBandDyn(fullTable, rowIdx, "Quarterly Bias", biasQuarter, _hdrBg, textSize, kCols, qTip)
        if rowVIX
            rowIdx := drawBiasBandDyn(fullTable, rowIdx, "VIX Fear Index", vixBias, _hdrBg, textSize, kCols, vixTip)
        if rowORB and timeframe.isintraday
            rowIdx := drawBiasBandDyn(fullTable, rowIdx, "Opening Range Breakout", orBand, _hdrBg, textSize, kCols, orbTip)
 
// ADD SEPARATOR ROW HERE
        for c = 0 to dynCols - 1
            table.cell(fullTable, c, rowIdx, "", bgcolor=_hdrBg,  text_size=size.auto, height=1.5)
        rowIdx += 1
        for c = 0 to dynCols - 1
            table.cell(fullTable, c, rowIdx, "",  bgcolor=color.new(color.white, 100),text_size=size.auto, height=1.5) 
        rowIdx += 1
        
 
// TF Header Row
        table.cell(fullTable, 0, rowIdx, "", bgcolor=_hdrBg, text_size=textSize)
    
        if timeframe.isdwm
            table.cell(fullTable, col_idx, rowIdx, "D", text_color=color.white, bgcolor=_hdrBg, text_size=textSize), col_idx += 1
            table.cell(fullTable, col_idx, rowIdx, "W", text_color=color.white, bgcolor=_hdrBg, text_size=textSize), col_idx += 1
            table.cell(fullTable, col_idx, rowIdx, "M", text_color=color.white, bgcolor=_hdrBg, text_size=textSize), col_idx += 1
            table.cell(fullTable, col_idx, rowIdx, "AVG", text_color=color.white, bgcolor=_hdrBg, text_size=textSize)
        else
            string[] tf_labels = array.from("1m","5m","15m","30m","1h","2h","4h")
            bool[]   tf_flags  = array.from(tf1mOn, tf5mOn, tf15mOn, tf30mOn, tf1hOn, tf2hOn, tf4hOn)
            for i = 0 to array.size(tf_labels) - 1
                if array.get(tf_flags, i)
                    table.cell(fullTable, col_idx, rowIdx, array.get(tf_labels, i), text_color=color.white, bgcolor=_hdrBg, text_size=textSize)
                    col_idx += 1
            table.cell(fullTable, 1 + kCols, rowIdx, "AVG", text_color=color.white, bgcolor=_hdrBg, text_size=textSize)
        
        rowIdx += 1
 
// Indicator rows (boolean vs tri-state mapped explicitly)
        if rowMA
            rowIdx := drawRowDyn(fullTable, rowIdx, rowLabelMACross, crossDyn, "Uses your selected MA types (Fast vs. Medium) on each active TF.", _hdrBg, textSize, kCols)
        if rowMA200
            rowIdx := drawRowDyn(fullTable, rowIdx, rowLabelMA200, above200Dyn, "Close vs. your selected Long/Bias MA.", _hdrBg, textSize, kCols)
        if rowVWAP
            bool isDWM = timeframe.isdwm
            bool anchoredNow = isDWM or useAnchoredVWAPinTable
            string vwapLbl = anchoredNow ? "Price > VWAP ⚓" : "Price > VWAP"
            string vwapTip = isDWM ? "Close vs anchored VWAP with HTF minimums (D→Week, W→Month, M→Year)." : (useAnchoredVWAPinTable ? "Close vs anchored VWAP (" + anchor + "), clamped to TF minimums on HTF." : "Close vs plain/session VWAP (intraday); HTF rows use Week/Month/Year by default.")
            rowIdx := drawRowDyn(fullTable, rowIdx, vwapLbl, vwapAboveDyn, vwapTip, _hdrBg, textSize, kCols)
        if rowMACD
            rowIdx := drawTriRowDyn(fullTable, rowIdx, "MACD > Signal", macdStateDyn, _hdrBg, textSize, "MACD vs Signal: 🟩 when MACD>Signal, 🟥 when MACD<Signal, 🟡 when data is NA.", kCols, 0.0)
        if rowST
            rowIdx := drawTriRowDyn(fullTable, rowIdx, "Supertrend", stStateDyn, _hdrBg, textSize, "Supertrend: 🟩 = up, 🟥 = down, 🟡 = neutral\nfor N bars after a flip.", kCols, 0.0)
        if rowZLSMA
            rowIdx := drawRowDyn(fullTable, rowIdx, "ZLSMA Rising", zlsmaUpDyn, "ZLSMA slope rising.", _hdrBg, textSize, kCols)
        if rowRSI
            rowIdx := drawTriRowDyn(fullTable, rowIdx, "RSI In Zone", rsiStateDyn,_hdrBg, textSize, "RSI zones: 🟩=Buy zone, 🟥=Sell zone, 🟡=Neutral. AVG treats neutral as 50%.", kCols, 0.50)
        if rowADX
            rowIdx := drawRowDyn(fullTable, rowIdx, "ADX ≥ Minimum", adxStrongDyn, "ADX above threshold per TF cells.", _hdrBg, textSize, kCols)
 
if needBias and needAnyRow
    // Indicator rows: collect TF data only if at least one indicator row is enabled
    if bias_guard and needAnyIndicatorRow
        if timeframe.isdwm
            // HTF: update only on confirmed bars (bar close) - saves computation
            if barstate.isconfirmed or na(crossDyn_htfCache) or array.size(crossDyn_htfCache) == 0
                clear_bias_arrays()
                collect_dwm()
                // Cache HTF results until next bar close
                crossDyn_htfCache := array.copy(crossDyn)
                above200Dyn_htfCache := array.copy(above200Dyn)
                macdStateDyn_htfCache := array.copy(macdStateDyn)
                vwapAboveDyn_htfCache := array.copy(vwapAboveDyn)
                zlsmaUpDyn_htfCache := array.copy(zlsmaUpDyn)
                adxStrongDyn_htfCache := array.copy(adxStrongDyn)
                stStateDyn_htfCache := array.copy(stStateDyn)
                rsiStateDyn_htfCache := array.copy(rsiStateDyn)
            else
                // Restore from cache - no recalculation needed
                crossDyn := array.copy(crossDyn_htfCache)
                above200Dyn := array.copy(above200Dyn_htfCache)
                macdStateDyn := array.copy(macdStateDyn_htfCache)
                vwapAboveDyn := array.copy(vwapAboveDyn_htfCache)
                zlsmaUpDyn := array.copy(zlsmaUpDyn_htfCache)
                adxStrongDyn := array.copy(adxStrongDyn_htfCache)
                stStateDyn := array.copy(stStateDyn_htfCache)
                rsiStateDyn := array.copy(rsiStateDyn_htfCache)
        else
            // Intraday: always recalculate (price changes rapidly)
            clear_bias_arrays()
            collect_intraday(tf1mOn, tf5mOn, tf15mOn, tf30mOn, tf1hOn, tf2hOn, tf4hOn)
 
    renderBiasAndIndicators()
 
// ================================================================================
// FINAL NOTES ON ATTRIBUTION:
// ================================================================================
// This indicator was developed over 2+ months using AI assistance (ChatGPT/Claude)
// for code generation and optimization. While AI helped write the code, all design
// decisions, integration logic, and system architecture are original.
//
// Standard calculations (UT Bot, Supertrend, etc.) may appear similar to existing
// indicators because these are mathematical formulas in the public domain.
// However, the implementation here includes numerous enhancements.
//
// For questions about specific components or attribution: orenluxy
// ================================================================================

← 返回列表