ORB High Low + Dynamic Targets |CPR, VWAP, RVOL & Smart Breakout

alamcet · study · 1419 行 · 点赞 18 · TradingView 原页

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

Pine Script

//@version=6
 
indicator("ORB High Low + Dynamic Targets V13 (TradingView Sessions)", overlay=true, max_lines_count=200, max_labels_count=100)
 
 
 
//══════════════════════════════════════════════════════════════════════════════
 
// SETTINGS
 
//══════════════════════════════════════════════════════════════════════════════
 
 
 
groupOR = "Opening Range / Session"
sessionMode = input.string("TradingView Daily Session", "Session Source", options=["TradingView Daily Session", "NSE Session (09:15–15:30 IST)"], group=groupOR, tooltip="TradingView Daily Session follows the symbol's daily candle boundary. Use this for XAUUSD and other non-NSE symbols.")
useDayHighLow = input.bool(false, "Use Day High/Low After Opening Range", group=groupOR, tooltip="OFF = use the first 15-minute candle High/Low. ON = after the first 15 minutes use the current session High/Low.")
 
 
 
groupTarget = "Target Settings"
 
targetMethod = input.string("Range Multiple", "Target Method", options=["Range Multiple", "ATR Multiple"], group=groupTarget)
 
t1Multiple = input.float(0.5, "Target 1 Multiple", minval=0.1, step=0.1, group=groupTarget)
 
t2Multiple = input.float(1.0, "Target 2 Multiple", minval=0.1, step=0.1, group=groupTarget)
 
t3Multiple = input.float(1.5, "Target 3 Multiple", minval=0.1, step=0.1, group=groupTarget)
 
atrLength = input.int(14, "ATR Length", minval=1, group=groupTarget)
 
atrMultiplier = input.float(1.0, "ATR Multiplier", minval=0.1, step=0.1, group=groupTarget)
 
 
 
groupBreakout = "Breakout Settings"
 
breakoutMode = input.string("Candle Close", "Breakout Confirmation", options=["Candle Close", "Wick"], group=groupBreakout)
 
 
 
groupVisual = "Visual Settings"
 
showHighLow = input.bool(true, "Show High/Low", group=groupVisual)
 
showTargets = input.bool(true, "Show Targets", group=groupVisual)
 
showLabels = input.bool(true, "Show Breakout Labels", group=groupVisual)
 
keepHistorical = input.bool(false, "Keep Previous Days", group=groupVisual)
 
 
 
//══════════════════════════════════════════════════════════════════════════════
 
// KEY LEVEL SETTINGS
 
//══════════════════════════════════════════════════════════════════════════════
 
 
 
groupKeyLevels = "Key Intraday Levels"
 
showKeyLevels = input.bool(true, "Show Key Levels", group=groupKeyLevels, tooltip="Master ON/OFF switch for Previous Day, Today, Week and Month levels.")
 
showPDH = input.bool(true, "Previous Day High (PDH)", group=groupKeyLevels)
 
showPDL = input.bool(true, "Previous Day Low (PDL)", group=groupKeyLevels)
 
showTDH = input.bool(true, "Today's High (TDH)", group=groupKeyLevels)
 
showTDL = input.bool(true, "Today's Low (TDL)", group=groupKeyLevels)
 
showWH = input.bool(true, "Week High (WH)", group=groupKeyLevels)
 
showWL = input.bool(true, "Week Low (WL)", group=groupKeyLevels)
 
showMH = input.bool(true, "Month High (MH)", group=groupKeyLevels)
 
showML = input.bool(true, "Month Low (ML)", group=groupKeyLevels)
 
showKeyLabels = input.bool(true, "Show Key Level Labels", group=groupKeyLevels)
 
keyLineWidth = input.int(1, "Key Level Line Width", minval=1, maxval=3, group=groupKeyLevels)
 
 
 
//══════════════════════════════════════════════════════════════════════════════
 
// KEY LEVEL COLORS
 
//══════════════════════════════════════════════════════════════════════════════
 
 
 
groupKeyColors = "Key Level Colors"
 
pdhColor = input.color(color.rgb(145, 70, 190), "PDH Color", group=groupKeyColors)
 
pdlColor = input.color(color.rgb(145, 70, 190), "PDL Color", group=groupKeyColors)
 
tdhColor = input.color(color.rgb(20, 150, 75), "TDH Color", group=groupKeyColors)
 
tdlColor = input.color(color.rgb(210, 55, 55), "TDL Color", group=groupKeyColors)
 
whColor = input.color(color.rgb(40, 100, 210), "Week High Color", group=groupKeyColors)
 
wlColor = input.color(color.rgb(40, 100, 210), "Week Low Color", group=groupKeyColors)
 
mhColor = input.color(color.rgb(225, 135, 30), "Month High Color", group=groupKeyColors)
 
mlColor = input.color(color.rgb(225, 135, 30), "Month Low Color", group=groupKeyColors)
 
 
//══════════════════════════════════════════════════════════════════════════════
// CENTRAL PIVOT RANGE (CPR)
//══════════════════════════════════════════════════════════════════════════════
 
groupCPR = "Central Pivot Range (CPR)"
showCPR = input.bool(false, "Show Central Pivot Range", group=groupCPR, tooltip="Show CPR calculated from the previous completed daily candle.")
cprPivotColor = input.color(color.rgb(255, 193, 7), "Pivot (P) Color", group=groupCPR)
cprTopColor = input.color(color.rgb(0, 188, 212), "Top CPR (TC) Color", group=groupCPR)
cprBottomColor = input.color(color.rgb(255, 152, 0), "Bottom CPR (BC) Color", group=groupCPR)
cprLineWidth = input.int(2, "CPR Line Width", minval=1, maxval=4, group=groupCPR)
 
 
 
//══════════════════════════════════════════════════════════════════════════════
 
// NSE TIME & SESSION
 
//══════════════════════════════════════════════════════════════════════════════
 
 
 
string TZ = "Asia/Kolkata"
int h = hour(time, TZ)
int m = minute(time, TZ)
 
bool nseMode = sessionMode == "NSE Session (09:15–15:30 IST)"
bool tvNewDailySession = timeframe.change("D")
bool sessionStart = nseMode ? (h == 9 and m == 15) : tvNewDailySession
bool inSession = nseMode ? ((h > 9 or (h == 9 and m >= 15)) and (h < 15 or (h == 15 and m <= 30))) : true
var int sessionStartTime = na
if sessionStart
    sessionStartTime := time
int minutesFromSessionOpen = not na(sessionStartTime) ? int((time - sessionStartTime) / 60000) : na
bool inOpeningRange = inSession and not na(minutesFromSessionOpen) and minutesFromSessionOpen >= 0 and minutesFromSessionOpen < 15
bool after0930 = inSession and not na(minutesFromSessionOpen) and minutesFromSessionOpen >= 15
 
 
 
 
//══════════════════════════════════════════════════════════════════════════════
 
// OPENING RANGE
 
//══════════════════════════════════════════════════════════════════════════════
 
 
 
