Smart Money Zones PRO+_CRYPTOMASH

danny25m · study · 1074 行 · 点赞 13 · TradingView 原页

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

Pine Script

//@version=6
indicator("Smart Money Zones PRO+_CRYPTOMASH", overlay=true, max_boxes_count=500, max_lines_count=100, max_labels_count=500, max_polylines_count=10, max_bars_back=500)
 
// ─────────────────────────────────────────────────────
// DISPLAY
// ─────────────────────────────────────────────────────
showOb = input.bool(true, "Display Order Blocks", group="Display Settings")
showDash = input.bool(true, "Show Dashboard", group="Dashboard")
advancedDashboard = input.bool(true, "Use Advanced Dashboard", group="Dashboard")
 
// EMA SETTINGS — ALL OFF BY DEFAULT
showEma14 = input.bool(false, "Show 14 EMA", group="EMA Settings")
showEma21 = input.bool(false, "Show 21 EMA", group="EMA Settings")
showEma50 = input.bool(false, "Show 50 EMA", group="EMA Settings")
showEma100 = input.bool(false, "Show 100 EMA", group="EMA Settings")
showEma200 = input.bool(false, "Show 200 EMA", group="EMA Settings")
showEma800 = input.bool(false, "Show 800 EMA", group="EMA Settings")
 
// ORDER BLOCK COLORS
bullishObColor = input.color(color.green, "Bullish OB Color", group="Order Block Colors")
bearishObColor = input.color(color.red, "Bearish OB Color", group="Order Block Colors")
bullishObTextColor = input.color(color.green, "Bullish OB Text Color", group="Order Block Colors")
bearishObTextColor = input.color(color.red, "Bearish OB Text Color", group="Order Block Colors")
 
// VWAP
showVwap = input.bool(true, "Show VWAP: Previous Day + Today Only", group="VWAP")
vwapWidth = input.int(2, "Line Width", minval=1, maxval=4, group="VWAP")
 
// HTF 1
showHtf1 = input.bool(true, "Show HTF 1", group="HTF 1")
htf1Res = input.timeframe("240", "Timeframe", group="HTF 1")
htf1Count = input.int(5, "Candles Per Timeframe", minval=1, maxval=5, group="HTF 1")
htf1BullColor = input.color(color.green, "Bullish Color", group="HTF 1")
htf1BearColor = input.color(color.red, "Bearish Color", group="HTF 1")
htf1Transp = input.int(35, "Body Transparency", minval=0, maxval=100, group="HTF 1")
useHtf1Bias = input.bool(true, "Include In Advanced Bias", group="HTF 1")
 
// HTF 2
showHtf2 = input.bool(true, "Show HTF 2", group="HTF 2")
htf2Res = input.timeframe("1D", "Timeframe", group="HTF 2")
htf2Count = input.int(2, "Candles Per Timeframe", minval=1, maxval=5, group="HTF 2")
htf2BullColor = input.color(color.aqua, "Bullish Color", group="HTF 2")
htf2BearColor = input.color(color.orange, "Bearish Color", group="HTF 2")
htf2Transp = input.int(35, "Body Transparency", minval=0, maxval=100, group="HTF 2")
useHtf2Bias = input.bool(true, "Include In Advanced Bias", group="HTF 2")
 
// HTF 3
showHtf3 = input.bool(false, "Show HTF 3", group="HTF 3")
htf3Res = input.timeframe("D", "Timeframe", group="HTF 3")
htf3Count = input.int(1, "Candles Per Timeframe", minval=1, maxval=5, group="HTF 3")
htf3BullColor = input.color(color.lime, "Bullish Color", group="HTF 3")
htf3BearColor = input.color(color.red, "Bearish Color", group="HTF 3")
htf3Transp = input.int(35, "Body Transparency", minval=0, maxval=100, group="HTF 3")
useHtf3Bias = input.bool(true, "Include In Advanced Bias", group="HTF 3")
 
// HTF 4
showHtf4 = input.bool(false, "Show HTF 4", group="HTF 4")
htf4Res = input.timeframe("W", "Timeframe", group="HTF 4")
htf4Count = input.int(1, "Candles Per Timeframe", minval=1, maxval=5, group="HTF 4")
htf4BullColor = input.color(color.aqua, "Bullish Color", group="HTF 4")
htf4BearColor = input.color(color.orange, "Bearish Color", group="HTF 4")
htf4Transp = input.int(35, "Body Transparency", minval=0, maxval=100, group="HTF 4")
useHtf4Bias = input.bool(true, "Include In Advanced Bias", group="HTF 4")
 
// HTF 5
showHtf5 = input.bool(false, "Show HTF 5", group="HTF 5")
htf5Res = input.timeframe("M", "Timeframe", group="HTF 5")
htf5Count = input.int(1, "Candles Per Timeframe", minval=1, maxval=5, group="HTF 5")
htf5BullColor = input.color(color.lime, "Bullish Color", group="HTF 5")
htf5BearColor = input.color(color.red, "Bearish Color", group="HTF 5")
htf5Transp = input.int(35, "Body Transparency", minval=0, maxval=100, group="HTF 5")
useHtf5Bias = input.bool(true, "Include In Advanced Bias", group="HTF 5")
 
// HTF POSITION
projectionGap = input.int(8, "Distance From Price", minval=2, maxval=100, group="HTF Candle Position")
projectionSpacing = input.int(10, "Space Between Timeframe Groups", minval=4, maxval=100, group="HTF Candle Position")
projectionWidth = input.int(4, "Candle Body Width", minval=2, maxval=8, group="HTF Candle Position")
candleSpacing = input.int(2, "Space Between Candles Within Group", minval=1, maxval=20, group="HTF Candle Position")
showCountdown = input.bool(true, "Show Candle Countdown", group="HTF Candle Position")
showLevels = input.bool(false, "Show Current HTF High/Low Guides", group="HTF Candle Position")
 
// ─────────────────────────────────────────────────────
// PREVIOUS-DAY VOLUME PROFILE
// ─────────────────────────────────────────────────────
showPreviousVp = input.bool(true, "Show Previous Day Volume Profile", group="Previous Day Volume Profile")
vpRows = input.int(24, "Number Of Price Rows", minval=8, maxval=100, group="Previous Day Volume Profile")
vpWidth = input.int(20, "Maximum Profile Width", minval=5, maxval=100, group="Previous Day Volume Profile")
vpGap = input.int(6, "Distance To Right Of HTF 2", minval=2, maxval=50, group="Previous Day Volume Profile")
vpColor = input.color(color.new(color.blue, 50), "Profile Color", group="Previous Day Volume Profile")
vpValueAreaColor = input.color(color.new(color.aqua, 40), "Value Area Color", group="Previous Day Volume Profile")
vpPocColor = input.color(color.yellow, "POC Color", group="Previous Day Volume Profile")
vpValueAreaPercent = input.int(70, "Value Area Percent", minval=1, maxval=100, group="Previous Day Volume Profile")
vpShowPoc = input.bool(true, "Show Point Of Control", group="Previous Day Volume Profile")
vpShowValueArea = input.bool(true, "Show Value Area High / Low", group="Previous Day Volume Profile")
vpShowLabels = input.bool(true, "Show Profile Labels", group="Previous Day Volume Profile")
 
// DAILY LEVELS
showDailyHL = input.bool(true, "Show Daily High / Low", group="Daily High / Low")
dailyHighColor = input.color(color.red, "Daily High Color", group="Daily High / Low")
dailyLowColor = input.color(color.lime, "Daily Low Color", group="Daily High / Low")
dailyHLWidth = input.int(1, "Line Width", minval=1, maxval=4, group="Daily High / Low")
dailyHLExtension = input.int(5, "Extend Beyond Current Candle", minval=1, maxval=100, group="Daily High / Low")
showDailyHLLabels = input.bool(true, "Show DH / DL Labels", group="Daily High / Low")
 
showPreviousHL = input.bool(true, "Show Previous Day High / Low", group="Previous Day High / Low")
previousHighColor = input.color(color.orange, "PDH Color", group="Previous Day High / Low")
previousLowColor = input.color(color.aqua, "PDL Color", group="Previous Day High / Low")
previousHLWidth = input.int(2, "Line Width", minval=1, maxval=4, group="Previous Day High / Low")
previousHLExtension = input.int(15, "Extend Beyond Current Candle", minval=1, maxval=100, group="Previous Day High / Low")
showPreviousHLLabels = input.bool(true, "Show PDH / PDL Labels", group="Previous Day High / Low")
 
// PDH / PDL RANGE FILL
showPreviousRangeFill = input.bool(true, "Show Color Between PDH And PDL", group="PDH / PDL Range Fill")
previousRangeFillColor = input.color(color.new(color.blue, 92), "Fill Color / Transparency", group="PDH / PDL Range Fill")
 
// ADVANCED BIAS
confirmedHtfBias = input.bool(true, "Use Closed HTF Candles For Advanced Bias", group="Advanced Bias")
requireHtfAgreement = input.bool(false, "Require All Selected HTFs For Setups", group="Advanced Bias")
requireVwapFilter = input.bool(false, "Require Setup Close On Correct Side Of VWAP", group="Advanced Bias")
 
// SWEEPS
enableSweeps = input.bool(true, "Enable PDH / PDL Sweep Detection", group="Liquidity Sweeps")
showSweepMarkers = input.bool(true, "Show PDH / PDL Sweep Labels: Current Day Only", group="Liquidity Sweeps")
minimumSweepTicks = input.int(1, "Minimum Penetration In Ticks", minval=1, maxval=1000, group="Liquidity Sweeps")
reclaimBars = input.int(0, "Extra Bars Allowed To Reclaim Level", minval=0, maxval=20, group="Liquidity Sweeps")
oneSweepPerDay = input.bool(true, "One Sweep Per Level Per Day", group="Liquidity Sweeps")
 
// BACKGROUND SETUPS
swingLength = input.int(3, "Swing Confirmation Length", minval=1, maxval=30, group="Background Setup Logic")
enableSetups = input.bool(true, "Enable Sweep-To-Structure Setup Logic", group="Background Setup Logic")
setupExpiryBars = input.int(30, "Maximum Bars After Sweep", minval=1, maxval=500, group="Background Setup Logic")
 
// ADVANCED ORDER BLOCKS
advancedOb = input.bool(true, "Use Advanced Zone Lifecycle", group="Advanced Order Blocks")
obLookback = input.int(300, "Lookback Bars", minval=20, maxval=300, group="Advanced Order Blocks")
maxVisibleOb = input.int(15, "Maximum Visible Zones", minval=1, maxval=50, group="Advanced Order Blocks")
showObText = input.bool(true, "Show Zone State Text", group="Advanced Order Blocks")
keepTouchedOb = input.bool(true, "Keep Touched Zones", group="Advanced Order Blocks")
showInvalidOb = input.bool(false, "Show Invalidated Zones", group="Advanced Order Blocks")
obInvalidation = input.string("Close", "Invalidate Beyond Far Edge Using", options=["Close", "Wick"], group="Advanced Order Blocks")
partialFillPercent = input.int(50, "Partial-Fill Threshold Percent", minval=1, maxval=100, group="Advanced Order Blocks")
requireDisplacement = input.bool(false, "Require Breakout-Candle Displacement", group="Advanced Order Blocks")
minimumDisplacementAtr = input.float(1.0, "Minimum Breakout Range / ATR", minval=0.1, maxval=10.0, step=0.1, group="Advanced Order Blocks")
 
// ALERTS
enableSweepAlerts = input.bool(true, "Enable Sweep Alerts", group="Alerts")
enableSetupAlerts = input.bool(true, "Enable Confirmed Setup Alerts", group="Alerts")
enableObAlerts = input.bool(true, "Enable Fresh Order-Block Retest Alerts", group="Alerts")
enableHtfAlerts = input.bool(true, "Enable Full HTF Agreement Alerts", group="Alerts")
 
// ─────────────────────────────────────────────────────
// CURRENT-TIMEFRAME CALCULATIONS
// ─────────────────────────────────────────────────────
volMA = ta.sma(volume, 20)
volRatio = volume / math.max(volMA, 1)
priceSpread = high - low
avgSpread = ta.sma(priceSpread, 20)
spreadRatio = priceSpread / math.max(avgSpread, 0.0001)
atrValue = ta.atr(14)
 
bool newTradingDay = timeframe.change("D")
int currentTradingDayStart = time("D")
 
// OPTIONAL EMAS
ema14Value = ta.ema(close, 14)
ema21Value = ta.ema(close, 21)
ema50Value = ta.ema(close, 50)
ema100Value = ta.ema(close, 100)
ema200Value = ta.ema(close, 200)
ema800Value = ta.ema(close, 800)
 
plot(showEma14 ? ema14Value : na, title="14 EMA", color=color.aqua, linewidth=1, force_overlay=true)
plot(showEma21 ? ema21Value : na, title="21 EMA", color=color.orange, linewidth=1, force_overlay=true)
plot(showEma50 ? ema50Value : na, title="50 EMA", color=color.lime, linewidth=1, force_overlay=true)
plot(showEma100 ? ema100Value : na, title="100 EMA", color=color.fuchsia, linewidth=1, force_overlay=true)
plot(showEma200 ? ema200Value : na, title="200 EMA", color=color.red, linewidth=2, force_overlay=true)
plot(showEma800 ? ema800Value : na, title="800 EMA", color=color.blue, linewidth=2, force_overlay=true)
 