// Capture the exact first 15-minute candle from TradingView's 15-minute data.
f_first15Range() =>
    var float firstHigh = na
    var float firstLow = na
    bool newDailyBar = timeframe.change("D")
    if newDailyBar or na(firstHigh) or na(firstLow)
        firstHigh := high
        firstLow := low
    [firstHigh, firstLow]
 
[orHigh, orLow] = request.security(syminfo.tickerid, "15", f_first15Range(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
float orRange = orHigh - orLow
 
 
 
//══════════════════════════════════════════════════════════════════════════════
 
// DAY HIGH / LOW & PREVIOUS SESSION
 
//══════════════════════════════════════════════════════════════════════════════
 
 
 
var float dayHigh = na
 
var float dayLow = na
 
var float previousDayHigh = na
 
var float previousDayLow = na
 
 
 
if sessionStart
 
    previousDayHigh := dayHigh
 
    previousDayLow := dayLow
 
    dayHigh := high
 
    dayLow := low
 
else if inSession
    dayHigh := math.max(dayHigh, high)
    dayLow := math.min(dayLow, low)
 
// Previous day levels from the previous completed TradingView daily candle.
[tradingViewPDH, tradingViewPDL] = request.security(syminfo.tickerid, "D", [high[1], low[1]], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
 
// CPR based on the previous completed daily candle, stable throughout the current session.
[cprPrevHigh, cprPrevLow, cprPrevClose] = request.security(syminfo.tickerid, "D", [high[1], low[1], close[1]], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
cprPivot = (cprPrevHigh + cprPrevLow + cprPrevClose) / 3.0
cprBC = (cprPrevHigh + cprPrevLow) / 2.0
cprTC = 2.0 * cprPivot - cprBC
previousDayHigh := tradingViewPDH
previousDayLow := tradingViewPDL
 
 
 
//══════════════════════════════════════════════════════════════════════════════
 
// WEEK & MONTH HIGH / LOW (Timezone Anchored)
 
//══════════════════════════════════════════════════════════════════════════════
 
 
 
var float weekHigh = na
 
var float weekLow = na
 
bool newWeek = ta.change(time("W", TZ)) != 0
 
 
 
if inSession
 
    if newWeek or na(weekHigh)
 
        weekHigh := high
 
        weekLow := low
 
    else
 
        weekHigh := math.max(weekHigh, high)
 
        weekLow := math.min(weekLow, low)
 
 
 
var float monthHigh = na
 
var float monthLow = na
 
bool newMonth = ta.change(time("M", TZ)) != 0
 
 
 
if inSession
 
    if newMonth or na(monthHigh)
 
        monthHigh := high
 
        monthLow := low
 
    else
 
        monthHigh := math.max(monthHigh, high)
 
        monthLow := math.min(monthLow, low)
 
 
 
//══════════════════════════════════════════════════════════════════════════════
 
// ACTIVE REFERENCE & TARGETS
 
//══════════════════════════════════════════════════════════════════════════════
 
 
 
float activeHigh = useDayHighLow and after0930 ? dayHigh : orHigh
 
float activeLow = useDayHighLow and after0930 ? dayLow : orLow
 
float activeRange = activeHigh - activeLow
 
 
 
float atr = ta.atr(atrLength)
 
float targetDistance = targetMethod == "Range Multiple" ? activeRange : atr * atrMultiplier
 
 
 
var bool bullishBreakout = false
 
var bool bearishBreakdown = false
 
 
 
if sessionStart
 
    bullishBreakout := false
 
    bearishBreakdown := false
 
 
 
bool bullishSignal = false
 
bool bearishSignal = false
 
 
 
// Normal ORB Signals
 
if after0930 and not useDayHighLow and not na(orHigh) and not na(orLow)
 
    if breakoutMode == "Candle Close"
 
        bullishSignal := close > orHigh and close[1] <= orHigh and not bullishBreakout
 
        bearishSignal := close < orLow and close[1] >= orLow and not bearishBreakdown
 
    else
 
        bullishSignal := high > orHigh and not bullishBreakout
 
        bearishSignal := low < orLow and not bearishBreakdown
 
 
 
// Day High/Low Signals
 
if after0930 and useDayHighLow and not na(previousDayHigh) and not na(previousDayLow)
 
    if breakoutMode == "Candle Close"
 
        bullishSignal := close > previousDayHigh and close[1] <= previousDayHigh and not bullishBreakout
 
        bearishSignal := close < previousDayLow and close[1] >= previousDayLow and not bearishBreakdown
 
    else
 
        bullishSignal := high > previousDayHigh and not bullishBreakout
 
        bearishSignal := low < previousDayLow and not bearishBreakdown
 
 
 
if bullishSignal
 
    bullishBreakout := true
 
if bearishSignal
 
    bearishBreakdown := true
 
 
 
float bullT1 = activeHigh + targetDistance * t1Multiple
 
float bullT2 = activeHigh + targetDistance * t2Multiple
 
float bullT3 = activeHigh + targetDistance * t3Multiple
 
 
 
float bearT1 = activeLow - targetDistance * t1Multiple
 
float bearT2 = activeLow - targetDistance * t2Multiple
 
float bearT3 = activeLow - targetDistance * t3Multiple
 
 
 
//══════════════════════════════════════════════════════════════════════════════
 
// MENTOR-STYLE SETTINGS & FILTERS
 
//══════════════════════════════════════════════════════════════════════════════
 
 
 
groupLiquidity = "General / Liquidity"
 
maxFlatDashedBars = input.int(5, "Max Flat Dashed Bars Allowed", minval=0, group=groupLiquidity)
 
min5DayAvgVolume = input.float(50000, "Min 5-Day Avg Volume (Shares)", minval=0, group=groupLiquidity)
 
min5DayAvgTurnover = input.float(500000, "Min 5-Day Avg Turnover (Currency)", minval=0, group=groupLiquidity)
 
minNBSThreshold = input.float(0, "Min Net Buy/Sell (NBS) Threshold", group=groupLiquidity)
 
blockTooManyMarubozus = input.bool(true, "Block Breakouts if Too Many Marubozus Today", group=groupLiquidity)
 
maxSessionMarubozus = input.int(20, "Max Allowed Session Marubozus", minval=0, group=groupLiquidity)
 
 
 
groupVWAP = "VWAP & Volatility Gates"
 
requirePriceAboveVWAPQuality = input.bool(true, "Require Favorable Price vs VWAP (Long > VWAP, Short < VWAP)", group=groupVWAP)
 
plotIntradayVWAP = input.bool(true, "Plot Intraday VWAP Line", group=groupVWAP)
 
mentorVWAPColor = input.color(color.orange, "VWAP Color", group=groupVWAP)
 
filterLowVolatility = input.bool(true, "Filter Out Low Volatility (Dead Stocks)", group=groupVWAP)
 
intradayATRLookback = input.int(14, "Intraday ATR Lookback", minval=1, group=groupVWAP)
 
minimumIntradayATRPercent = input.float(0.08, "Minimum Intraday ATR% (% of Price)", minval=0, step=0.01, group=groupVWAP)
 
 
 
groupBeta = "Beta Filter Configuration"
 
enableBetaGate = input.bool(false, "Enable Beta Threshold Gate", group=groupBeta)
 
betaIndexChoice = input.string("NIFTY 50", "Beta Benchmark Index", options=["NIFTY 50", "NIFTY BANK", "NIFTY FIN SERVICE", "SENSEX", "Custom Symbol"], group=groupBeta)
 
customBetaBenchmark = input.symbol("NSE:NIFTY", "Custom Benchmark Symbol", group=groupBeta)
 
betaBenchmark = betaIndexChoice == "NIFTY 50" ? "NSE:NIFTY" : betaIndexChoice == "NIFTY BANK" ? "NSE:BANKNIFTY" : betaIndexChoice == "NIFTY FIN SERVICE" ? "NSE:FINNIFTY" : betaIndexChoice == "SENSEX" ? "BSE:SENSEX" : customBetaBenchmark
 
betaLookbackDays = input.int(20, "Beta Lookback Period (Days)", minval=2, group=groupBeta)
 
minimumBetaAllowed = input.float(0.8, "Minimum Beta Allowed", step=0.1, group=groupBeta)
 
 
 
groupExhaustion = "Exhaustion & Overextension Filters"
 
filterExtendedRunup = input.bool(true, "Filter Out Extended Run-Up from Session Extreme", group=groupExhaustion)
 
maxRunupBeforeBreakout = input.float(5.0, "Max Allowed Stretch Prior to Breakout (%)", minval=0, step=0.1, group=groupExhaustion)
 
filterOverextendedVWAP = input.bool(false, "Filter Out Overextended Price from VWAP", group=groupExhaustion)
 
maxStretchAboveVWAP = input.float(2.0, "Max Allowed Stretch Above VWAP (%)", minval=0, step=0.1, group=groupExhaustion)
 
avoidHighFirst15mRange = input.bool(true, "Avoid Alert if 1st 15m Range is High", group=groupExhaustion)
 
maxFirst15mRange = input.float(8.0, "Max Allowed 1st 15m Range (%)", minval=0, step=0.1, group=groupExhaustion)
 
filterOverextended1h = input.bool(false, "Filter 1h Level if 1-Hour Range is Overextended", group=groupExhaustion)
 
max1hWindowRange = input.float(2.5, "Max Allowed 1-Hour Window Range (%)", minval=0, step=0.1, group=groupExhaustion)
 
require1hNearEarlierWindows = input.bool(true, "Require 1h Level Near Earlier Windows (Max Gap %)", group=groupExhaustion)
 
max1hGapPercent = input.float(4.0, "Max Allowed Gap: 1h High vs 45m/30m High (%)", minval=0, step=0.1, group=groupExhaustion)
 
 
 
groupMentorAlerts = "Alert Rules & Priority Toggles"
 
excludeIlliquidExchanges = input.bool(true, "Exclude Illiquid Exchanges (BSE for Cash Equities)", group=groupMentorAlerts)
 
requireConfirmingNBS = input.bool(true, "Require Confirming NBS Direction (+ve Long / -ve Short)", group=groupMentorAlerts)
 
requireVWAPForAlert = input.bool(true, "Require VWAP Alignment to Fire Alerts", group=groupMentorAlerts)
 
requireVolumeMultiple = input.bool(true, "Require Volume >= Multiplier * 20 MA", group=groupMentorAlerts)
 
mentorVolumeMALength = input.int(20, "Volume MA Length", minval=1, group=groupMentorAlerts)
 
minimumVolumeMultiplier = input.float(0.5, "Min Volume Multiplier", minval=0, step=0.1, group=groupMentorAlerts)
 
mentorBreakoutMode = input.string("Intrabar", "Price Breakout Mode", options=["Intrabar", "Candle Close"], group=groupMentorAlerts)
 
requireBreakoutExpansion = input.bool(false, "Require Breakout Candle Minimum Expansion %", group=groupMentorAlerts)
 
minimumCandleTotalRange = input.float(0.8, "Minimum Candle Total Range %", minval=0, step=0.05, group=groupMentorAlerts)
 
minimumCandleBody = input.float(0.35, "Minimum Candle Body %", minval=0, step=0.05, group=groupMentorAlerts)
 
 
 
groupWindows = "Alert Active Windows"
 
alert15Minute = input.bool(true, "Alert on 15-Min Breakouts", group=groupWindows)
 
alert30Minute = input.bool(true, "Alert on 30-Min Breakouts", group=groupWindows)
 
alert45Minute = input.bool(true, "Alert on 45-Min Breakouts", group=groupWindows)
 
alert1Hour = input.bool(true, "Alert on 1-Hour Breakouts", group=groupWindows)
 
 
 
groupRearm = "Failed Breakout Re-Arm Logic"
 
enableFailedBreakoutRearm = input.bool(false, "Enable Failed Breakout Re-Arm", group=groupRearm)
 
minimumDumpDistanceReset = input.float(0.5, "Min Dump Distance Below Level to Reset (%)", minval=0, step=0.1, group=groupRearm)
 
consecutiveBarsBelowVWAPToFail = input.int(3, "Consecutive Bars Below VWAP to Confirm Failure", minval=1, group=groupRearm)
 
 
 
groupBaseAlerts = "Original ORB Alert Controls"
 
enableORBAlerts = input.bool(true, "Enable Original ORB Alerts", group=groupBaseAlerts)
 
enableBullAlerts = input.bool(true, "Enable Bullish Breakout Alerts", group=groupBaseAlerts)
 
enableBearAlerts = input.bool(true, "Enable Bearish Breakdown Alerts", group=groupBaseAlerts)
 
alertsOnClose = input.bool(true, "Confirm Original ORB Signals at Candle Close", group=groupBaseAlerts)
 
 
 
// Calculations
 
mentorVWAP = ta.vwap(hlc3)
 
plot(plotIntradayVWAP ? mentorVWAP : na, title="Intraday VWAP", color=mentorVWAPColor, linewidth=2)
 
plot(showCPR ? cprPivot : na, title="CPR Pivot (P)", color=cprPivotColor, linewidth=cprLineWidth, style=plot.style_stepline)
plot(showCPR ? cprTC : na, title="CPR Top (TC)", color=cprTopColor, linewidth=cprLineWidth, style=plot.style_stepline)
plot(showCPR ? cprBC : na, title="CPR Bottom (BC)", color=cprBottomColor, linewidth=cprLineWidth, style=plot.style_stepline)
 
mentorVolumeMA = ta.sma(volume, mentorVolumeMALength)
 
mentorNBS = high != low ? volume * (close - open) / (high - low) : 0.0
 
mentorATR = ta.atr(intradayATRLookback)
 
mentorATRPercent = close != 0 ? mentorATR / close * 100 : 0.0
 
 
 
// Safe daily security requests without lookahead bias or intraday sampling distortion
 
f_dailyMetrics() =>
 
    vSMA = ta.sma(volume[1], 5)
 
    tSMA = ta.sma((volume * close)[1], 5)
 
    ret  = math.log(close[1] / close[2])
 
    [vSMA, tSMA, ret]
 
 
 
f_dailyBench() =>
 
    math.log(close[1] / close[2])
 
 
 
[avg5DayVolume, avg5DayTurnover, dailyStockRet] = request.security(syminfo.tickerid, "D", f_dailyMetrics(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
 
dailyBenchRet = request.security(betaBenchmark, "D", f_dailyBench(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
 
 
 
// Approximate Beta from daily returns
 
stockRetMean = ta.sma(dailyStockRet, betaLookbackDays)
 
benchmarkRetMean = ta.sma(dailyBenchRet, betaLookbackDays)
 
betaCov = ta.sma(dailyStockRet * dailyBenchRet, betaLookbackDays) - stockRetMean * benchmarkRetMean
 
betaVar = ta.sma(dailyBenchRet * dailyBenchRet, betaLookbackDays) - benchmarkRetMean * benchmarkRetMean
 
mentorBeta = not na(betaVar) and betaVar > 0 ? betaCov / betaVar : na
 
 
 
var float mentorSessionOpen = na
 
var float mentorSessionHigh = na
 
var float mentorSessionLow = na
 
var float window15High = na
 
var float window15Low = na
 
var float window30High = na
 
var float window30Low = na
 
var float window45High = na
 
var float window45Low = na
 
var float window60High = na
 
var float window60Low = na
 
var int sessionMarubozuCount = 0
 
 
 
var bool fired15Bull = false
 
var bool fired15Bear = false
 
var bool fired30Bull = false
 
var bool fired30Bear = false
 
var bool fired45Bull = false
 
var bool fired45Bear = false
 
var bool fired60Bull = false
 
var bool fired60Bear = false
 
 
 
if sessionStart
 
    mentorSessionOpen := open
 
    mentorSessionHigh := high
 
    mentorSessionLow := low
 
    window15High := na
 
    window15Low := na
 
    window30High := na
 
    window30Low := na
 
    window45High := na
 
    window45Low := na
 
    window60High := na
 
    window60Low := na
 
    sessionMarubozuCount := 0
 
    fired15Bull := false
 
    fired15Bear := false
 
    fired30Bull := false
 
    fired30Bear := false
 
    fired45Bull := false
 
    fired45Bear := false
 
    fired60Bull := false
 
    fired60Bear := false
 
else if inSession
 
    mentorSessionHigh := na(mentorSessionHigh) ? high : math.max(mentorSessionHigh, high)
 
    mentorSessionLow := na(mentorSessionLow) ? low : math.min(mentorSessionLow, low)
 
 
 
minutesFromNSEOpen = minutesFromSessionOpen
 
if inSession and minutesFromNSEOpen >= 0 and minutesFromNSEOpen < 15
 
    window15High := na(window15High) ? high : math.max(window15High, high)
 
    window15Low := na(window15Low) ? low : math.min(window15Low, low)
 
if inSession and minutesFromNSEOpen >= 0 and minutesFromNSEOpen < 30
 
    window30High := na(window30High) ? high : math.max(window30High, high)
 
    window30Low := na(window30Low) ? low : math.min(window30Low, low)
 
if inSession and minutesFromNSEOpen >= 0 and minutesFromNSEOpen < 45
 
    window45High := na(window45High) ? high : math.max(window45High, high)
 
    window45Low := na(window45Low) ? low : math.min(window45Low, low)
 
if inSession and minutesFromNSEOpen >= 0 and minutesFromNSEOpen < 60
 
    window60High := na(window60High) ? high : math.max(window60High, high)
 
    window60Low := na(window60Low) ? low : math.min(window60Low, low)
 
 
 
isMarubozu = high > low and math.abs(close - open) / (high - low) >= 0.90
 
if inSession and isMarubozu
 
    sessionMarubozuCount += 1
 
 
 
candleRangePercent = close != 0 ? (high - low) / close * 100 : 0.0
 
candleBodyPercent = close != 0 ? math.abs(close - open) / close * 100 : 0.0
 
first15RangePercent = not na(window15High) and not na(window15Low) and not na(mentorSessionOpen) and mentorSessionOpen != 0 ? (window15High - window15Low) / mentorSessionOpen * 100 : na
 
first60RangePercent = not na(window60High) and not na(window60Low) and not na(mentorSessionOpen) and mentorSessionOpen != 0 ? (window60High - window60Low) / mentorSessionOpen * 100 : na
 
runupPercent = not na(mentorSessionLow) and mentorSessionLow != 0 ? (close - mentorSessionLow) / mentorSessionLow * 100 : na
 
rundownPercent = not na(mentorSessionHigh) and mentorSessionHigh != 0 ? (mentorSessionHigh - close) / mentorSessionHigh * 100 : na
 
vwapStretchPercent = not na(mentorVWAP) and mentorVWAP != 0 ? math.abs(close - mentorVWAP) / mentorVWAP * 100 : na
 
gap60to45Percent = not na(window60High) and not na(window45High) and window45High != 0 ? math.abs(window60High - window45High) / window45High * 100 : na
 
 
 
// Exchange & Liquidity baseline checks
 
exchangePass = not excludeIlliquidExchanges or syminfo.prefix != "BSE"
 
liquidityPass = (na(avg5DayVolume) or avg5DayVolume >= min5DayAvgVolume) and (na(avg5DayTurnover) or avg5DayTurnover >= min5DayAvgTurnover)
 
marubozuPass = not blockTooManyMarubozus or sessionMarubozuCount <= maxSessionMarubozus
 
volumePass = not requireVolumeMultiple or (not na(mentorVolumeMA) and volume >= mentorVolumeMA * minimumVolumeMultiplier)
 
volatilityPass = not filterLowVolatility or mentorATRPercent >= minimumIntradayATRPercent
 
betaPass = not enableBetaGate or (not na(mentorBeta) and mentorBeta >= minimumBetaAllowed)
 
stretchPass = not filterOverextendedVWAP or (not na(vwapStretchPercent) and vwapStretchPercent <= maxStretchAboveVWAP)
 
first15Pass = not avoidHighFirst15mRange or na(first15RangePercent) or first15RangePercent <= maxFirst15mRange
 
first60Pass = not filterOverextended1h or na(first60RangePercent) or first60RangePercent <= max1hWindowRange
 
gapPass = not require1hNearEarlierWindows or na(gap60to45Percent) or gap60to45Percent <= max1hGapPercent
 
candleExpansionPass = not requireBreakoutExpansion or (candleRangePercent >= minimumCandleTotalRange and candleBodyPercent >= minimumCandleBody)
 
 
 
// Separated Bullish vs Bearish Gates
 
bullNBSPass = not requireConfirmingNBS or (mentorNBS > 0 and mentorNBS >= minNBSThreshold)
 
bullVWAPQuality = not requirePriceAboveVWAPQuality or close > mentorVWAP
 
bullVWAPAlert = not requireVWAPForAlert or close > mentorVWAP
 
bullRunupPass = not filterExtendedRunup or (not na(runupPercent) and runupPercent <= maxRunupBeforeBreakout)
 
 
 
bullCommonPass = exchangePass and liquidityPass and marubozuPass and volumePass and volatilityPass and betaPass and stretchPass and first15Pass and first60Pass and gapPass and candleExpansionPass and bullNBSPass and bullVWAPQuality and bullVWAPAlert and bullRunupPass
 
 
 
bearNBSPass = not requireConfirmingNBS or (mentorNBS < 0 and math.abs(mentorNBS) >= minNBSThreshold)
 
bearVWAPQuality = not requirePriceAboveVWAPQuality or close < mentorVWAP
 
bearVWAPAlert = not requireVWAPForAlert or close < mentorVWAP
 
bearRunupPass = not filterExtendedRunup or (not na(rundownPercent) and rundownPercent <= maxRunupBeforeBreakout)
 
 
 
bearCommonPass = exchangePass and liquidityPass and marubozuPass and volumePass and volatilityPass and betaPass and stretchPass and first15Pass and first60Pass and gapPass and candleExpansionPass and bearNBSPass and bearVWAPQuality and bearVWAPAlert and bearRunupPass
 
 
 
mentorClosePass = mentorBreakoutMode == "Intrabar" or barstate.isconfirmed
 
originalClosePass = not alertsOnClose or barstate.isconfirmed
 
 
 
bullAlertSignal = enableORBAlerts and enableBullAlerts and bullishSignal and originalClosePass and bullCommonPass
 
bearAlertSignal = enableORBAlerts and enableBearAlerts and bearishSignal and originalClosePass and bearCommonPass
 
anyAlertSignal = bullAlertSignal or bearAlertSignal
 
 
 
after15Window = inSession and minutesFromNSEOpen >= 15
 
after30Window = inSession and minutesFromNSEOpen >= 30
 
after45Window = inSession and minutesFromNSEOpen >= 45
 
after60Window = inSession and minutesFromNSEOpen >= 60
 
 
 
bull15Raw = after15Window and not na(window15High) and (mentorBreakoutMode == "Intrabar" ? high > window15High : close > window15High and close[1] <= window15High)
 
bear15Raw = after15Window and not na(window15Low) and (mentorBreakoutMode == "Intrabar" ? low < window15Low : close < window15Low and close[1] >= window15Low)
 
bull30Raw = after30Window and not na(window30High) and (mentorBreakoutMode == "Intrabar" ? high > window30High : close > window30High and close[1] <= window30High)
 
bear30Raw = after30Window and not na(window30Low) and (mentorBreakoutMode == "Intrabar" ? low < window30Low : close < window30Low and close[1] >= window30Low)
 
bull45Raw = after45Window and not na(window45High) and (mentorBreakoutMode == "Intrabar" ? high > window45High : close > window45High and close[1] <= window45High)
 
bear45Raw = after45Window and not na(window45Low) and (mentorBreakoutMode == "Intrabar" ? low < window45Low : close < window45Low and close[1] >= window45Low)
 
bull60Raw = after60Window and not na(window60High) and (mentorBreakoutMode == "Intrabar" ? high > window60High : close > window60High and close[1] <= window60High)
 
bear60Raw = after60Window and not na(window60Low) and (mentorBreakoutMode == "Intrabar" ? low < window60Low : close < window60Low and close[1] >= window60Low)
 
 
 
bull15Signal = alert15Minute and bull15Raw and not fired15Bull and bullCommonPass and mentorClosePass
 
bear15Signal = alert15Minute and bear15Raw and not fired15Bear and bearCommonPass and mentorClosePass
 
bull30Signal = alert30Minute and bull30Raw and not fired30Bull and bullCommonPass and mentorClosePass
 
bear30Signal = alert30Minute and bear30Raw and not fired30Bear and bearCommonPass and mentorClosePass
 
bull45Signal = alert45Minute and bull45Raw and not fired45Bull and bullCommonPass and mentorClosePass
 
bear45Signal = alert45Minute and bear45Raw and not fired45Bear and bearCommonPass and mentorClosePass
 
bull60Signal = alert1Hour and bull60Raw and not fired60Bull and bullCommonPass and mentorClosePass
 
bear60Signal = alert1Hour and bear60Raw and not fired60Bear and bearCommonPass and mentorClosePass
 
 
 
// Latch flags only when bar confirms to prevent intrabar false-break lockouts
 
if bull15Signal and barstate.isconfirmed
 
    fired15Bull := true
 
if bear15Signal and barstate.isconfirmed
 
    fired15Bear := true
 
if bull30Signal and barstate.isconfirmed
 
    fired30Bull := true
 
if bear30Signal and barstate.isconfirmed
 
    fired30Bear := true
 
if bull45Signal and barstate.isconfirmed
 
    fired45Bull := true
 
if bear45Signal and barstate.isconfirmed
 
    fired45Bear := true
 
if bull60Signal and barstate.isconfirmed
 
    fired60Bull := true
 
if bear60Signal and barstate.isconfirmed
 
    fired60Bear := true
 
 
 
var int mentorBarsBelowVWAP = 0
 
mentorBarsBelowVWAP := close < mentorVWAP ? mentorBarsBelowVWAP + 1 : 0
 
failedBreakoutReset = enableFailedBreakoutRearm and mentorBarsBelowVWAP >= consecutiveBarsBelowVWAPToFail and not na(mentorSessionLow) and mentorSessionLow != 0 and (mentorSessionLow - close) / mentorSessionLow * 100 >= minimumDumpDistanceReset
 
if failedBreakoutReset
 
    fired15Bull := false
 
    fired30Bull := false
 
    fired45Bull := false
 
    fired60Bull := false
 
 
 
//══════════════════════════════════════════════════════════════════════════════
 
// VISUAL DRAWINGS (LINES & LABELS)
 
//══════════════════════════════════════════════════════════════════════════════
 
 
 
var line highLine = na
 
var line lowLine = na
 
var line bullT1Line = na
 
var line bullT2Line = na
 
var line bullT3Line = na
 
var line bearT1Line = na
 
var line bearT2Line = na
 
var line bearT3Line = na
 
var line pdhLine = na
 
var line pdlLine = na
 
var line tdhLine = na
 
var line tdlLine = na
 
var line whLine = na
 
var line wlLine = na
 
var line mhLine = na
 
var line mlLine = na
 
 
 
var label pdhLabel = na
 
var label pdlLabel = na
 
var label tdhLabel = na
 
var label tdlLabel = na
 
var label whLabel = na
 
var label wlLabel = na
 
var label mhLabel = na
 
var label mlLabel = na
 
 
 
var array<label> breakoutLabels = array.new<label>()
 
 
 
if sessionStart and not keepHistorical
 
    if array.size(breakoutLabels) > 0
 
        for i = 0 to array.size(breakoutLabels) - 1
 
            label oldLabel = array.get(breakoutLabels, i)
 
            label.delete(oldLabel)
 
        array.clear(breakoutLabels)
 
 
 
    line.delete(highLine)
 
    line.delete(lowLine)
 
    line.delete(bullT1Line)
 
    line.delete(bullT2Line)
 
    line.delete(bullT3Line)
 
    line.delete(bearT1Line)
 
    line.delete(bearT2Line)
 
    line.delete(bearT3Line)
 
    highLine := na
 
    lowLine := na
 
    bullT1Line := na
 
    bullT2Line := na
 
    bullT3Line := na
 
    bearT1Line := na
 
    bearT2Line := na
 
    bearT3Line := na
 
 
 
if after0930 and showHighLow and na(highLine)
 
    highLine := line.new(bar_index, activeHigh, bar_index + 1, activeHigh, extend=extend.right, color=color.green, style=line.style_dashed, width=2)
 
    lowLine := line.new(bar_index, activeLow, bar_index + 1, activeLow, extend=extend.right, color=color.red, style=line.style_dashed, width=2)
 
 
 
if after0930 and not na(highLine)
 
    line.set_y1(highLine, activeHigh)
 
    line.set_y2(highLine, activeHigh)
 
 
 
if after0930 and not na(lowLine)
 
    line.set_y1(lowLine, activeLow)
 
    line.set_y2(lowLine, activeLow)
 
 
 
f_updateKeyLine(line existingLine, float price, bool enabled, color levelColor) =>
 
    line result = existingLine
 
    if showKeyLevels and enabled and not na(price)
 
        if na(result)
 
            result := line.new(bar_index, price, bar_index + 1, price, extend=extend.right, color=levelColor, style=line.style_dashed, width=keyLineWidth)
 
        else
 
            line.set_y1(result, price)
 
            line.set_y2(result, price)
 
            line.set_color(result, levelColor)
 
            line.set_width(result, keyLineWidth)
 
    else
 
        if not na(result)
 
            line.delete(result)
 
        result := na
 
    result
 
 
 
f_updateKeyLabel(label existingLabel, float price, float labelY, string levelName, bool enabled, color levelColor) =>
 
    label result = existingLabel
 
    if showKeyLevels and showKeyLabels and enabled and not na(price) and not na(labelY)
 
        string labelText = levelName + "  " + str.tostring(price, format.mintick)
 
        if na(result)
 
            result := label.new(bar_index + 2, labelY, labelText, xloc=xloc.bar_index, style=label.style_label_left, color=levelColor, textcolor=color.white, size=size.small)
 
        else
 
            label.set_x(result, bar_index + 2)
 
            label.set_y(result, labelY)
 
            label.set_text(result, labelText)
 
            label.set_color(result, levelColor)
 
    else
 
        if not na(result)
 
            label.delete(result)
 
        result := na
 
    result
 
 
 
if inSession
 
    pdhLine := f_updateKeyLine(pdhLine, previousDayHigh, showPDH, pdhColor)
 
    pdlLine := f_updateKeyLine(pdlLine, previousDayLow, showPDL, pdlColor)
 
    tdhLine := f_updateKeyLine(tdhLine, dayHigh, showTDH, tdhColor)
 
    tdlLine := f_updateKeyLine(tdlLine, dayLow, showTDL, tdlColor)
 
    whLine := f_updateKeyLine(whLine, weekHigh, showWH, whColor)
 
    wlLine := f_updateKeyLine(wlLine, weekLow, showWL, wlColor)
 
    mhLine := f_updateKeyLine(mhLine, monthHigh, showMH, mhColor)
 
    mlLine := f_updateKeyLine(mlLine, monthLow, showML, mlColor)
 
 
 
    // Stack labels vertically when key levels are at (or within two ticks of) the same price.
    // The horizontal level lines remain at their exact calculated prices; only label positions move.
    float labelStep = math.max(nz(ta.atr(14), close * 0.001) * 0.04, syminfo.mintick * 10)
    float sameLevelTolerance = syminfo.mintick * 2
    bool pdhActive = showKeyLevels and showKeyLabels and showPDH and not na(previousDayHigh)
    bool pdlActive = showKeyLevels and showKeyLabels and showPDL and not na(previousDayLow)
    bool tdhActive = showKeyLevels and showKeyLabels and showTDH and not na(dayHigh)
    bool tdlActive = showKeyLevels and showKeyLabels and showTDL and not na(dayLow)
    bool whActive = showKeyLevels and showKeyLabels and showWH and not na(weekHigh)
    bool wlActive = showKeyLevels and showKeyLabels and showWL and not na(weekLow)
    bool mhActive = showKeyLevels and showKeyLabels and showMH and not na(monthHigh)
    bool mlActive = showKeyLevels and showKeyLabels and showML and not na(monthLow)
 
    bool pdlSame = pdhActive and pdlActive and math.abs(previousDayLow - previousDayHigh) <= sameLevelTolerance
    bool tdhSamePDH = pdhActive and tdhActive and math.abs(dayHigh - previousDayHigh) <= sameLevelTolerance
    bool tdhSamePDL = pdlActive and tdhActive and math.abs(dayHigh - previousDayLow) <= sameLevelTolerance
    bool tdlSamePDH = pdhActive and tdlActive and math.abs(dayLow - previousDayHigh) <= sameLevelTolerance
    bool tdlSamePDL = pdlActive and tdlActive and math.abs(dayLow - previousDayLow) <= sameLevelTolerance
    bool tdlSameTDH = tdhActive and tdlActive and math.abs(dayLow - dayHigh) <= sameLevelTolerance
    bool whSamePDH = pdhActive and whActive and math.abs(weekHigh - previousDayHigh) <= sameLevelTolerance
    bool whSamePDL = pdlActive and whActive and math.abs(weekHigh - previousDayLow) <= sameLevelTolerance
    bool whSameTDH = tdhActive and whActive and math.abs(weekHigh - dayHigh) <= sameLevelTolerance
    bool whSameTDL = tdlActive and whActive and math.abs(weekHigh - dayLow) <= sameLevelTolerance
    bool wlSamePDH = pdhActive and wlActive and math.abs(weekLow - previousDayHigh) <= sameLevelTolerance
    bool wlSamePDL = pdlActive and wlActive and math.abs(weekLow - previousDayLow) <= sameLevelTolerance
    bool wlSameTDH = tdhActive and wlActive and math.abs(weekLow - dayHigh) <= sameLevelTolerance
    bool wlSameTDL = tdlActive and wlActive and math.abs(weekLow - dayLow) <= sameLevelTolerance
    bool wlSameWH = whActive and wlActive and math.abs(weekLow - weekHigh) <= sameLevelTolerance
    bool mhSamePDH = pdhActive and mhActive and math.abs(monthHigh - previousDayHigh) <= sameLevelTolerance
    bool mhSamePDL = pdlActive and mhActive and math.abs(monthHigh - previousDayLow) <= sameLevelTolerance
    bool mhSameTDH = tdhActive and mhActive and math.abs(monthHigh - dayHigh) <= sameLevelTolerance
    bool mhSameTDL = tdlActive and mhActive and math.abs(monthHigh - dayLow) <= sameLevelTolerance
    bool mhSameWH = whActive and mhActive and math.abs(monthHigh - weekHigh) <= sameLevelTolerance
    bool mhSameWL = wlActive and mhActive and math.abs(monthHigh - weekLow) <= sameLevelTolerance
    bool mlSamePDH = pdhActive and mlActive and math.abs(monthLow - previousDayHigh) <= sameLevelTolerance
    bool mlSamePDL = pdlActive and mlActive and math.abs(monthLow - previousDayLow) <= sameLevelTolerance
    bool mlSameTDH = tdhActive and mlActive and math.abs(monthLow - dayHigh) <= sameLevelTolerance
    bool mlSameTDL = tdlActive and mlActive and math.abs(monthLow - dayLow) <= sameLevelTolerance
    bool mlSameWH = whActive and mlActive and math.abs(monthLow - weekHigh) <= sameLevelTolerance
    bool mlSameWL = wlActive and mlActive and math.abs(monthLow - weekLow) <= sameLevelTolerance
    bool mlSameMH = mhActive and mlActive and math.abs(monthLow - monthHigh) <= sameLevelTolerance
 
    int pdhStack = 0
    int pdlStack = (pdlSame ? 1 : 0)
    int tdhStack = (tdhSamePDH ? 1 : 0) + (tdhSamePDL ? 1 : 0)
    int tdlStack = (tdlSamePDH ? 1 : 0) + (tdlSamePDL ? 1 : 0) + (tdlSameTDH ? 1 : 0)
    int whStack = (whSamePDH ? 1 : 0) + (whSamePDL ? 1 : 0) + (whSameTDH ? 1 : 0) + (whSameTDL ? 1 : 0)
    int wlStack = (wlSamePDH ? 1 : 0) + (wlSamePDL ? 1 : 0) + (wlSameTDH ? 1 : 0) + (wlSameTDL ? 1 : 0) + (wlSameWH ? 1 : 0)
    int mhStack = (mhSamePDH ? 1 : 0) + (mhSamePDL ? 1 : 0) + (mhSameTDH ? 1 : 0) + (mhSameTDL ? 1 : 0) + (mhSameWH ? 1 : 0) + (mhSameWL ? 1 : 0)
    int mlStack = (mlSamePDH ? 1 : 0) + (mlSamePDL ? 1 : 0) + (mlSameTDH ? 1 : 0) + (mlSameTDL ? 1 : 0) + (mlSameWH ? 1 : 0) + (mlSameWL ? 1 : 0) + (mlSameMH ? 1 : 0)
 
    pdhLabel := f_updateKeyLabel(pdhLabel, previousDayHigh, previousDayHigh + labelStep * pdhStack, "PDH", showPDH, pdhColor)
    pdlLabel := f_updateKeyLabel(pdlLabel, previousDayLow, previousDayLow + labelStep * pdlStack, "PDL", showPDL, pdlColor)
    tdhLabel := f_updateKeyLabel(tdhLabel, dayHigh, dayHigh + labelStep * tdhStack, "TDH", showTDH, tdhColor)
    tdlLabel := f_updateKeyLabel(tdlLabel, dayLow, dayLow + labelStep * tdlStack, "TDL", showTDL, tdlColor)
    whLabel := f_updateKeyLabel(whLabel, weekHigh, weekHigh + labelStep * whStack, "WH", showWH, whColor)
    wlLabel := f_updateKeyLabel(wlLabel, weekLow, weekLow + labelStep * wlStack, "WL", showWL, wlColor)
    mhLabel := f_updateKeyLabel(mhLabel, monthHigh, monthHigh + labelStep * mhStack, "MH", showMH, mhColor)
    mlLabel := f_updateKeyLabel(mlLabel, monthLow, monthLow + labelStep * mlStack, "ML", showML, mlColor)
 
 
 
if bullishSignal and showTargets
 
    bullT1Line := line.new(bar_index, bullT1, bar_index + 1, bullT1, extend=extend.right, color=color.green, style=line.style_dashed, width=1)
 
    bullT2Line := line.new(bar_index, bullT2, bar_index + 1, bullT2, extend=extend.right, color=color.green, style=line.style_dashed, width=1)
 
    bullT3Line := line.new(bar_index, bullT3, bar_index + 1, bullT3, extend=extend.right, color=color.green, style=line.style_dashed, width=2)
 
 
 
if bearishSignal and showTargets
 
    bearT1Line := line.new(bar_index, bearT1, bar_index + 1, bearT1, extend=extend.right, color=color.red, style=line.style_dashed, width=1)
 
    bearT2Line := line.new(bar_index, bearT2, bar_index + 1, bearT2, extend=extend.right, color=color.red, style=line.style_dashed, width=1)
 
    bearT3Line := line.new(bar_index, bearT3, bar_index + 1, bearT3, extend=extend.right, color=color.red, style=line.style_dashed, width=2)
 
 
 
if bullishBreakout and showTargets
 
    if not na(bullT1Line)
 
        line.set_y1(bullT1Line, bullT1)
 
        line.set_y2(bullT1Line, bullT1)
 
    if not na(bullT2Line)
 
        line.set_y1(bullT2Line, bullT2)
 
        line.set_y2(bullT2Line, bullT2)
 
    if not na(bullT3Line)
 
        line.set_y1(bullT3Line, bullT3)
 
        line.set_y2(bullT3Line, bullT3)
 
 
 
if bearishBreakdown and showTargets
 
    if not na(bearT1Line)
 
        line.set_y1(bearT1Line, bearT1)
 
        line.set_y2(bearT1Line, bearT1)
 
    if not na(bearT2Line)
 
        line.set_y1(bearT2Line, bearT2)
 
        line.set_y2(bearT2Line, bearT2)
 
    if not na(bearT3Line)
 
        line.set_y1(bearT3Line, bearT3)
 
        line.set_y2(bearT3Line, bearT3)
 
 
 
if bullishSignal and showLabels
 
    label newBullLabel = label.new(bar_index, low, "BULL BREAKOUT\nT1: " + str.tostring(bullT1, format.mintick) + "\nT2: " + str.tostring(bullT2, format.mintick) + "\nT3: " + str.tostring(bullT3, format.mintick), style=label.style_label_up, color=color.green, textcolor=color.white)
 
    array.push(breakoutLabels, newBullLabel)
 
 
 
if bearishSignal and showLabels
 
    label newBearLabel = label.new(bar_index, high, "BEAR BREAKDOWN\nT1: " + str.tostring(bearT1, format.mintick) + "\nT2: " + str.tostring(bearT2, format.mintick) + "\nT3: " + str.tostring(bearT3, format.mintick), style=label.style_label_down, color=color.red, textcolor=color.white)
 
    array.push(breakoutLabels, newBearLabel)
 
 
 
//══════════════════════════════════════════════════════════════════════════════
 
// ALERTE ENGINE (alertcondition)
 
//══════════════════════════════════════════════════════════════════════════════
 
 
 
alertcondition(bullAlertSignal, title="Bullish ORB Breakout (Mentor Filters)", message="Bullish ORB breakout passed configured mentor-style filters.")
 
alertcondition(bearAlertSignal, title="Bearish ORB Breakdown (Mentor Filters)", message="Bearish ORB breakdown passed configured mentor-style filters.")
 
alertcondition(anyAlertSignal, title="ORB Breakout - Bullish or Bearish", message="ORB breakout passed configured mentor-style filters.")
 
alertcondition(bull15Signal or bear15Signal, title="15-Min Window Breakout", message="15-minute opening-window breakout passed configured filters.")
 
alertcondition(bull30Signal or bear30Signal, title="30-Min Window Breakout", message="30-minute opening-window breakout passed configured filters.")
 
alertcondition(bull45Signal or bear45Signal, title="45-Min Window Breakout", message="45-minute opening-window breakout passed configured filters.")
 
alertcondition(bull60Signal or bear60Signal, title="1-Hour Window Breakout", message="1-hour opening-window breakout passed configured filters.")
 
alertcondition(bull15Signal or bear15Signal or bull30Signal or bear30Signal or bull45Signal or bear45Signal or bull60Signal or bear60Signal, title="Any Active Window Breakout", message="A 15/30/45/60-minute opening-window breakout passed configured filters.")
 
 
 
//══════════════════════════════════════════════════════════════════════════════
 
// RELATIVE VOLUME (RVOL) TABLE
 
//══════════════════════════════════════════════════════════════════════════════
 
 
 
groupRVOL = "Relative Volume (RVOL)"
 
showRVOLTable = input.bool(true, "Show Latest Daily RVOL Table", group=groupRVOL)
 
rvolLength = input.int(20, "Average Volume Lookback (Days)", minval=1, group=groupRVOL)
 
rvolThreshold = input.float(1.5, "High RVOL Threshold", minval=0.1, step=0.1, group=groupRVOL)
 
rvolPositionInput = input.string("Top Right", "Table Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=groupRVOL)
 
 
 
f_rvolTablePosition(string pos) =>
 
    pos == "Top Left" ? position.top_left : pos == "Bottom Right" ? position.bottom_right : pos == "Bottom Left" ? position.bottom_left : position.top_right
 
 
 
[dailyVolume, averagePriorVolume, latestDailyTime] = request.security(syminfo.tickerid, "D", [volume, ta.sma(volume[1], rvolLength), time], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
 
float latestRVOL = not na(averagePriorVolume) and averagePriorVolume > 0 ? dailyVolume / averagePriorVolume : na
 
 
 
var table rvolTable = table.new(f_rvolTablePosition(rvolPositionInput), 2, 5, border_width=1, frame_width=2, frame_color=color.rgb(55, 75, 100), border_color=color.rgb(45, 55, 70))
 
 
 
if barstate.islast
 
    if showRVOLTable
 
        color headerBg = color.rgb(20, 31, 50)
 
        color labelBg = color.rgb(39, 51, 70)
 
        color neutralBg = color.rgb(28, 39, 56)
 
        color highBg = color.rgb(0, 145, 95)
 
        color lowBg = color.rgb(166, 66, 54)
 
        color midBg = color.rgb(177, 119, 24)
 
        bool highRVOL = not na(latestRVOL) and latestRVOL >= rvolThreshold
 
        bool moderateRVOL = not na(latestRVOL) and latestRVOL >= 1.0 and latestRVOL < rvolThreshold
 
        color valueBg = highRVOL ? highBg : moderateRVOL ? midBg : lowBg
 
        color statusBg = na(latestRVOL) ? labelBg : highRVOL ? highBg : moderateRVOL ? midBg : lowBg
 
 
 
        string dateText = na(latestDailyTime) ? "N/A" : str.format_time(latestDailyTime, "dd MMM yyyy", "Asia/Kolkata")
 
        string avgDailyVolumeText = na(averagePriorVolume) ? "N/A" : str.tostring(averagePriorVolume, "#,###")
 
        string rvolText = na(latestRVOL) ? "N/A" : str.tostring(latestRVOL, "#.##") + "x"
 
        string statusText = na(latestRVOL) ? "WAITING FOR DATA" : highRVOL ? "HIGH RVOL | >= " + str.tostring(rvolThreshold, "#.##") + "x" : moderateRVOL ? "NORMAL ACTIVITY" : "BELOW THRESHOLD"
 
 
 
        table.cell(rvolTable, 0, 0, "  RELATIVE VOLUME  ", bgcolor=headerBg, text_color=color.rgb(205, 220, 240), text_size=size.small, text_halign=text.align_left)
 
        table.cell(rvolTable, 1, 0, syminfo.ticker, bgcolor=headerBg, text_color=color.white, text_size=size.small, text_halign=text.align_right)
 
        table.cell(rvolTable, 0, 1, "LATEST SESSION", bgcolor=labelBg, text_color=color.rgb(190, 205, 225), text_size=size.tiny, text_halign=text.align_left)
 
        table.cell(rvolTable, 1, 1, dateText, bgcolor=neutralBg, text_color=color.white, text_size=size.small, text_halign=text.align_right)
 
        table.cell(rvolTable, 0, 2, str.tostring(rvolLength) + "D AVG DAILY VOL", bgcolor=labelBg, text_color=color.rgb(190, 205, 225), text_size=size.tiny, text_halign=text.align_left)
 
        table.cell(rvolTable, 1, 2, avgDailyVolumeText, bgcolor=neutralBg, text_color=color.white, text_size=size.normal, text_halign=text.align_center)
 
        table.cell(rvolTable, 0, 3, "CURRENT DAILY RVOL", bgcolor=labelBg, text_color=color.rgb(190, 205, 225), text_size=size.tiny, text_halign=text.align_left)
 
        table.cell(rvolTable, 1, 3, rvolText, bgcolor=valueBg, text_color=color.white, text_size=size.large, text_halign=text.align_center)
 
        table.cell(rvolTable, 0, 4, "VOLUME STATUS", bgcolor=labelBg, text_color=color.rgb(190, 205, 225), text_size=size.tiny, text_halign=text.align_left)
 
        table.cell(rvolTable, 1, 4, statusText, bgcolor=statusBg, text_color=color.white, text_size=size.tiny, text_halign=text.align_center)
 
    else
 
        table.clear(rvolTable, 0, 0, 1, 4)
 
 
 
 
 
 
 
//══════════════════════════════════════════════════════════════════════════════
 
// HISTORICAL ALERT AUDIT PLOTS
 
//══════════════════════════════════════════════════════════════════════════════
 
 
 
// // 1. Shapes directly on the signal bar
 
// plotshape(bullAlertSignal or bull15Signal, title="Bull Alert Fired", style=shape.triangleup, 
 
//           location=location.belowbar, color=color.new(color.green, 0), size=size.small)
 
 
 
// plotshape(bearAlertSignal or bear15Signal, title="Bear Alert Fired", style=shape.triangledown, 
 
//           location=location.abovebar, color=color.new(color.red, 0), size=size.small)
 
 
 
// // 2. Full column highlight so you can spot triggers across days instantly
 
// bgcolor(bullAlertSignal or bull15Signal ? color.new(color.green, 85) : 
 
//         bearAlertSignal or bear15Signal ? color.new(color.red, 85) : na, 
 
//         title="Alert Triggered Highlight")

← 返回列表