// PREVIOUS-DAY DATA
[pdhPrice, pdlPrice, previousDailyOpenTime] = request.security(syminfo.tickerid, "D", [high[1], low[1], time[1]], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
 
// ─────────────────────────────────────────────────────
// PDH / PDL RANGE FILL
// ─────────────────────────────────────────────────────
var box previousRangeFill = box.new(left=na, top=na, right=na, bottom=na, xloc=xloc.bar_time, border_color=na, bgcolor=na, force_overlay=true)
 
if barstate.islast
    bool validPreviousRange = showPreviousHL and showPreviousRangeFill and timeframe.isintraday and not na(pdhPrice) and not na(pdlPrice) and not na(previousDailyOpenTime)
 
    if validPreviousRange
        int rangeIntervalMs = int(timeframe.in_seconds() * 1000)
        int rangeRightTime = time + rangeIntervalMs * previousHLExtension
        box.set_lefttop(previousRangeFill, previousDailyOpenTime, pdhPrice)
        box.set_rightbottom(previousRangeFill, rangeRightTime, pdlPrice)
        box.set_bgcolor(previousRangeFill, previousRangeFillColor)
        box.set_border_color(previousRangeFill, na)
    else
        box.set_lefttop(previousRangeFill, na, na)
        box.set_rightbottom(previousRangeFill, na, na)
        box.set_bgcolor(previousRangeFill, na)
 
// ─────────────────────────────────────────────────────
// VWAP: PREVIOUS TRADING DAY + TODAY
// ─────────────────────────────────────────────────────
vwapValue = ta.vwap(hlc3, newTradingDay or barstate.isfirst)
 
var array<chart.point> currentVwapPoints = array.new<chart.point>()
var array<chart.point> previousVwapPoints = array.new<chart.point>()
var polyline currentVwapDrawing = na
var polyline previousVwapDrawing = na
 
if newTradingDay
    previousVwapPoints := currentVwapPoints
    currentVwapPoints := array.new<chart.point>()
 
if not na(vwapValue)
    array.push(currentVwapPoints, chart.point.from_time(time, vwapValue))
    if array.size(currentVwapPoints) > 10000
        array.shift(currentVwapPoints)
 
if barstate.islast
    if not na(currentVwapDrawing)
        polyline.delete(currentVwapDrawing)
        currentVwapDrawing := na
 
    if not na(previousVwapDrawing)
        polyline.delete(previousVwapDrawing)
        previousVwapDrawing := na
 
    if showVwap and timeframe.isintraday
        if array.size(previousVwapPoints) >= 2
            previousVwapDrawing := polyline.new(points=previousVwapPoints, curved=false, closed=false, xloc=xloc.bar_time, line_color=color.yellow, line_style=line.style_solid, line_width=vwapWidth, force_overlay=true)
 
        if array.size(currentVwapPoints) >= 2
            currentVwapDrawing := polyline.new(points=currentVwapPoints, curved=false, closed=false, xloc=xloc.bar_time, line_color=color.yellow, line_style=line.style_solid, line_width=vwapWidth, force_overlay=true)
 
// ─────────────────────────────────────────────────────
// VOLUME PROFILE SOURCE DATA
// ─────────────────────────────────────────────────────
var array<float> vpCurrentHighs = array.new<float>()
var array<float> vpCurrentLows = array.new<float>()
var array<float> vpCurrentVolumes = array.new<float>()
 
var array<float> vpPreviousHighs = array.new<float>()
var array<float> vpPreviousLows = array.new<float>()
var array<float> vpPreviousVolumes = array.new<float>()
 
var bool vpCurrentTruncated = false
var bool vpPreviousTruncated = false
var int vpPreviousSession = na
 
if newTradingDay
    vpPreviousHighs := vpCurrentHighs
    vpPreviousLows := vpCurrentLows
    vpPreviousVolumes := vpCurrentVolumes
    vpPreviousTruncated := vpCurrentTruncated
    vpPreviousSession := currentTradingDayStart[1]
 
    vpCurrentHighs := array.new<float>()
    vpCurrentLows := array.new<float>()
    vpCurrentVolumes := array.new<float>()
    vpCurrentTruncated := false
 
if timeframe.isintraday and showPreviousVp
    array.push(vpCurrentHighs, high)
    array.push(vpCurrentLows, low)
    array.push(vpCurrentVolumes, math.max(nz(volume, 0), 0))
 
    if array.size(vpCurrentHighs) > 20000
        array.shift(vpCurrentHighs)
        array.shift(vpCurrentLows)
        array.shift(vpCurrentVolumes)
        vpCurrentTruncated := true
 
// ─────────────────────────────────────────────────────
// HTF DATA
// ─────────────────────────────────────────────────────
f_getHtfData(simple string tf) =>
    request.security(syminfo.tickerid, tf, [open, high, low, close, time_close, open[1], high[1], low[1], close[1], open[2], high[2], low[2], close[2], open[3], high[3], low[3], close[3], open[4], high[4], low[4], close[4]], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
 
[h1O, h1H, h1L, h1C, h1End, h1O1, h1H1, h1L1, h1C1, h1O2, h1H2, h1L2, h1C2, h1O3, h1H3, h1L3, h1C3, h1O4, h1H4, h1L4, h1C4] = f_getHtfData(htf1Res)
[h2O, h2H, h2L, h2C, h2End, h2O1, h2H1, h2L1, h2C1, h2O2, h2H2, h2L2, h2C2, h2O3, h2H3, h2L3, h2C3, h2O4, h2H4, h2L4, h2C4] = f_getHtfData(htf2Res)
[h3O, h3H, h3L, h3C, h3End, h3O1, h3H1, h3L1, h3C1, h3O2, h3H2, h3L2, h3C2, h3O3, h3H3, h3L3, h3C3, h3O4, h3H4, h3L4, h3C4] = f_getHtfData(htf3Res)
[h4O, h4H, h4L, h4C, h4End, h4O1, h4H1, h4L1, h4C1, h4O2, h4H2, h4L2, h4C2, h4O3, h4H3, h4L3, h4C3, h4O4, h4H4, h4L4, h4C4] = f_getHtfData(htf4Res)
[h5O, h5H, h5L, h5C, h5End, h5O1, h5H1, h5L1, h5C1, h5O2, h5H2, h5L2, h5C2, h5O3, h5H3, h5L3, h5C3, h5O4, h5H4, h5L4, h5C4] = f_getHtfData(htf5Res)
 
// CONFIRMED HTF BIAS
f_getConfirmedBias(simple string tf) =>
    request.security(syminfo.tickerid, tf, [open[1], close[1]], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
 
[b1O, b1C] = f_getConfirmedBias(htf1Res)
[b2O, b2C] = f_getConfirmedBias(htf2Res)
[b3O, b3C] = f_getConfirmedBias(htf3Res)
[b4O, b4C] = f_getConfirmedBias(htf4Res)
[b5O, b5C] = f_getConfirmedBias(htf5Res)
 
f_direction(float o, float c) =>
    int result = 0
    if not na(o) and not na(c)
        result := c > o ? 1 : c < o ? -1 : 0
    result
 
int bias1 = confirmedHtfBias ? f_direction(b1O, b1C) : f_direction(h1O, h1C)
int bias2 = confirmedHtfBias ? f_direction(b2O, b2C) : f_direction(h2O, h2C)
int bias3 = confirmedHtfBias ? f_direction(b3O, b3C) : f_direction(h3O, h3C)
int bias4 = confirmedHtfBias ? f_direction(b4O, b4C) : f_direction(h4O, h4C)
int bias5 = confirmedHtfBias ? f_direction(b5O, b5C) : f_direction(h5O, h5C)
 
bool selected1 = showHtf1 and useHtf1Bias
bool selected2 = showHtf2 and useHtf2Bias
bool selected3 = showHtf3 and useHtf3Bias
bool selected4 = showHtf4 and useHtf4Bias
bool selected5 = showHtf5 and useHtf5Bias
 
int selectedCount = (selected1 ? 1 : 0) + (selected2 ? 1 : 0) + (selected3 ? 1 : 0) + (selected4 ? 1 : 0) + (selected5 ? 1 : 0)
int bullishCount = (selected1 and bias1 == 1 ? 1 : 0) + (selected2 and bias2 == 1 ? 1 : 0) + (selected3 and bias3 == 1 ? 1 : 0) + (selected4 and bias4 == 1 ? 1 : 0) + (selected5 and bias5 == 1 ? 1 : 0)
int bearishCount = (selected1 and bias1 == -1 ? 1 : 0) + (selected2 and bias2 == -1 ? 1 : 0) + (selected3 and bias3 == -1 ? 1 : 0) + (selected4 and bias4 == -1 ? 1 : 0) + (selected5 and bias5 == -1 ? 1 : 0)
 
bool allHtfBull = selectedCount > 0 and bullishCount == selectedCount
bool allHtfBear = selectedCount > 0 and bearishCount == selectedCount
bool htf1Bull = h1C > h1O
bool htf2Bull = h2C > h2O
 
// COUNTDOWN
f_countdown(int endTime) =>
    string result = ""
    if not na(endTime)
        int secondsLeft = int(math.max(0.0, math.floor((endTime - timenow) / 1000.0)))
        int hoursLeft = int(math.floor(secondsLeft / 3600.0))
        int minutesLeft = int(math.floor((secondsLeft % 3600) / 60.0))
        int remainingSeconds = secondsLeft % 60
        result := str.tostring(hoursLeft, "00") + ":" + str.tostring(minutesLeft, "00") + ":" + str.tostring(remainingSeconds, "00")
    result
 
// ─────────────────────────────────────────────────────
// HTF / PROFILE POSITIONS
// ─────────────────────────────────────────────────────
f_groupWidth(int count) =>
    count * projectionWidth + (count - 1) * candleSpacing + projectionSpacing
 
int htf1Offset = projectionGap
int htf2Offset = htf1Offset + (showHtf1 ? f_groupWidth(htf1Count) : 0)
 
int htf2GroupRight = htf2Offset + (showHtf2 ? f_groupWidth(htf2Count) - projectionSpacing : 0)
int vpStartOffset = htf2GroupRight + vpGap
int vpEndOffset = vpStartOffset + vpWidth
 
int htf3Offset = showPreviousVp ? vpEndOffset + projectionSpacing : htf2Offset + (showHtf2 ? f_groupWidth(htf2Count) : 0)
int htf4Offset = htf3Offset + (showHtf3 ? f_groupWidth(htf3Count) : 0)
int htf5Offset = htf4Offset + (showHtf4 ? f_groupWidth(htf4Count) : 0)
 
int layoutExtent = projectionGap
layoutExtent := showHtf1 ? math.max(layoutExtent, htf1Offset + f_groupWidth(htf1Count) - projectionSpacing) : layoutExtent
layoutExtent := showHtf2 ? math.max(layoutExtent, htf2Offset + f_groupWidth(htf2Count) - projectionSpacing) : layoutExtent
layoutExtent := showPreviousVp ? math.max(layoutExtent, vpEndOffset + 4) : layoutExtent
layoutExtent := showHtf3 ? math.max(layoutExtent, htf3Offset + f_groupWidth(htf3Count) - projectionSpacing) : layoutExtent
layoutExtent := showHtf4 ? math.max(layoutExtent, htf4Offset + f_groupWidth(htf4Count) - projectionSpacing) : layoutExtent
layoutExtent := showHtf5 ? math.max(layoutExtent, htf5Offset + f_groupWidth(htf5Count) - projectionSpacing) : layoutExtent
 
float htfLayoutScale = math.min(1.0, 490.0 / math.max(layoutExtent, 1))
 
// ─────────────────────────────────────────────────────
// FIXED HTF DRAWING SLOTS
// ─────────────────────────────────────────────────────
var array<box> htfBodies = array.new<box>()
var array<line> htfWicks = array.new<line>()
var array<label> htfNames = array.new<label>()
var array<label> htfTimers = array.new<label>()
var array<line> htfHighGuides = array.new<line>()
var array<line> htfLowGuides = array.new<line>()
 
if barstate.isfirst
    for slot = 0 to 24
        array.push(htfBodies, box.new(left=na, top=na, right=na, bottom=na, xloc=xloc.bar_index, force_overlay=true))
        array.push(htfWicks, line.new(x1=na, y1=na, x2=na, y2=na, xloc=xloc.bar_index, force_overlay=true))
        array.push(htfNames, label.new(x=na, y=na, text="", xloc=xloc.bar_index, style=label.style_label_down, color=color.new(color.black, 100), textcolor=color.silver, size=size.small, force_overlay=true))
        array.push(htfTimers, label.new(x=na, y=na, text="", xloc=xloc.bar_index, style=label.style_label_up, color=color.new(color.black, 100), textcolor=color.silver, size=size.small, force_overlay=true))
 
    for groupSlot = 0 to 4
        array.push(htfHighGuides, line.new(x1=na, y1=na, x2=na, y2=na, xloc=xloc.bar_index, style=line.style_dotted, force_overlay=true))
        array.push(htfLowGuides, line.new(x1=na, y1=na, x2=na, y2=na, xloc=xloc.bar_index, style=line.style_dotted, force_overlay=true))
 
if barstate.islast
    for slot = 0 to 24
        box body = array.get(htfBodies, slot)
        line wick = array.get(htfWicks, slot)
        label nameLabel = array.get(htfNames, slot)
        label timerLabel = array.get(htfTimers, slot)
 
        box.set_lefttop(body, na, na)
        box.set_rightbottom(body, na, na)
        line.set_xy1(wick, na, na)
        line.set_xy2(wick, na, na)
        label.set_xy(nameLabel, na, na)
        label.set_text(nameLabel, "")
        label.set_xy(timerLabel, na, na)
        label.set_text(timerLabel, "")
 
    for groupSlot = 0 to 4
        line highGuide = array.get(htfHighGuides, groupSlot)
        line lowGuide = array.get(htfLowGuides, groupSlot)
        line.set_xy1(highGuide, na, na)
        line.set_xy2(highGuide, na, na)
        line.set_xy1(lowGuide, na, na)
        line.set_xy2(lowGuide, na, na)
 
// DRAW A SINGLE HTF CANDLE
f_drawHtfSlot(int slot, int groupSlot, float o, float h, float l, float c, int endTime, string tf, int rawOffset, color bullColor, color bearColor, int transparency, bool isCurrent) =>
    if not na(o) and not na(h) and not na(l) and not na(c)
        box body = array.get(htfBodies, slot)
        line wick = array.get(htfWicks, slot)
        label nameLabel = array.get(htfNames, slot)
        label timerLabel = array.get(htfTimers, slot)
 
        int leftOffset = int(math.round(rawOffset * htfLayoutScale))
        int rightOffset = int(math.round((rawOffset + projectionWidth) * htfLayoutScale))
        rightOffset := math.max(rightOffset, leftOffset + 1)
 
        int leftX = bar_index + leftOffset
        int rightX = bar_index + rightOffset
        int middleX = leftX + int(math.floor((rightX - leftX) / 2.0))
 
        float bodyTop = math.max(o, c)
        float bodyBottom = math.min(o, c)
        if bodyTop - bodyBottom < syminfo.mintick
            bodyTop := bodyBottom + syminfo.mintick
 
        color candleColor = c >= o ? bullColor : bearColor
 
        box.set_lefttop(body, leftX, bodyTop)
        box.set_rightbottom(body, rightX, bodyBottom)
        box.set_bgcolor(body, color.new(candleColor, transparency))
        box.set_border_color(body, candleColor)
        box.set_border_width(body, 1)
 
        line.set_xy1(wick, middleX, h)
        line.set_xy2(wick, middleX, l)
        line.set_color(wick, candleColor)
        line.set_width(wick, 1)
 
        if isCurrent
            label.set_xy(nameLabel, middleX, h)
            label.set_text(nameLabel, tf)
            label.set_textcolor(nameLabel, color.silver)
            label.set_xy(timerLabel, middleX, l)
            label.set_text(timerLabel, showCountdown ? f_countdown(endTime) : "")
            label.set_textcolor(timerLabel, candleColor)
 
            if showLevels
                line highGuide = array.get(htfHighGuides, groupSlot)
                line lowGuide = array.get(htfLowGuides, groupSlot)
                line.set_xy1(highGuide, bar_index, h)
                line.set_xy2(highGuide, middleX, h)
                line.set_color(highGuide, color.new(candleColor, 25))
                line.set_xy1(lowGuide, bar_index, l)
                line.set_xy2(lowGuide, middleX, l)
                line.set_color(lowGuide, color.new(candleColor, 25))
 
// DRAW HTF GROUP
f_drawHtfGroup(int groupSlot, bool enabled, int count, string tf, int startOffset, color bullColor, color bearColor, int transparency, float o, float h, float l, float c, int endTime, float o1, float h1, float l1, float c1, float o2, float h2, float l2, float c2, float o3, float h3, float l3, float c3, float o4, float h4, float l4, float c4) =>
    if barstate.islast and enabled
        array<float> opens = array.from(o, o1, o2, o3, o4)
        array<float> highs = array.from(h, h1, h2, h3, h4)
        array<float> lows = array.from(l, l1, l2, l3, l4)
        array<float> closes = array.from(c, c1, c2, c3, c4)
 
        int step = projectionWidth + candleSpacing
 
        for candleIndex = 0 to count - 1
            int slot = groupSlot * 5 + candleIndex
            int candleOffset = startOffset + (count - 1 - candleIndex) * step
            f_drawHtfSlot(slot, groupSlot, array.get(opens, candleIndex), array.get(highs, candleIndex), array.get(lows, candleIndex), array.get(closes, candleIndex), endTime, tf, candleOffset, bullColor, bearColor, transparency, candleIndex == 0)
 
f_drawHtfGroup(0, showHtf1, htf1Count, htf1Res, htf1Offset, htf1BullColor, htf1BearColor, htf1Transp, h1O, h1H, h1L, h1C, h1End, h1O1, h1H1, h1L1, h1C1, h1O2, h1H2, h1L2, h1C2, h1O3, h1H3, h1L3, h1C3, h1O4, h1H4, h1L4, h1C4)
f_drawHtfGroup(1, showHtf2, htf2Count, htf2Res, htf2Offset, htf2BullColor, htf2BearColor, htf2Transp, h2O, h2H, h2L, h2C, h2End, h2O1, h2H1, h2L1, h2C1, h2O2, h2H2, h2L2, h2C2, h2O3, h2H3, h2L3, h2C3, h2O4, h2H4, h2L4, h2C4)
f_drawHtfGroup(2, showHtf3, htf3Count, htf3Res, htf3Offset, htf3BullColor, htf3BearColor, htf3Transp, h3O, h3H, h3L, h3C, h3End, h3O1, h3H1, h3L1, h3C1, h3O2, h3H2, h3L2, h3C2, h3O3, h3H3, h3L3, h3C3, h3O4, h3H4, h3L4, h3C4)
f_drawHtfGroup(3, showHtf4, htf4Count, htf4Res, htf4Offset, htf4BullColor, htf4BearColor, htf4Transp, h4O, h4H, h4L, h4C, h4End, h4O1, h4H1, h4L1, h4C1, h4O2, h4H2, h4L2, h4C2, h4O3, h4H3, h4L3, h4C3, h4O4, h4H4, h4L4, h4C4)
f_drawHtfGroup(4, showHtf5, htf5Count, htf5Res, htf5Offset, htf5BullColor, htf5BearColor, htf5Transp, h5O, h5H, h5L, h5C, h5End, h5O1, h5H1, h5L1, h5C1, h5O2, h5H2, h5L2, h5C2, h5O3, h5H3, h5L3, h5C3, h5O4, h5H4, h5L4, h5C4)
 
// ─────────────────────────────────────────────────────
// PREVIOUS-DAY VOLUME PROFILE CALCULATION
// ─────────────────────────────────────────────────────
var array<float> vpBins = array.new<float>(vpRows, 0.0)
var int vpBuiltSession = na
var float vpProfileHigh = na
var float vpProfileLow = na
var float vpRowSize = na
var float vpTotalVolume = 0.0
var float vpMaxVolume = 0.0
var int vpPocIndex = 0
var int vpVaLowIndex = 0
var int vpVaHighIndex = 0
 
if barstate.islast and showPreviousVp and timeframe.isintraday
    bool needVpBuild = not na(vpPreviousSession) and (na(vpBuiltSession) or vpBuiltSession != vpPreviousSession)
 
    if needVpBuild and array.size(vpPreviousHighs) > 0
        array.fill(vpBins, 0.0)
 
        vpProfileHigh := array.max(vpPreviousHighs)
        vpProfileLow := array.min(vpPreviousLows)
        vpRowSize := math.max((vpProfileHigh - vpProfileLow) / vpRows, syminfo.mintick / vpRows)
 
        for sourceIndex = 0 to array.size(vpPreviousHighs) - 1
            float sourceHigh = array.get(vpPreviousHighs, sourceIndex)
            float sourceLow = array.get(vpPreviousLows, sourceIndex)
            float sourceVolume = array.get(vpPreviousVolumes, sourceIndex)
            float sourceRange = sourceHigh - sourceLow
 
            if sourceVolume > 0
                if sourceRange <= 0
                    int rowIndex = int(math.floor((sourceLow - vpProfileLow) / vpRowSize))
                    rowIndex := math.max(0, math.min(vpRows - 1, rowIndex))
                    array.set(vpBins, rowIndex, array.get(vpBins, rowIndex) + sourceVolume)
                else
                    int firstRow = int(math.floor((sourceLow - vpProfileLow) / vpRowSize))
                    int lastRow = int(math.floor((sourceHigh - vpProfileLow) / vpRowSize))
                    firstRow := math.max(0, math.min(vpRows - 1, firstRow))
                    lastRow := math.max(0, math.min(vpRows - 1, lastRow))
 
                    for rowIndex = firstRow to lastRow
                        float rowBottom = vpProfileLow + rowIndex * vpRowSize
                        float rowTop = rowBottom + vpRowSize
                        float overlap = math.max(0.0, math.min(sourceHigh, rowTop) - math.max(sourceLow, rowBottom))
                        float allocatedVolume = sourceVolume * overlap / sourceRange
                        array.set(vpBins, rowIndex, array.get(vpBins, rowIndex) + allocatedVolume)
 
        vpTotalVolume := array.sum(vpBins)
        vpMaxVolume := array.max(vpBins)
        vpPocIndex := array.indexof(vpBins, vpMaxVolume)
        vpVaLowIndex := vpPocIndex
        vpVaHighIndex := vpPocIndex
 
        float accumulatedVolume = array.get(vpBins, vpPocIndex)
        float targetVolume = vpTotalVolume * vpValueAreaPercent / 100.0
 
        while accumulatedVolume < targetVolume and (vpVaLowIndex > 0 or vpVaHighIndex < vpRows - 1)
            float nextAbove = vpVaHighIndex < vpRows - 1 ? array.get(vpBins, vpVaHighIndex + 1) : -1.0
            float nextBelow = vpVaLowIndex > 0 ? array.get(vpBins, vpVaLowIndex - 1) : -1.0
 
            if nextAbove >= nextBelow
                vpVaHighIndex += 1
                accumulatedVolume += array.get(vpBins, vpVaHighIndex)
            else
                vpVaLowIndex -= 1
                accumulatedVolume += array.get(vpBins, vpVaLowIndex)
 
        vpBuiltSession := vpPreviousSession
 
// ─────────────────────────────────────────────────────
// VOLUME PROFILE DRAWINGS
// ─────────────────────────────────────────────────────
var array<box> vpRowBoxes = array.new<box>()
 
var line vpPocLine = line.new(x1=na, y1=na, x2=na, y2=na, xloc=xloc.bar_index, force_overlay=true)
var line vpVahLine = line.new(x1=na, y1=na, x2=na, y2=na, xloc=xloc.bar_index, style=line.style_dashed, force_overlay=true)
var line vpValLine = line.new(x1=na, y1=na, x2=na, y2=na, xloc=xloc.bar_index, style=line.style_dashed, force_overlay=true)
 
var label vpTitleLabel = label.new(x=na, y=na, text="", xloc=xloc.bar_index, style=label.style_label_down, color=color.new(color.black, 100), textcolor=color.silver, size=size.small, force_overlay=true)
var label vpPocLabel = label.new(x=na, y=na, text="", xloc=xloc.bar_index, style=label.style_label_left, color=color.new(color.black, 100), size=size.tiny, force_overlay=true)
var label vpVahLabel = label.new(x=na, y=na, text="", xloc=xloc.bar_index, style=label.style_label_left, color=color.new(color.black, 100), size=size.tiny, force_overlay=true)
var label vpValLabel = label.new(x=na, y=na, text="", xloc=xloc.bar_index, style=label.style_label_left, color=color.new(color.black, 100), size=size.tiny, force_overlay=true)
 
if barstate.isfirst
    for rowIndex = 0 to vpRows - 1
        array.push(vpRowBoxes, box.new(left=na, top=na, right=na, bottom=na, xloc=xloc.bar_index, border_color=color.new(color.black, 70), border_width=1, force_overlay=true))
 
if barstate.islast
    for rowIndex = 0 to vpRows - 1
        box rowBox = array.get(vpRowBoxes, rowIndex)
        box.set_lefttop(rowBox, na, na)
        box.set_rightbottom(rowBox, na, na)
 
    line.set_xy1(vpPocLine, na, na)
    line.set_xy2(vpPocLine, na, na)
    line.set_xy1(vpVahLine, na, na)
    line.set_xy2(vpVahLine, na, na)
    line.set_xy1(vpValLine, na, na)
    line.set_xy2(vpValLine, na, na)
 
    label.set_text(vpTitleLabel, "")
    label.set_text(vpPocLabel, "")
    label.set_text(vpVahLabel, "")
    label.set_text(vpValLabel, "")
 
    int profileLeftX = bar_index + int(math.round(vpStartOffset * htfLayoutScale))
    int profileRightX = bar_index + int(math.round(vpEndOffset * htfLayoutScale))
    profileRightX := math.max(profileRightX, profileLeftX + 1)
 
    bool validVp = showPreviousVp and timeframe.isintraday and not na(vpBuiltSession) and vpMaxVolume > 0
 
    if validVp
        int availableWidth = profileRightX - profileLeftX
 
        for rowIndex = 0 to vpRows - 1
            float rowVolume = array.get(vpBins, rowIndex)
 
            if rowVolume > 0
                int rowWidth = math.max(1, int(math.round(rowVolume / vpMaxVolume * availableWidth)))
                float rowBottom = vpProfileLow + rowIndex * vpRowSize
                float rowTop = rowBottom + vpRowSize
                bool insideValueArea = rowIndex >= vpVaLowIndex and rowIndex <= vpVaHighIndex
 
                color rowColor = insideValueArea ? vpValueAreaColor : vpColor
                if rowIndex == vpPocIndex and vpShowPoc
                    rowColor := vpPocColor
 
                box rowBox = array.get(vpRowBoxes, rowIndex)
                box.set_lefttop(rowBox, profileRightX - rowWidth, rowTop)
                box.set_rightbottom(rowBox, profileRightX, rowBottom)
                box.set_bgcolor(rowBox, rowColor)
                color barBorderColor = rowIndex == vpPocIndex and vpShowPoc ? color.new(vpPocColor, 20) : insideValueArea ? color.new(vpValueAreaColor, 30) : color.new(vpColor, 20)
                box.set_border_color(rowBox, barBorderColor)
                box.set_border_width(rowBox, 1)
 
        float pocPrice = vpProfileLow + (vpPocIndex + 0.5) * vpRowSize
        float vahPrice = vpProfileLow + (vpVaHighIndex + 1) * vpRowSize
        float valPrice = vpProfileLow + vpVaLowIndex * vpRowSize
 
        label.set_xy(vpTitleLabel, profileLeftX + int(math.floor(availableWidth / 2.0)), vpProfileHigh)
        label.set_text(vpTitleLabel, vpShowLabels ? (vpPreviousTruncated ? "PREV DAY VP\nPARTIAL DATA" : "PREVIOUS DAY VP") : "")
 
        if vpShowPoc
            line.set_xy1(vpPocLine, profileLeftX, pocPrice)
            line.set_xy2(vpPocLine, profileRightX, pocPrice)
            line.set_color(vpPocLine, vpPocColor)
            line.set_width(vpPocLine, 2)
 
            label.set_xy(vpPocLabel, profileRightX + 1, pocPrice)
            label.set_text(vpPocLabel, vpShowLabels ? "POC" : "")
            label.set_textcolor(vpPocLabel, vpPocColor)
 
        if vpShowValueArea
            line.set_xy1(vpVahLine, profileLeftX, vahPrice)
            line.set_xy2(vpVahLine, profileRightX, vahPrice)
            line.set_color(vpVahLine, vpValueAreaColor)
 
            line.set_xy1(vpValLine, profileLeftX, valPrice)
            line.set_xy2(vpValLine, profileRightX, valPrice)
            line.set_color(vpValLine, vpValueAreaColor)
 
            label.set_xy(vpVahLabel, profileRightX + 1, vahPrice)
            label.set_text(vpVahLabel, vpShowLabels ? "VAH" : "")
            label.set_textcolor(vpVahLabel, vpValueAreaColor)
 
            label.set_xy(vpValLabel, profileRightX + 1, valPrice)
            label.set_text(vpValLabel, vpShowLabels ? "VAL" : "")
            label.set_textcolor(vpValLabel, vpValueAreaColor)
 
    else if showPreviousVp and timeframe.isintraday
        label.set_xy(vpTitleLabel, profileLeftX, close)
        label.set_text(vpTitleLabel, vpShowLabels ? "PREV DAY VP\nNO VOLUME / HISTORY" : "")
 
// ─────────────────────────────────────────────────────
// ORIGINAL STRENGTH FORMULA
// ─────────────────────────────────────────────────────
emaFast = ta.ema(close, 9)
emaSlow = ta.ema(close, 21)
 
trendVal = 50.0 + 50.0 * (emaFast - emaSlow) / close * 100
trendVal := math.max(0.0, math.min(100.0, trendVal))
 
float htfBoost = (htf1Bull ? 10.0 : -10.0) + (htf2Bull ? 10.0 : -10.0)
float rawStrength = math.min(30, volRatio * 15) + math.min(30, spreadRatio * 15) + trendVal * 0.3 + htfBoost
int smcStrength = math.round(math.max(0, math.min(100, rawStrength)))
 
// ─────────────────────────────────────────────────────
// DAILY EXTREMES / EXACT CANDLE ANCHORS
// ─────────────────────────────────────────────────────
var float dailyHigh = na
var float dailyLow = na
var int dailyHighCandleTime = na
var int dailyLowCandleTime = na
 
var float completedDayHigh = na
var float completedDayLow = na
var int completedHighCandleTime = na
var int completedLowCandleTime = na
 
if na(dailyHigh)
    dailyHigh := high
    dailyLow := low
    dailyHighCandleTime := time
    dailyLowCandleTime := time
else if newTradingDay
    completedDayHigh := dailyHigh
    completedDayLow := dailyLow
    completedHighCandleTime := dailyHighCandleTime
    completedLowCandleTime := dailyLowCandleTime
 
    dailyHigh := high
    dailyLow := low
    dailyHighCandleTime := time
    dailyLowCandleTime := time
else
    if high > dailyHigh
        dailyHigh := high
        dailyHighCandleTime := time
    if low < dailyLow
        dailyLow := low
        dailyLowCandleTime := time
 
bool highAnchorMatches = not na(completedDayHigh) and not na(pdhPrice) and math.abs(completedDayHigh - pdhPrice) < syminfo.mintick * 0.5
bool lowAnchorMatches = not na(completedDayLow) and not na(pdlPrice) and math.abs(completedDayLow - pdlPrice) < syminfo.mintick * 0.5
 
int pdhAnchorTime = highAnchorMatches ? completedHighCandleTime : previousDailyOpenTime
int pdlAnchorTime = lowAnchorMatches ? completedLowCandleTime : previousDailyOpenTime
 
// DAILY LEVEL DRAWINGS
f_drawLevel(bool enabled, float levelPrice, int anchorTime, string levelText, color levelColor, int levelWidth, int extensionBars, bool showLabel, bool dashed) =>
    var line levelLine = line.new(x1=na, y1=na, x2=na, y2=na, xloc=xloc.bar_time, extend=extend.none, force_overlay=true)
    var label levelLabel = label.new(x=na, y=na, text="", xloc=xloc.bar_time, style=label.style_label_left, color=color.new(color.black, 100), size=size.small, force_overlay=true)
 
    if barstate.islast
        bool valid = enabled and timeframe.isintraday and not na(levelPrice) and not na(anchorTime)
 
        if valid
            int chartIntervalMs = int(timeframe.in_seconds() * 1000)
            int endpointTime = time + chartIntervalMs * extensionBars
 
            line.set_xy1(levelLine, anchorTime, levelPrice)
            line.set_xy2(levelLine, endpointTime, levelPrice)
            line.set_color(levelLine, levelColor)
            line.set_width(levelLine, levelWidth)
            line.set_style(levelLine, dashed ? line.style_dashed : line.style_solid)
 
            label.set_xy(levelLabel, endpointTime, levelPrice)
            label.set_text(levelLabel, showLabel ? levelText : "")
            label.set_textcolor(levelLabel, levelColor)
        else
            line.set_xy1(levelLine, na, na)
            line.set_xy2(levelLine, na, na)
            label.set_text(levelLabel, "")
 
f_drawLevel(showDailyHL, dailyHigh, dailyHighCandleTime, "DH", dailyHighColor, dailyHLWidth, dailyHLExtension, showDailyHLLabels, false)
f_drawLevel(showDailyHL, dailyLow, dailyLowCandleTime, "DL", dailyLowColor, dailyHLWidth, dailyHLExtension, showDailyHLLabels, false)
f_drawLevel(showPreviousHL, pdhPrice, pdhAnchorTime, "PDH", previousHighColor, previousHLWidth, previousHLExtension, showPreviousHLLabels, true)
f_drawLevel(showPreviousHL, pdlPrice, pdlAnchorTime, "PDL", previousLowColor, previousHLWidth, previousHLExtension, showPreviousHLLabels, true)
 
// ─────────────────────────────────────────────────────
// BACKGROUND SWINGS
// ─────────────────────────────────────────────────────
pivotHigh = ta.pivothigh(high, swingLength, swingLength)
pivotLow = ta.pivotlow(low, swingLength, swingLength)
 
var float lastSwingHigh = na
var float lastSwingLow = na
 
if barstate.isconfirmed
    if not na(pivotHigh)
        lastSwingHigh := pivotHigh
    if not na(pivotLow)
        lastSwingLow := pivotLow
 
// ─────────────────────────────────────────────────────
// PDH / PDL SWEEPS
// ─────────────────────────────────────────────────────
float sweepDistance = minimumSweepTicks * syminfo.mintick
 
bool aboveSweepThreshold = not na(pdhPrice) and high >= pdhPrice + sweepDistance
bool belowSweepThreshold = not na(pdlPrice) and low <= pdlPrice - sweepDistance
 
bool firstHighPenetration = aboveSweepThreshold and (newTradingDay or not aboveSweepThreshold[1])
bool firstLowPenetration = belowSweepThreshold and (newTradingDay or not belowSweepThreshold[1])
 
var int pendingHighSweepBar = na
var int pendingLowSweepBar = na
var bool highSweptToday = false
var bool lowSweptToday = false
 
bool pdhSweep = false
bool pdlSweep = false
 
if newTradingDay
    pendingHighSweepBar := na
    pendingLowSweepBar := na
    highSweptToday := false
    lowSweptToday := false
 
if barstate.isconfirmed and timeframe.isintraday and enableSweeps
    if not na(pendingHighSweepBar)
        if bar_index - pendingHighSweepBar > reclaimBars
            pendingHighSweepBar := na
 
    if not na(pendingLowSweepBar)
        if bar_index - pendingLowSweepBar > reclaimBars
            pendingLowSweepBar := na
 
    if firstHighPenetration and na(pendingHighSweepBar) and (not oneSweepPerDay or not highSweptToday)
        pendingHighSweepBar := bar_index
 
    if firstLowPenetration and na(pendingLowSweepBar) and (not oneSweepPerDay or not lowSweptToday)
        pendingLowSweepBar := bar_index
 
    if not na(pendingHighSweepBar)
        if close < pdhPrice and bar_index - pendingHighSweepBar <= reclaimBars
            pdhSweep := true
            highSweptToday := true
            pendingHighSweepBar := na
 
    if not na(pendingLowSweepBar)
        if close > pdlPrice and bar_index - pendingLowSweepBar <= reclaimBars
            pdlSweep := true
            lowSweptToday := true
            pendingLowSweepBar := na
 
// SWEEP LABELS — CURRENT DAY ONLY
var array<label> currentDaySweepLabels = array.new<label>()
 
if newTradingDay or barstate.islast
    bool checkingOldSweeps = true
 
    while checkingOldSweeps and array.size(currentDaySweepLabels) > 0
        label oldestSweep = array.get(currentDaySweepLabels, 0)
        if label.get_x(oldestSweep) < currentTradingDayStart
            label.delete(array.shift(currentDaySweepLabels))
        else
            checkingOldSweeps := false
 
if showSweepMarkers and barstate.isconfirmed and timeframe.isintraday
    if pdhSweep
        label pdhSweepLabel = label.new(x=time, y=high, text="PDH SWEEP", xloc=xloc.bar_time, yloc=yloc.abovebar, style=label.style_label_down, color=color.new(color.orange, 85), textcolor=color.orange, size=size.small, force_overlay=true)
        array.push(currentDaySweepLabels, pdhSweepLabel)
 
    if pdlSweep
        label pdlSweepLabel = label.new(x=time, y=low, text="PDL SWEEP", xloc=xloc.bar_time, yloc=yloc.belowbar, style=label.style_label_up, color=color.new(color.aqua, 85), textcolor=color.aqua, size=size.small, force_overlay=true)
        array.push(currentDaySweepLabels, pdlSweepLabel)
 
while array.size(currentDaySweepLabels) > 400
    label.delete(array.shift(currentDaySweepLabels))
 
// ─────────────────────────────────────────────────────
// BACKGROUND SETUP LOGIC
// ─────────────────────────────────────────────────────
var int bullishSetupStart = na
var int bearishSetupStart = na
var float bullishSetupTarget = na
var float bearishSetupTarget = na
 
bool bullishSetup = false
bool bearishSetup = false
 
if newTradingDay or not enableSetups
    bullishSetupStart := na
    bearishSetupStart := na
    bullishSetupTarget := na
    bearishSetupTarget := na
 
if barstate.isconfirmed and enableSetups and timeframe.isintraday
    if pdlSweep
        bearishSetupStart := na
        bearishSetupTarget := na
 
        if not na(lastSwingHigh) and lastSwingHigh > close
            bullishSetupStart := bar_index
            bullishSetupTarget := lastSwingHigh
        else
            bullishSetupStart := na
            bullishSetupTarget := na
 
    if pdhSweep
        bullishSetupStart := na
        bullishSetupTarget := na
 
        if not na(lastSwingLow) and lastSwingLow < close
            bearishSetupStart := bar_index
            bearishSetupTarget := lastSwingLow
        else
            bearishSetupStart := na
            bearishSetupTarget := na
 
    if not na(bullishSetupStart)
        if bar_index - bullishSetupStart > setupExpiryBars
            bullishSetupStart := na
            bullishSetupTarget := na
        else if bar_index > bullishSetupStart and close > bullishSetupTarget
            bool htfPass = not requireHtfAgreement or allHtfBull
            bool vwapPass = not requireVwapFilter or (not na(vwapValue) and close > vwapValue)
            bullishSetup := htfPass and vwapPass
            bullishSetupStart := na
            bullishSetupTarget := na
 
    if not na(bearishSetupStart)
        if bar_index - bearishSetupStart > setupExpiryBars
            bearishSetupStart := na
            bearishSetupTarget := na
        else if bar_index > bearishSetupStart and close < bearishSetupTarget
            bool htfPass = not requireHtfAgreement or allHtfBear
            bool vwapPass = not requireVwapFilter or (not na(vwapValue) and close < vwapValue)
            bearishSetup := htfPass and vwapPass
            bearishSetupStart := na
            bearishSetupTarget := na
 
// ─────────────────────────────────────────────────────
// ORDER BLOCKS
// ─────────────────────────────────────────────────────
var box[] activeBoxes = array.new_box()
 
bool bullishObFirstRetest = false
bool bearishObFirstRetest = false
 
if barstate.islast
    if array.size(activeBoxes) > 0
        for i = 0 to array.size(activeBoxes) - 1
            box.delete(array.get(activeBoxes, i))
        array.clear(activeBoxes)
 
    if showOb and bar_index >= 3
        int scanBars = advancedOb ? obLookback : 300
        int lookback = math.min(bar_index - 2, scanBars)
        int zoneLimit = advancedOb ? maxVisibleOb : 15
 
        for i = 1 to lookback
            bool histBullOB = close[i + 1] < open[i + 1] and close[i] > open[i] and close[i] > high[i + 1]
            bool histBearOB = close[i + 1] > open[i + 1] and close[i] < open[i] and close[i] < low[i + 1]
            bool displacementPass = not advancedOb or not requireDisplacement or (not na(atrValue[i]) and priceSpread[i] >= atrValue[i] * minimumDisplacementAtr)
 
            if (histBullOB or histBearOB) and displacementPass
                float topLimit = high[i + 1]
                float botLimit = low[i + 1]
                float zoneHeight = math.max(topLimit - botLimit, syminfo.mintick)
 
                bool touched = false
                bool invalidated = false
                bool originalMitigated = false
                int firstTouchOffset = na
                float deepestFill = 0.0
 
                for step = 0 to i - 1
                    int j = i - 1 - step
                    bool originalTouch = histBullOB ? low[j] <= topLimit : high[j] >= botLimit
 
                    if originalTouch
                        originalMitigated := true
 
                    bool overlapsZone = low[j] <= topLimit and high[j] >= botLimit
                    bool invalidBar = false
 
                    if obInvalidation == "Close"
                        invalidBar := histBullOB ? close[j] < botLimit : close[j] > topLimit
                    else
                        invalidBar := histBullOB ? low[j] < botLimit : high[j] > topLimit
 
                    if advancedOb
                        if invalidBar
                            invalidated := true
                            break
 
                        if overlapsZone
                            if not touched
                                firstTouchOffset := j
 
                            touched := true
                            float fill = histBullOB ? (topLimit - low[j]) / zoneHeight * 100.0 : (high[j] - botLimit) / zoneHeight * 100.0
                            deepestFill := math.max(deepestFill, math.max(0.0, math.min(100.0, fill)))
 
                if advancedOb and not invalidated and touched and firstTouchOffset == 0 and barstate.isconfirmed
                    if histBullOB
                        bullishObFirstRetest := true
                    else
                        bearishObFirstRetest := true
 
                bool displayZone = false
                if advancedOb
                    displayZone := invalidated ? showInvalidOb : (not touched or keepTouchedOb)
                else
                    displayZone := not originalMitigated
 
                if displayZone and array.size(activeBoxes) < zoneLimit
                    color zoneColor = histBullOB ? bullishObColor : bearishObColor
                    color zoneTextColor = histBullOB ? bullishObTextColor : bearishObTextColor
                    int zoneTransparency = 80
                    string stateText = ""
 
                    if advancedOb
                        if invalidated
                            zoneColor := color.gray
                            zoneTransparency := 92
                            stateText := "INVALID"
                        else if not touched
                            zoneTransparency := 80
                            stateText := "FRESH"
                        else if deepestFill >= partialFillPercent
                            zoneTransparency := 91
                            stateText := "FILLED " + str.tostring(math.round(deepestFill)) + "%"
                        else
                            zoneTransparency := 87
                            stateText := "TOUCHED"
 
                    string zoneText = advancedOb and showObText ? (histBullOB ? "BULL OB | " : "BEAR OB | ") + stateText : ""
 
                    box zone = box.new(
                         left=bar_index - i - 1,
                         top=topLimit,
                         right=bar_index,
                         bottom=botLimit,
                         bgcolor=color.new(zoneColor, zoneTransparency),
                         border_color=color.new(zoneColor, invalidated ? 70 : 20),
                         text=zoneText,
                         text_color=zoneTextColor,
                         text_size=size.tiny,
                         text_halign=text.align_right,
                         text_valign=text.align_center,
                         force_overlay=true)
 
                    array.push(activeBoxes, zone)
 
// ─────────────────────────────────────────────────────
// ALERTS
// ─────────────────────────────────────────────────────
bool prevBull = bar_index > 0 ? allHtfBull[1] : false
bool prevBear = bar_index > 0 ? allHtfBear[1] : false
bool bullishAgreementEvent = barstate.isconfirmed and allHtfBull and not prevBull
bool bearishAgreementEvent = barstate.isconfirmed and allHtfBear and not prevBear
 
alertcondition(enableSweepAlerts and pdhSweep, title="PDH Sweep Confirmed", message="PDH sweep confirmed: price penetrated previous-day high and closed back below. {{ticker}} {{interval}}")
alertcondition(enableSweepAlerts and pdlSweep, title="PDL Sweep Confirmed", message="PDL sweep confirmed: price penetrated previous-day low and closed back above. {{ticker}} {{interval}}")
alertcondition(enableSetupAlerts and bullishSetup, title="Bullish Sweep + Structure Setup", message="Bullish setup: PDL sweep followed by a close above the frozen swing-high target. Enabled filters passed. {{ticker}} {{interval}}")
alertcondition(enableSetupAlerts and bearishSetup, title="Bearish Sweep + Structure Setup", message="Bearish setup: PDH sweep followed by a close below the frozen swing-low target. Enabled filters passed. {{ticker}} {{interval}}")
alertcondition(enableObAlerts and bullishObFirstRetest, title="Fresh Bullish OB First Retest", message="First retest of a non-invalidated bullish order block. {{ticker}} {{interval}}")
alertcondition(enableObAlerts and bearishObFirstRetest, title="Fresh Bearish OB First Retest", message="First retest of a non-invalidated bearish order block. {{ticker}} {{interval}}")
alertcondition(enableHtfAlerts and bullishAgreementEvent, title="All Selected HTFs Bullish", message="All selected HTFs have changed to full bullish agreement. {{ticker}} {{interval}}")
alertcondition(enableHtfAlerts and bearishAgreementEvent, title="All Selected HTFs Bearish", message="All selected HTFs have changed to full bearish agreement. {{ticker}} {{interval}}")
 
// ─────────────────────────────────────────────────────
// DASHBOARD
// ─────────────────────────────────────────────────────
var table dash = table.new(position.top_right, 1, 8, bgcolor=color.new(color.black, 20), border_color=color.gray, border_width=1)
 
if barstate.islast
    table.clear(dash, 0, 0, 0, 7)
 
    if showDash
        color strengthColor = smcStrength >= 70 ? color.green : smcStrength <= 30 ? color.red : color.orange
 
        if not advancedDashboard
            string htf1Status = "HTF1 (" + htf1Res + "): " + (htf1Bull ? "BULLISH" : "BEARISH")
            string htf2Status = "HTF2 (" + htf2Res + "): " + (htf2Bull ? "BULLISH" : "BEARISH")
            table.cell(dash, 0, 0, "SMC STRENGTH: " + str.tostring(smcStrength) + "/100", text_color=color.white, text_size=size.small, bgcolor=strengthColor)
            table.cell(dash, 0, 1, htf1Status, text_color=color.white, text_size=size.small, bgcolor=htf1Bull ? color.new(color.green, 40) : color.new(color.red, 40))
            table.cell(dash, 0, 2, htf2Status, text_color=color.white, text_size=size.small, bgcolor=htf2Bull ? color.new(color.green, 40) : color.new(color.red, 40))
        else
            string directionText = selectedCount == 0 ? "NO HTFs SELECTED" : bullishCount > bearishCount ? "BULLISH BIAS" : bearishCount > bullishCount ? "BEARISH BIAS" : "MIXED / NEUTRAL"
            color directionColor = bullishCount > bearishCount ? color.new(color.green, 35) : bearishCount > bullishCount ? color.new(color.red, 35) : color.new(color.orange, 35)
            string agreementText = "HTF: " + str.tostring(bullishCount) + " BULL | " + str.tostring(bearishCount) + " BEAR | " + str.tostring(selectedCount) + " SELECTED"
            string biasModeText = confirmedHtfBias ? "BIAS DATA: CLOSED HTF CANDLES" : "BIAS DATA: LIVE HTF CANDLES"
            string activityText = "VOLUME: " + (na(volRatio) ? "N/A" : str.tostring(volRatio, "#.##") + "x") + " | RANGE: " + (na(spreadRatio) ? "N/A" : str.tostring(spreadRatio, "#.##") + "x")
            string vwapText = na(vwapValue) ? "VWAP: NO DATA" : close > vwapValue ? "PRICE ABOVE VWAP" : close < vwapValue ? "PRICE BELOW VWAP" : "PRICE AT VWAP"
 
            string setupText = "SETUP: WAITING FOR SWEEP"
            if not enableSetups
                setupText := "SETUPS DISABLED"
            else if not enableSweeps
                setupText := "ENABLE SWEEP DETECTION"
            else if bullishSetup
                setupText := "BULLISH SETUP CONFIRMED"
            else if bearishSetup
                setupText := "BEARISH SETUP CONFIRMED"
            else if not na(bullishSetupStart)
                setupText := "PDL SWEPT: WAITING FOR SWING BREAK"
            else if not na(bearishSetupStart)
                setupText := "PDH SWEPT: WAITING FOR SWING BREAK"
            else if not na(pendingHighSweepBar) or not na(pendingLowSweepBar)
                setupText := "WAITING FOR LEVEL RECLAIM"
 
            string filterText = "FILTERS: HTF " + (requireHtfAgreement ? "ON" : "OFF") + " | VWAP " + (requireVwapFilter ? "ON" : "OFF")
            table.cell(dash, 0, 0, directionText, text_color=color.white, text_size=size.small, bgcolor=directionColor)
            table.cell(dash, 0, 1, agreementText, text_color=color.white, text_size=size.small)
            table.cell(dash, 0, 2, biasModeText, text_color=color.silver, text_size=size.small)
            table.cell(dash, 0, 3, activityText, text_color=color.white, text_size=size.small)
            table.cell(dash, 0, 4, vwapText, text_color=color.yellow, text_size=size.small)
            table.cell(dash, 0, 5, setupText, text_color=color.white, text_size=size.small)
            table.cell(dash, 0, 6, filterText, text_color=color.silver, text_size=size.small)
            table.cell(dash, 0, 7, "ORIGINAL STRENGTH: " + str.tostring(smcStrength) + "/100", text_color=color.white, text_size=size.small, bgcolor=strengthColor)

← 返回列表