SNR Retest Finder + Delta Zones | Reversal & Supply/Demand

vijiagarwal · study · 1104 行 · 点赞 89 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartPrime (Support/Resistance Re-test Finder)
// Delta Zones Buy/Sell Pressure + ZigZag Volume Profile
// MERGED into one indicator. Logic of both scripts is unchanged.
 
//@version=6
import DevLucem/ZigLib/1 as ZigZag
indicator(title = "SNR Retest Finder + Delta Zones | Reversal & Supply/Demand Analysis", overlay = true, format = format.price, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
 
 
// ████████████████████████████████████████████████████████████
// ██  PART 1 — SUPPORT/RESISTANCE RE-TEST FINDER [ChartPrime] ██
// ████████████████████████████████████████████████████████████
 
// { <CONSTANTS>
 
MAIN_GROUP       = "Main Settings"
DELETE_GROUP     = "Deletion Settings"
COSMETIC_GROUP   = "Cosmetic Settings"
 
// } <CONSTANTS>
 
 
 
// { <INPUTS>
 
levelMethod = input.string(
 title = "Detection Method",
  defval = "Wick",
   options = ["Wick", "Body"],
     group = MAIN_GROUP)
 
leftBars = input.int(
 title = "Left Bars",
  defval = 10,
   group = MAIN_GROUP,
     inline = "pivot")
 
rightBars = input.int(
 title = "Right Bars",
  defval = 10,
   group = MAIN_GROUP,
     inline = "pivot")
 
retestLogic = input.bool(
 title = "Retest Weaker",
  defval = false,
  tooltip = "Retest makes level weaker vs retest makes level stronger",
   group = MAIN_GROUP)
 
definitionOfDelete = input.string(
 title = "Delete Definition",
  defval = "Stop Updating Level",
   options = ["Stop Updating Level", "Completely Delete Level", "Stop Updating Level & Turn Level Unique Color"],
     group = DELETE_GROUP)
 
flipsUntilDeletion = input.int(
 title = "Breakouts Until Level Deletes",
  defval = 1,
   group = DELETE_GROUP)
 
ageUntilDeletion = input.int(
 title = "Bars Until Level Deletes",
  defval = 300,
   group = DELETE_GROUP)
 
supportColor = input.color(
 title = "Initial Support Re-Test Color",
  defval = color.rgb(76, 175, 79, 50),
   group = COSMETIC_GROUP)
 
resistanceColor = input.color(
 title = "Initial Resistance Re-Test Color",
  defval = color.rgb(255, 82, 82, 50),
   group = COSMETIC_GROUP)
 
uniqueDeleteColor = input.color(
 title = "Unique Deletion Color",
  defval = color.rgb(120, 123, 134, 50),
   group = COSMETIC_GROUP)
 
changeColorMethod = input.string(
 title = "Change Color Method",
  defval = "Price Above/Below",
   options = ["Price Above/Below", "Fade Out Based On Age"],
     group = COSMETIC_GROUP)
 
lineWidth = input.int(
 title = "Line Width",
  defval = 10,
   group = COSMETIC_GROUP)
 
// } <INPUTS>
 
 
 
// { <USER DEFINED TYPES>
 
type flipLevelManager
    array<string> variation
    array<line> lineArray
    array<int> lineAge
    array<int> lineFlips
    array<int> linePhase
 
// } <USER DEFINED TYPES>
 
 
 
// { <CALCULATIONS>
 
pivotHigh = ta.pivothigh(
 levelMethod == "Wick" ?
  high : close > open ? close : open,
   leftBars,
     rightBars)
 
pivotLow = ta.pivotlow(
 levelMethod == "Wick" ?
  low : close < open ? close : open,
   leftBars,
     rightBars)
 
newHigh = not na(pivotHigh)
newLow  = not na(pivotLow)
 
newTestedSupport        = false
newTestedResistance     = false
supportBrokeDownside    = false
supportBrokeUpside      = false
resistanceBrokeDownside = false
resistanceBrokeUpside   = false
 
var firstPhaseHigh  = array.new_float()
var firstPhaseHighI = array.new_int()
var firstPhaseLow   = array.new_float()
var firstPhaseLowI  = array.new_int()
 
var secondPhaseHigh  = array.new_float()
var secondPhaseHighI = array.new_int()
var secondPhaseLow   = array.new_float()
var secondPhaseLowI  = array.new_int()
 
var flipManager = flipLevelManager.new(
 array.new_string(),
  array.new_line(),
   array.new_int(),
     array.new_int(),
      array.new_int())
 
if barstate.isconfirmed
    if newHigh
        array.push(firstPhaseHigh, pivotHigh)
        array.push(firstPhaseHighI, bar_index[rightBars])
    
    if newLow
        array.push(firstPhaseLow, pivotLow)
        array.push(firstPhaseLowI, bar_index[rightBars])
 
    // NOTE (v6 port): the original loops used "size > 0 ? size - 1 : na to 0".
    // v6 does not accept an na loop bound, so the same behaviour is written
    // as an explicit "size > 0" guard around "size - 1 to 0".
    if array.size(secondPhaseHigh) > 0
        for i = array.size(secondPhaseHigh) - 1 to 0
            price = array.get(secondPhaseHigh, i)
            index = array.get(secondPhaseHighI, i)
 
            if low <= price and close > price and close > open
                newLine = line.new(
                 x1 = index, y1 = price,
                  x2 = bar_index, y2 = price,
                   xloc = xloc.bar_index, extend = extend.none,
                     color = supportColor, width = lineWidth)
 
                array.push(flipManager.lineArray, newLine)
                array.push(flipManager.variation, "Support")
                array.push(flipManager.lineAge, 0)
                array.push(flipManager.lineFlips, 0)
                array.push(flipManager.linePhase, 1)
                array.remove(secondPhaseHigh, i)
                array.remove(secondPhaseHighI, i)
                newTestedSupport := true
        
            else if bar_index - index > 1000 or close < price
                array.remove(secondPhaseHigh, i)
                array.remove(secondPhaseHighI, i)
 
    if array.size(secondPhaseLow) > 0
        for i = array.size(secondPhaseLow) - 1 to 0
            price = array.get(secondPhaseLow, i)
            index = array.get(secondPhaseLowI, i)
 
            if high >= price and close < price and close < open
                newLine = line.new(
                 x1 = index, y1 = price,
                  x2 = bar_index, y2 = price,
                   xloc = xloc.bar_index, extend = extend.none,
                     color = resistanceColor, width = lineWidth)
 
                array.push(flipManager.lineArray, newLine)
                array.push(flipManager.variation, "Resistance")
                array.push(flipManager.lineAge, 0)
                array.push(flipManager.lineFlips, 0)
                array.push(flipManager.linePhase, -1)
                array.remove(secondPhaseLow, i)
                array.remove(secondPhaseLowI, i)
                newTestedResistance := true
            
            else if bar_index - index > 1000 or close > price
                array.remove(secondPhaseLow, i)
                array.remove(secondPhaseLowI, i)
 
    if array.size(firstPhaseHigh) > 0
        for i = array.size(firstPhaseHigh) - 1 to 0
            price = array.get(firstPhaseHigh, i)
            index = array.get(firstPhaseHighI, i)
 
            if low > price
                array.push(secondPhaseHigh, price)
                array.push(secondPhaseHighI, index)
                array.remove(firstPhaseHigh, i)
                array.remove(firstPhaseHighI, i)
            else if bar_index - index > 1000
                array.remove(firstPhaseHigh, i)
                array.remove(firstPhaseHighI, i)
        
    if array.size(firstPhaseLow) > 0
        for i = array.size(firstPhaseLow) - 1 to 0
            price = array.get(firstPhaseLow, i)
            index = array.get(firstPhaseLowI, i)
 
            if high < price
                array.push(secondPhaseLow, price)
                array.push(secondPhaseLowI, index)
                array.remove(firstPhaseLow, i)
                array.remove(firstPhaseLowI, i)
            else if bar_index - index > 1000
                array.remove(firstPhaseLow, i)
                array.remove(firstPhaseLowI, i)
 
    if array.size(flipManager.lineArray) > 0
        for i = array.size(flipManager.lineArray) - 1 to 0
            lineObject = array.get(flipManager.lineArray, i)
            lineAge   = array.get(flipManager.lineAge, i)
            lineType  = array.get(flipManager.variation, i)
            lineFlips = array.get(flipManager.lineFlips, i)
            linePhase = array.get(flipManager.linePhase, i)
 
            linePrice  = line.get_y1(lineObject)
            line.set_x2(lineObject, bar_index + 1)
 
            lineColor = lineType == "Support" ? supportColor : resistanceColor
            gradientLineColor = color.from_gradient(lineAge, 0, ageUntilDeletion, lineColor, color.new(lineColor, 100))
            newLineColor = changeColorMethod == "Fade Out Based On Age" ?
             gradientLineColor : close > linePrice ? supportColor : resistanceColor
            line.set_color(lineObject, newLineColor)
 
            array.set(flipManager.lineAge, i, lineAge + 1)
 
            if lineType == "Support"
 
                if linePhase == 1 and close < linePrice
                    array.set(flipManager.lineFlips, i, lineFlips + 1)
                    array.set(flipManager.linePhase, i, -1)
                    supportBrokeDownside := true
                else if linePhase == -1 and close > linePrice
                    array.set(flipManager.lineFlips, i, lineFlips + 1)
                    array.set(flipManager.linePhase, i, 1)
                    supportBrokeUpside := true
            
            if lineType == "Resistance"
 
                if linePhase == -1 and close > linePrice
                    array.set(flipManager.lineFlips, i, lineFlips + 1)
                    array.set(flipManager.linePhase, i, 1)
                    resistanceBrokeUpside := true
                else if linePhase == 1 and close < linePrice
                    array.set(flipManager.lineFlips, i, lineFlips + 1)
                    array.set(flipManager.linePhase, i, -1)
                    resistanceBrokeDownside := true
 
            lineFlips := array.get(flipManager.lineFlips, i)
 
            if lineFlips >= flipsUntilDeletion or lineAge >= ageUntilDeletion
                if definitionOfDelete == "Completely Delete Level"
                    line.delete(lineObject)
                    array.remove(flipManager.lineArray, i)
                    array.remove(flipManager.lineAge, i)
                    array.remove(flipManager.lineFlips, i)
                    array.remove(flipManager.variation, i)
                    array.remove(flipManager.linePhase, i)
                else if definitionOfDelete == "Stop Updating Level"
                    array.remove(flipManager.lineArray, i)
                    array.remove(flipManager.lineAge, i)
                    array.remove(flipManager.lineFlips, i)
                    array.remove(flipManager.variation, i)
                    array.remove(flipManager.linePhase, i)
                else if definitionOfDelete == "Stop Updating Level & Turn Level Unique Color"
                    line.set_color(lineObject, uniqueDeleteColor)
                    array.remove(flipManager.lineArray, i)
                    array.remove(flipManager.lineAge, i)
                    array.remove(flipManager.lineFlips, i)
                    array.remove(flipManager.variation, i)
                    array.remove(flipManager.linePhase, i)
 
// } <CALCULATIONS>
            
 
 
// { <VISUALS>
 
plotshape(
 series = newTestedSupport,
  title = "New Support Re-Test X",
   style = retestLogic ? shape.labeldown : shape.labelup,
     text = "R",
      textcolor = color.white,
       location = retestLogic ? location.abovebar : location.belowbar,
         color = retestLogic ? color.red :color.green,
          size = size.tiny,
           show_last = 20000)
 
plotshape(
 series = newTestedResistance,
  title = "New Resistance Re-Test X",
   style = retestLogic ? shape.labelup : shape.labeldown,
     text = "R",
      textcolor = color.white,
       location = retestLogic ? location.belowbar : location.abovebar,
         color = retestLogic ? color.green : color.red,
          size = size.tiny,
           show_last = 20000)
         
// } <VISUALS>
 
 
 
// { <ALERTS>
 
alertcondition(
 condition = newTestedSupport,
  title = "New Support Re-Test")
 
alertcondition(
 condition = newTestedResistance,
  title = "New Resistance Re-Test")
 
alertcondition(
 condition = supportBrokeDownside,
  title = "Support Re-Test Downside Break")
 
alertcondition(
 condition = supportBrokeUpside,
  title = "Support Re-Test Upside Break")
 
alertcondition(
 condition = resistanceBrokeDownside,
  title = "Resistance Re-Test Downside Break")
 
alertcondition(
 condition = resistanceBrokeUpside,
  title = "Resistance Re-Test Upside Break")
 
alertcondition(
 condition = supportBrokeDownside or resistanceBrokeDownside,
  title = "Any Downside Break")
 
alertcondition(
 condition = supportBrokeUpside or resistanceBrokeUpside,
  title = "Any Upside Break")
 
// } <ALERTS>
 
 
 
// ████████████████████████████████████████████████████████████
// ██  PART 2 — DELTA ZONES BUY/SELL PRESSURE                  ██
// ████████████████████████████████████████████████████████████
 
// ╔══════════════════════════════════════════════════════════╗
// ║  1. DELTA ZONES — General Settings                       ║
// ╚══════════════════════════════════════════════════════════╝
stddevlevel    = input.float(title='Standard Deviation',          defval=3.5, step=0.5, group="1. Delta Zones — General")
stddevlookback = input.int  (title='Standard Deviation Lookback', defval=20,            group="1. Delta Zones — General")
 
// ╔══════════════════════════════════════════════════════════╗
// ║  2. DELTA ZONES — Current TF Boxes                       ║
// ╚══════════════════════════════════════════════════════════╝
showBuyBoxes       = input.bool (title='Show Buy Boxes',              defval=true,  group="2. Delta Zones — Current TF Boxes")
showSellBoxes      = input.bool (title='Show Sell Boxes',             defval=true,  group="2. Delta Zones — Current TF Boxes")
buyBoxColor        = input.color(title='Buy Fill Color',              defval=color.new(color.green, 83), group="2. Delta Zones — Current TF Boxes")
sellBoxColor       = input.color(title='Sell Fill Color',             defval=color.new(color.red,   83), group="2. Delta Zones — Current TF Boxes")
buyBoxBorderColor  = input.color(title='Buy Border Color',            defval=color.green,               group="2. Delta Zones — Current TF Boxes")
sellBoxBorderColor = input.color(title='Sell Border Color',           defval=color.red,                 group="2. Delta Zones — Current TF Boxes")
boxBorderWidth     = input.int  (title='Border Width',                defval=1, minval=1, maxval=5,     group="2. Delta Zones — Current TF Boxes")
maxCurrentBoxes    = input.int  (title='Max Boxes Visible',           defval=3,  minval=1, maxval=20,   group="2. Delta Zones — Current TF Boxes")
deleteOnClose      = input.bool (title='Delete Box When Price Breaks Zone', defval=false, group="2. Delta Zones — Current TF Boxes")
 
// ╔══════════════════════════════════════════════════════════╗
// ║  3. HIGHER TIMEFRAME (HTF) — Activation                  ║
// ╚══════════════════════════════════════════════════════════╝
showHTFBoxes     = input.bool     (title='Enable HTF Boxes',          defval=false, group="3. HTF Boxes — Activation")
htfTimeframe     = input.timeframe(title='Higher Timeframe',          defval="60",  group="3. HTF Boxes — Activation")
hideCurrentOnHTF = input.bool     (title='Hide Current TF Boxes When HTF Active', defval=true, group="3. HTF Boxes — Activation")
 
// ╔══════════════════════════════════════════════════════════╗
// ║  4. HIGHER TIMEFRAME (HTF) — Appearance                  ║
// ╚══════════════════════════════════════════════════════════╝
htfBuyBorderColor  = input.color(title='HTF Buy Border Color',  defval=color.new(color.aqua,   0),  group="4. HTF Boxes — Appearance")
htfSellBorderColor = input.color(title='HTF Sell Border Color', defval=color.new(color.orange, 0),  group="4. HTF Boxes — Appearance")
htfBuyFillColor    = input.color(title='HTF Buy Fill Color',    defval=color.new(color.aqua,   92), group="4. HTF Boxes — Appearance")
htfSellFillColor   = input.color(title='HTF Sell Fill Color',   defval=color.new(color.orange, 92), group="4. HTF Boxes — Appearance")
htfBorderWidth     = input.int  (title='HTF Border Width',      defval=2, minval=1, maxval=5,       group="4. HTF Boxes — Appearance")
showHTFLabels      = input.bool (title='Show HTF Labels',       defval=true,  group="4. HTF Boxes — Appearance")
maxHTFBoxes        = input.int  (title='Max HTF Boxes Visible', defval=2, minval=1, maxval=10,      group="4. HTF Boxes — Appearance")
 
// ╔══════════════════════════════════════════════════════════╗
// ║  5A. ZIGZAG — Price Action Lines (optional, purely visual)║
// ╚══════════════════════════════════════════════════════════╝
showLinesPA      = input.bool (false, 'Enable ZigZag Lines',  group="5A. ZigZag — Price Action", tooltip="Draws lines between ZigZag pivots. Tip: for a cleaner view, consider hiding the price candles (eye icon next to the symbol, or right-click → Visual Order) and leaving only the ZigZag lines visible.")
depth            = input.int  (12,    'Depth',    minval=1,   group="5A. ZigZag — Price Action")
deviation        = input.int  (5,     'Deviation',minval=1,   group="5A. ZigZag — Price Action")
backstep         = input.int  (2,     'Backstep', minval=2,   group="5A. ZigZag — Price Action")
lineThickness    = input.int  (1,  'Line Thickness', minval=1, maxval=4, group="5A. ZigZag — Price Action")
bullColor        = input.color(color.lime, 'Bullish Color',   group="5A. ZigZag — Price Action")
bearColor        = input.color(color.red,  'Bearish Color',   group="5A. ZigZag — Price Action")
lineTransparency = input.int  (0,  'Line Transparency',       group="5A. ZigZag — Price Action")
repaintLines     = input.bool (true,  'Repaint Lines',        group="5A. ZigZag — Price Action")
extendLines      = input.bool (false, 'Extend Lines',         group="5A. ZigZag — Price Action")
 
// ╔══════════════════════════════════════════════════════════╗
// ║  5B. VOLUME PROFILE — Master switch + general settings   ║
// ║  (built on the SAME ZigZag pivots as 5A — no redundant    ║
// ║  recomputation; see the single ZigZag.zigzag() call in   ║
// ║  the "ZIGZAG PIVOT DETECTION" section below)              ║
// ╚══════════════════════════════════════════════════════════╝
groupVP             = "5B. Volume Profile"
enableVolumeProfile = input.bool(false, "Enable Live Volume Profile", group=groupVP, tooltip="Profiles each ZigZag impulse with volume LIVE (while it's still developing, without waiting for the pivot to be confirmed). Independent of the lines toggle in section 5A.")
profileMode         = input.string("Bullish only", "Profile which legs", options=["Bullish only", "Bearish only", "Both"], group=groupVP)
vpBins              = input.int(30, "Number of levels (rows)", minval=5, maxval=60, group=groupVP)
valueAreaPct        = input.float(0.70, "Value Area %", minval=0.1, maxval=0.95, step=0.05, group=groupVP)
maxBarWidthBars     = input.int(20, "Max bar length (bars)", minval=5, group=groupVP)
showVolLabels       = input.bool(false, "Show volume labels", group=groupVP)
lvnThreshold        = input.float(0.25, "LVN threshold (fraction of max bin volume)", minval=0.05, maxval=0.9, step=0.05, group=groupVP)
showPOC             = input.bool(true, "Show POC line", group=groupVP)
showDivider         = input.bool(true, "Show profile start divider", group=groupVP)
maxProfilesKeep     = input.int(5, "Max finalized profiles to keep on chart (per side)", minval=1, maxval=15, group=groupVP)
useAutoTheme        = input.bool(true, "Auto-adapt text/border/divider to chart theme", group=groupVP, tooltip="When on, volume labels, normal-level borders and the divider line use chart.fg_color — automatically black on a light chart background and white on a dark one. Turn off to use the fixed colors below instead.")
lvnBorderColor      = input.color(color.new(#FF7043, 0), "LVN border color", group=groupVP)
normalBorderColor   = input.color(color.new(color.gray, 70), "Normal level border color (used when auto-adapt is off)", group=groupVP)
labelTextColor      = input.color(color.gray, "Volume label text color (used when auto-adapt is off)", group=groupVP)
 
// ╔══════════════════════════════════════════════════════════╗
// ║  5C. VOLUME PROFILE — Bullish leg colors                  ║
// ╚══════════════════════════════════════════════════════════╝
groupVPBull         = "5C. Volume Profile — Bullish Colors"
colorValueAreaBull  = input.color(color.new(#26A69A, 78), "Value Area color", group=groupVPBull)
colorNormalBull     = input.color(color.new(#5C6BC0, 83), "Normal node color", group=groupVPBull)
pocColorBull        = input.color(color.new(#FFB300, 5), "POC line color", group=groupVPBull)
dividerColorBull    = input.color(color.new(color.gray, 60), "Profile start divider color (used when auto-adapt is off)", group=groupVPBull)
 
// ╔══════════════════════════════════════════════════════════╗
// ║  5D. VOLUME PROFILE — Bearish leg colors                  ║
// ╚══════════════════════════════════════════════════════════╝
groupVPBear         = "5D. Volume Profile — Bearish Colors"
colorValueAreaBear  = input.color(color.new(#EF5350, 78), "Value Area color", group=groupVPBear)
colorNormalBear     = input.color(color.new(#AB47BC, 83), "Normal node color", group=groupVPBear)
pocColorBear        = input.color(color.new(#FFB300, 5), "POC line color", group=groupVPBear)
dividerColorBear    = input.color(color.new(color.gray, 60), "Profile start divider color (used when auto-adapt is off)", group=groupVPBear)
 
// ╔══════════════════════════════════════════════════════════╗
// ║  5E. VOLUME PROFILE — Impulse Size Filter (ATR)           ║
// ║  Auto-adapts to each instrument/timeframe: a leg only     ║
// ║  gets profiled once its range exceeds N × ATR AND it has  ║
// ║  lasted long enough (filters out sharp, short-lived       ║
// ║  bounces without needing per-instrument tuning).          ║
// ╚══════════════════════════════════════════════════════════╝
groupATR            = "5E. Volume Profile — Impulse Size Filter (ATR)"
atrLength           = input.int(14, "ATR Length", minval=1, group=groupATR)
atrMultiplier       = input.float(6.0, "Minimum leg range (× ATR) to profile", minval=0.1, step=0.1, group=groupATR)
minLegBars          = input.int(8, "Minimum leg duration (bars) to profile", minval=1, group=groupATR)
 
// Needed because the historical backfill below (Section: PIVOT
// CONFIRMATION) uses a dynamic (series) offset into high/low/volume,
// which Pine can't size automatically.
max_bars_back(high, 500)
max_bars_back(low, 500)
max_bars_back(volume, 500)
 
 
// ══════════════════════════════════════════════════════════
//  TIMEFRAME VALIDATION
//  HTF must be strictly GREATER than the chart timeframe.
//  If not, HTF boxes are silently ignored.
// ══════════════════════════════════════════════════════════
currentTFsec = timeframe.in_seconds(timeframe.period)
htfSec       = timeframe.in_seconds(htfTimeframe)
htfIsValid   = htfSec > currentTFsec
 
// HTF boxes are only drawn if htfIsValid (HTF > current TF). If equal or lower, they are silently ignored.
 
// ══════════════════════════════════════════════════════════
//  DELTA FUNCTION
// ══════════════════════════════════════════════════════════
deltaHunting(lvl, lbk) =>
    _up_d  = (open - low)  - (high - close)
    _dn_d  = (high - open) - (close - low)
    _delta = _up_d != 0 ? _up_d : _dn_d != 0 ? _dn_d : na
    _pos   = _delta > 0 ? _delta : na
    _neg   = _delta < 0 ? _delta : na
    _hup   = _pos >= ta.stdev(_pos, lbk) * lvl
    _hdn   = _neg <= ta.stdev(_neg, lbk) * -lvl
    _buyTop  = open <= close ? (open + low) / 2 : (close + low) / 2
    _buyBot  = low
    _sellTop = high
    _sellBot = open < close ? (close + high) / 2 : (open + high) / 2
    [_hup, _hdn, _buyTop, _buyBot, _sellTop, _sellBot]
 
// ══════════════════════════════════════════════════════════
//  DELTA — CURRENT TF AND HTF
// ══════════════════════════════════════════════════════════
[huntingup, huntingdn, buyTop, buyBot, sellTop, sellBot] = deltaHunting(stddevlevel, stddevlookback)
[htf_hup, htf_hdn, htf_buyTop, htf_buyBot, htf_sellTop, htf_sellBot] = request.security(syminfo.tickerid, htfTimeframe, deltaHunting(stddevlevel, stddevlookback), lookahead=barmerge.lookahead_off)
 
// ══════════════════════════════════════════════════════════
//  HELPER — removes oldest box when limit is exceeded
// ══════════════════════════════════════════════════════════
pruneBoxes(boxArr, topArr, botArr, maxCount) =>
    while array.size(boxArr) > maxCount
        box.delete(array.shift(boxArr))
        array.shift(topArr)
        array.shift(botArr)
 
// ══════════════════════════════════════════════════════════
//  BOXES — CURRENT TF
//  Deleted when price closes beyond the zone
// ══════════════════════════════════════════════════════════
var box[]   curBuyBoxes  = array.new<box>()
var box[]   curSellBoxes = array.new<box>()
var float[] curBuyTops   = array.new<float>()
var float[] curBuyBots   = array.new<float>()
var float[] curSellTops  = array.new<float>()
var float[] curSellBots  = array.new<float>()
 
// Buy boxes current TF — deleted when price closes BELOW the bottom
// If hideCurrentOnHTF is active and HTF is valid, they are not drawn
showCurrentBoxes = not (hideCurrentOnHTF and showHTFBoxes and htfIsValid)
if showBuyBoxes and showCurrentBoxes
    if huntingup
        array.push(curBuyBoxes, box.new(left=bar_index, top=buyTop, right=bar_index + 5, bottom=buyBot, bgcolor=buyBoxColor, border_width=boxBorderWidth, border_color=buyBoxBorderColor))
        array.push(curBuyTops, buyTop)
        array.push(curBuyBots, buyBot)
        pruneBoxes(curBuyBoxes, curBuyTops, curBuyBots, maxCurrentBoxes)
    else if array.size(curBuyBoxes) > 0
        i = array.size(curBuyBoxes) - 1
        while i >= 0
            if deleteOnClose and close < array.get(curBuyBots, i)
                box.delete(array.get(curBuyBoxes, i))
                array.remove(curBuyBoxes, i)
                array.remove(curBuyTops, i)
                array.remove(curBuyBots, i)
            else
                box.set_right(array.get(curBuyBoxes, i), bar_index + 5)
            i -= 1
 
// Sell boxes current TF — deleted when price closes ABOVE the top
if showSellBoxes and showCurrentBoxes
    if huntingdn
        array.push(curSellBoxes, box.new(left=bar_index, top=sellTop, right=bar_index + 5, bottom=sellBot, bgcolor=sellBoxColor, border_width=boxBorderWidth, border_color=sellBoxBorderColor))
        array.push(curSellTops, sellTop)
        array.push(curSellBots, sellBot)
        pruneBoxes(curSellBoxes, curSellTops, curSellBots, maxCurrentBoxes)
    else if array.size(curSellBoxes) > 0
        i = array.size(curSellBoxes) - 1
        while i >= 0
            if deleteOnClose and close > array.get(curSellTops, i)
                box.delete(array.get(curSellBoxes, i))
                array.remove(curSellBoxes, i)
                array.remove(curSellTops, i)
                array.remove(curSellBots, i)
            else
                box.set_right(array.get(curSellBoxes, i), bar_index + 5)
            i -= 1
 
// ══════════════════════════════════════════════════════════
//  BOXES — HTF
//  Only drawn if htfIsValid (HTF strictly > current TF)
//  Distinct visual: near-transparent fill + thick solid border
//  Deleted when price closes beyond the zone
// ══════════════════════════════════════════════════════════
var box[]   htfBuyBoxes  = array.new<box>()
var box[]   htfSellBoxes = array.new<box>()
var float[] htfBuyTops   = array.new<float>()
var float[] htfBuyBots   = array.new<float>()
var float[] htfSellTops  = array.new<float>()
var float[] htfSellBots  = array.new<float>()
 
htfBuyNew  = showHTFBoxes and htfIsValid and showBuyBoxes  and htf_hup and not htf_hup[1]
htfSellNew = showHTFBoxes and htfIsValid and showSellBoxes and htf_hdn and not htf_hdn[1]
 
// Create new HTF Buy box
if htfBuyNew
    array.push(htfBuyBoxes, box.new(left=bar_index, top=htf_buyTop, right=bar_index + 500, bottom=htf_buyBot, bgcolor=htfBuyFillColor, border_width=htfBorderWidth, border_color=htfBuyBorderColor))
    array.push(htfBuyTops, htf_buyTop)
    array.push(htfBuyBots, htf_buyBot)
    pruneBoxes(htfBuyBoxes, htfBuyTops, htfBuyBots, maxHTFBoxes)
    if showHTFLabels
        label.new(x=bar_index, y=htf_buyBot, text="▲ " + htfTimeframe + "m BUY", style=label.style_label_upper_right, color=htfBuyBorderColor, textcolor=color.black, size=size.small)
 
// Create new HTF Sell box
if htfSellNew
    array.push(htfSellBoxes, box.new(left=bar_index, top=htf_sellTop, right=bar_index + 500, bottom=htf_sellBot, bgcolor=htfSellFillColor, border_width=htfBorderWidth, border_color=htfSellBorderColor))
    array.push(htfSellTops, htf_sellTop)
    array.push(htfSellBots, htf_sellBot)
    pruneBoxes(htfSellBoxes, htfSellTops, htfSellBots, maxHTFBoxes)
    if showHTFLabels
        label.new(x=bar_index, y=htf_sellTop, text="▼ " + htfTimeframe + "m SELL", style=label.style_label_lower_right, color=htfSellBorderColor, textcolor=color.black, size=size.small)
 
// Manage active HTF Buy boxes
// Deleted when price CLOSES BELOW the bottom (zone broken to the downside)
if array.size(htfBuyBoxes) > 0
    i = array.size(htfBuyBoxes) - 1
    while i >= 0
        breached = deleteOnClose and close < array.get(htfBuyBots, i)
        if breached
            box.delete(array.get(htfBuyBoxes, i))
            array.remove(htfBuyBoxes, i)
            array.remove(htfBuyTops, i)
            array.remove(htfBuyBots, i)
        else
            box.set_right(array.get(htfBuyBoxes, i), bar_index + 1)
        i -= 1
 
// Manage active HTF Sell boxes
// Deleted when price CLOSES ABOVE the top (zone broken to the upside)
if array.size(htfSellBoxes) > 0
    i = array.size(htfSellBoxes) - 1
    while i >= 0
        breached = deleteOnClose and close > array.get(htfSellTops, i)
        if breached
            box.delete(array.get(htfSellBoxes, i))
            array.remove(htfSellBoxes, i)
            array.remove(htfSellTops, i)
            array.remove(htfSellBots, i)
        else
            box.set_right(array.get(htfSellBoxes, i), bar_index + 1)
        i -= 1
 
// ══════════════════════════════════════════════════════════
//  ARROWS
// ══════════════════════════════════════════════════════════
plotshape(series=huntingup, location=location.belowbar, color=color.green, style=shape.triangleup,   size=size.tiny, title="Buy Pressure")
plotshape(series=huntingdn, location=location.abovebar, color=color.red,   style=shape.triangledown, size=size.tiny, title="Sell Pressure")
 
// ══════════════════════════════════════════════════════════
//  ALERTS (Delta Zones)
// ══════════════════════════════════════════════════════════
alertcondition(huntingup,  title="Buy Pressure Alert",  message="Buy pressure detected!")
alertcondition(huntingdn,  title="Sell Pressure Alert", message="Sell pressure detected!")
alertcondition(htfBuyNew,  title="HTF Buy Zone Alert",  message="HTF Buy zone appeared!")
alertcondition(htfSellNew, title="HTF Sell Zone Alert", message="HTF Sell zone appeared!")
 
 
// ════════════════════════════════════════════════════════════════
//  ZIGZAG PIVOT DETECTION (feeds BOTH section 5A lines and the 5B-5E
//  live volume profile below — single call, no redundant
//  recomputation). direction > 0 means the latest confirmed leg was
//  UP (z2 is a pivot HIGH); direction < 0 means it was DOWN (z2 is a
//  pivot LOW). z1/z2 are chart.point (price + bar index) for the
//  previous/current pivot.
// ════════════════════════════════════════════════════════════════
[direction, z1, z2] = ZigZag.zigzag(low, high, depth, deviation, backstep)
atrValue = ta.atr(atrLength)
 
bool profileBull = profileMode == "Bullish only" or profileMode == "Both"
bool profileBear = profileMode == "Bearish only" or profileMode == "Both"
 
// Resolved once per bar: when useAutoTheme is on, these track
// chart.fg_color (black on a light chart background, white on dark)
// instead of a fixed color, so the profile stays readable either way.
color effectiveNormalBorder    = useAutoTheme ? color.new(chart.fg_color, 70) : normalBorderColor
color effectiveLabelColor      = useAutoTheme ? chart.fg_color : labelTextColor
color effectiveDividerColorBull = useAutoTheme ? color.new(chart.fg_color, 60) : dividerColorBull
color effectiveDividerColorBear = useAutoTheme ? color.new(chart.fg_color, 60) : dividerColorBear
 
 
// ════════════════════════════════════════════════════════════════
//  SECTION 5A — OPTIONAL ZIGZAG LINES (purely visual, no labels)
//  "Repaint" mode redraws the live, still-moving segment every bar;
//  the non-repaint branch only draws once a segment is confirmed
//  (direction flips).
// ════════════════════════════════════════════════════════════════
line zz = na
 
if showLinesPA and not na(z1) and not na(z2)
    if repaintLines
        zz := line.new(z1, z2, xloc.bar_time, extendLines ? extend.right : extend.none, color.new(direction > 0 ? bullColor : bearColor, lineTransparency), width=lineThickness)
        if direction == direction[1]
            line.delete(zz[1])
        else
            line.set_extend(zz[1], extend.none)
    else
        if direction != direction[1] and not na(z1[1]) and not na(z2[1])
            zz := line.new(z1[1], z2[1], xloc.bar_time, extend.none, color.new(direction > 0 ? bullColor : bearColor, lineTransparency), width=lineThickness)
 
 
// ════════════════════════════════════════════════════════════════
//  SECTION 5B/C/D/E — LIVE VOLUME PROFILE STATE
//  Bull leg runs from a confirmed LOW (fixed) up to a running high.
//  Bear leg runs from a confirmed HIGH (fixed) down to a running low.
//  Everything below only draws/updates when enableVolumeProfile is on.
// ════════════════════════════════════════════════════════════════
 
// -- Leg being tracked: bullish (low -> running high) --
var int   legStartBar  = na
var float legLow       = na
var float legHigh      = na
var float[] legHighArr = array.new_float(0)
var float[] legLowArr  = array.new_float(0)
var float[] legVolArr  = array.new_float(0)
 
// -- Leg being tracked: bearish (high -> running low) --
var int   legTopBar     = na
var float legTop        = na
var float legLowRunning = na
var float[] legHighArrB = array.new_float(0)
var float[] legLowArrB  = array.new_float(0)
var float[] legVolArrB  = array.new_float(0)
 
// -- Drawing pools: "live*" = leg currently in progress, updated IN
// PLACE every bar; "vp*"/"pocLines*"/"vpDividers*" = permanent (FIFO)
// pools that finalized legs get moved into once their opposite pivot
// confirms. Bull and bear each get a complete, independent set. --
var box[]   liveBars        = array.new<box>(0)
var label[] liveLabels      = array.new<label>(0)
var line    livePocLine     = na
var line    liveDividerLine = na
var bool    liveInitialized = false
 
var box[]  vpBars     = array.new<box>(0)
var label[] vpLabels  = array.new<label>(0)
var line[] pocLines   = array.new<line>(0)
var line[] vpDividers = array.new<line>(0)
 
var box[]   liveBarsB        = array.new<box>(0)
var label[] liveLabelsB      = array.new<label>(0)
var line    livePocLineB     = na
var line    liveDividerLineB = na
var bool    liveInitializedB = false
 
var box[]  vpBarsB     = array.new<box>(0)
var label[] vpLabelsB  = array.new<label>(0)
var line[] pocLinesB   = array.new<line>(0)
var line[] vpDividersB = array.new<line>(0)
 
 
// ════════════════════════════════════════════════════════════════
//  HISTOGRAM MATH (pure calculation, no drawing, no global
//  reassignment — this is the only piece kept as a real Pine
//  function, since Pine functions may READ outer variables but may
//  NOT reassign them; this one only returns values, so it is shared
//  by both the bullish and bearish drawing code below).
//  Distributes each candle's volume across the vpBins levels its
//  high-low range overlaps, then finds the Value Area (the levels
//  holding the top valueAreaPct of total volume) and the POC (the
//  single highest-volume level).
// ════════════════════════════════════════════════════════════════
computeProfile(rangeLow, rangeHigh, highArr, lowArr, volArr) =>
    float span = rangeHigh - rangeLow
    int nBars = array.size(volArr)
 
    float[] binVol = array.new_float(vpBins, 0.0)
    for i = 0 to nBars - 1
        float bh = array.get(highArr, i)
        float bl = array.get(lowArr, i)
        float bv = array.get(volArr, i)
        float barRange = bh - bl
        for b = 0 to vpBins - 1
            float binBot = rangeLow + span * b / vpBins
            float binTop = rangeLow + span * (b + 1) / vpBins
            float overlap = math.max(0.0, math.min(bh, binTop) - math.max(bl, binBot))
            if barRange > 0 and overlap > 0
                array.set(binVol, b, array.get(binVol, b) + bv * (overlap / barRange))
 
    float maxVol = array.max(binVol)
    bool[] inValueArea = array.new_bool(vpBins, false)
    int pocBin = -1
 
    if maxVol > 0
        float totalVol = array.sum(binVol)
        float[] remaining = array.copy(binVol)
        float cum = 0.0
        float target = totalVol * valueAreaPct
        for k = 0 to vpBins - 1
            if cum >= target
                break
            float mx = array.max(remaining)
            if mx <= 0
                break
            int idx = array.indexof(remaining, mx)
            array.set(inValueArea, idx, true)
            cum += mx
            array.set(remaining, idx, -1.0)
        pocBin := array.indexof(binVol, maxVol)
 
    [binVol, inValueArea, maxVol, pocBin]
 
 
// ════════════════════════════════════════════════════════════════
//  PIVOT CONFIRMATION — START/FINALIZE BOTH LEG TYPES
//  Plain top-level code (not a function) on purpose: it reassigns
//  global "var" state, and Pine only allows that from top-level
//  script code, never from inside a user-defined function.
//
//  Each pivot confirmation is BOTH an ending and a beginning:
//  - A confirmed LOW ends a bearish leg (finalize it) AND begins a
//    bullish leg (start tracking it, with backfill for the bars
//    already elapsed during ZigZag's confirmation lag).
//  - A confirmed HIGH ends a bullish leg (finalize it) AND begins a
//    bearish leg (start tracking it, with the same backfill).
// ════════════════════════════════════════════════════════════════
if enableVolumeProfile and bool(ta.change(direction)) and not na(z2[1])
    if direction[1] < 0
        // ---- CONFIRMED LOW ----
        // finalize the bearish leg that was running down to this low
        if profileBear and liveInitializedB
            for b = 0 to array.size(liveBarsB) - 1
                array.push(vpBarsB, array.get(liveBarsB, b))
            for b = 0 to array.size(liveLabelsB) - 1
                array.push(vpLabelsB, array.get(liveLabelsB, b))
            array.push(pocLinesB, livePocLineB)
            array.push(vpDividersB, liveDividerLineB)
            array.clear(liveBarsB)
            array.clear(liveLabelsB)
            livePocLineB := na
            liveDividerLineB := na
            liveInitializedB := false
 
            while array.size(pocLinesB) > maxProfilesKeep
                for i = 0 to vpBins - 1
                    box.delete(array.shift(vpBarsB))
                    label.delete(array.shift(vpLabelsB))
                line.delete(array.shift(pocLinesB))
                line.delete(array.shift(vpDividersB))
        legTopBar := na
 
        // discard any bullish live profile that was never finalized (safety net)
        if liveInitialized
            for b = 0 to array.size(liveBars) - 1
                box.delete(array.get(liveBars, b))
            for b = 0 to array.size(liveLabels) - 1
                label.delete(array.get(liveLabels, b))
            array.clear(liveBars)
            array.clear(liveLabels)
            if not na(livePocLine)
                line.delete(livePocLine)
            if not na(liveDividerLine)
                line.delete(liveDividerLine)
            livePocLine := na
            liveDividerLine := na
            liveInitialized := false
 
        // start tracking the new bullish leg from this confirmed LOW
        if profileBull
            legStartBar := int((z2[1]).index)
            legLow      := (z2[1]).price
            legHigh     := (z2[1]).price
            array.clear(legHighArr)
            array.clear(legLowArr)
            array.clear(legVolArr)
 
            // backfill every bar between the actual pivot and today
            int gap = math.min(bar_index - legStartBar, 480)   // safety cap, see max_bars_back above
            for i = 0 to gap
                int offset = gap - i
                float bh = high[offset]
                float bl = low[offset]
                float bv = volume[offset]
                array.push(legHighArr, bh)
                array.push(legLowArr, bl)
                array.push(legVolArr, bv)
                if bh > legHigh
                    legHigh := bh
    else
        // ---- CONFIRMED HIGH ----
        // finalize the bullish leg that was running up to this high
        if profileBull and liveInitialized
            for b = 0 to array.size(liveBars) - 1
                array.push(vpBars, array.get(liveBars, b))
            for b = 0 to array.size(liveLabels) - 1
                array.push(vpLabels, array.get(liveLabels, b))
            array.push(pocLines, livePocLine)
            array.push(vpDividers, liveDividerLine)
            array.clear(liveBars)
            array.clear(liveLabels)
            livePocLine := na
            liveDividerLine := na
            liveInitialized := false
 
            while array.size(pocLines) > maxProfilesKeep
                for i = 0 to vpBins - 1
                    box.delete(array.shift(vpBars))
                    label.delete(array.shift(vpLabels))
                line.delete(array.shift(pocLines))
                line.delete(array.shift(vpDividers))
        legStartBar := na
 
        // discard any bearish live profile that was never finalized (safety net)
        if liveInitializedB
            for b = 0 to array.size(liveBarsB) - 1
                box.delete(array.get(liveBarsB, b))
            for b = 0 to array.size(liveLabelsB) - 1
                label.delete(array.get(liveLabelsB, b))
            array.clear(liveBarsB)
            array.clear(liveLabelsB)
            if not na(livePocLineB)
                line.delete(livePocLineB)
            if not na(liveDividerLineB)
                line.delete(liveDividerLineB)
            livePocLineB := na
            liveDividerLineB := na
            liveInitializedB := false
 
        // start tracking the new bearish leg from this confirmed HIGH
        if profileBear
            legTopBar     := int((z2[1]).index)
            legTop        := (z2[1]).price
            legLowRunning := (z2[1]).price
            array.clear(legHighArrB)
            array.clear(legLowArrB)
            array.clear(legVolArrB)
 
            // backfill every bar between the actual pivot and today
            int gapB = math.min(bar_index - legTopBar, 480)   // safety cap, see max_bars_back above
            for i = 0 to gapB
                int offset = gapB - i
                float bh = high[offset]
                float bl = low[offset]
                float bv = volume[offset]
                array.push(legHighArrB, bh)
                array.push(legLowArrB, bl)
                array.push(legVolArrB, bv)
                if bl < legLowRunning
                    legLowRunning := bl
 
 
// ════════════════════════════════════════════════════════════════
//  ONGOING DATA COLLECTION (every bar after each leg started).
//  Skipped on the confirmation bar itself, since the block above
//  already backfilled it.
// ════════════════════════════════════════════════════════════════
bool justConfirmedLow  = enableVolumeProfile and bool(ta.change(direction)) and not na(z2[1]) and direction[1] < 0
bool justConfirmedHigh = enableVolumeProfile and bool(ta.change(direction)) and not na(z2[1]) and direction[1] > 0
 
if enableVolumeProfile and not na(legStartBar) and not justConfirmedLow
    array.push(legHighArr, high)
    array.push(legLowArr, low)
    array.push(legVolArr, volume)
    if legHigh < high
        legHigh := high
 
if enableVolumeProfile and not na(legTopBar) and not justConfirmedHigh
    array.push(legHighArrB, high)
    array.push(legLowArrB, low)
    array.push(legVolArrB, volume)
    if legLowRunning > low
        legLowRunning := low
 
 
// ════════════════════════════════════════════════════════════════
//  LIVE REDRAW — BULLISH LEG
//  Runs every bar the bull leg is active, using the running high as
//  the provisional top of the range. The ATR gate (legBigEnough) and
//  duration gate (legLongEnough) decide when drawing starts; once
//  liveInitialized is true it keeps updating in place (box.set_*,
//  label.set_*, line.set_*) instead of deleting/recreating objects.
// ════════════════════════════════════════════════════════════════
bool legBigEnough  = (legHigh - legLow) >= atrMultiplier * atrValue
bool legLongEnough = array.size(legVolArr) >= minLegBars
 
if enableVolumeProfile and not na(legStartBar) and (legHigh - legLow) > 0 and (liveInitialized or (legBigEnough and legLongEnough))
    [binVol, inValueArea, maxVol, pocBin] = computeProfile(legLow, legHigh, legHighArr, legLowArr, legVolArr)
 
    if maxVol > 0
        float span = legHigh - legLow
 
        if not liveInitialized
            for b = 0 to vpBins - 1
                float v = array.get(binVol, b)
                float binBot = legLow + span * b / vpBins
                float binTop = legLow + span * (b + 1) / vpBins
                int barLen = math.max(1, math.round(v / maxVol * maxBarWidthBars))
                bool isVA  = array.get(inValueArea, b)
                bool isLVN = v < maxVol * lvnThreshold
                color fillC   = isVA ? colorValueAreaBull : colorNormalBull
                color borderC = isLVN ? lvnBorderColor : effectiveNormalBorder
                box newBox = box.new(legStartBar, binTop, legStartBar + barLen, binBot, border_color=borderC, border_width=isLVN ? 2 : 1, bgcolor=fillC)
                array.push(liveBars, newBox)
                label newLbl = label.new(legStartBar, (binTop + binBot) / 2, showVolLabels ? str.tostring(v, format.volume) : "", style=label.style_label_left, color=color(na), textcolor=effectiveLabelColor, size=size.small)
                array.push(liveLabels, newLbl)
            float pocBot0 = legLow + span * pocBin / vpBins
            float pocTop0 = legLow + span * (pocBin + 1) / vpBins
            float pocMid0 = (pocBot0 + pocTop0) / 2
            livePocLine     := line.new(legStartBar, pocMid0, bar_index, pocMid0, color=showPOC ? pocColorBull : color(na), width=2, style=line.style_dashed)
            liveDividerLine := line.new(legStartBar, legLow, legStartBar, legHigh, color=showDivider ? effectiveDividerColorBull : color(na), style=line.style_dotted, width=1)
            liveInitialized := true
        else
            for b = 0 to vpBins - 1
                float v = array.get(binVol, b)
                float binBot = legLow + span * b / vpBins
                float binTop = legLow + span * (b + 1) / vpBins
                int barLen = math.max(1, math.round(v / maxVol * maxBarWidthBars))
                bool isVA  = array.get(inValueArea, b)
                bool isLVN = v < maxVol * lvnThreshold
                color fillC   = isVA ? colorValueAreaBull : colorNormalBull
                color borderC = isLVN ? lvnBorderColor : effectiveNormalBorder
                box bx = array.get(liveBars, b)
                box.set_top(bx, binTop)
                box.set_bottom(bx, binBot)
                box.set_right(bx, legStartBar + barLen)
                box.set_bgcolor(bx, fillC)
                box.set_border_color(bx, borderC)
                box.set_border_width(bx, isLVN ? 2 : 1)
                label lb = array.get(liveLabels, b)
                label.set_xy(lb, legStartBar, (binTop + binBot) / 2)
                label.set_text(lb, showVolLabels ? str.tostring(v, format.volume) : "")
                label.set_textcolor(lb, effectiveLabelColor)
            float pocBot = legLow + span * pocBin / vpBins
            float pocTop = legLow + span * (pocBin + 1) / vpBins
            float pocMid = (pocBot + pocTop) / 2
            line.set_y1(livePocLine, pocMid)
            line.set_y2(livePocLine, pocMid)
            line.set_x2(livePocLine, bar_index)
            line.set_color(livePocLine, showPOC ? pocColorBull : color(na))
            line.set_y2(liveDividerLine, legHigh)
            line.set_color(liveDividerLine, showDivider ? effectiveDividerColorBull : color(na))
 
 
// ════════════════════════════════════════════════════════════════
//  LIVE REDRAW — BEARISH LEG
//  Mirror of the bullish block above: runs every bar the bear leg is
//  active, using the running low as the provisional bottom.
// ════════════════════════════════════════════════════════════════
bool legBigEnoughB  = (legTop - legLowRunning) >= atrMultiplier * atrValue
bool legLongEnoughB = array.size(legVolArrB) >= minLegBars
 
if enableVolumeProfile and not na(legTopBar) and (legTop - legLowRunning) > 0 and (liveInitializedB or (legBigEnoughB and legLongEnoughB))
    [binVolB, inValueAreaB, maxVolB, pocBinB] = computeProfile(legLowRunning, legTop, legHighArrB, legLowArrB, legVolArrB)
 
    if maxVolB > 0
        float spanB = legTop - legLowRunning
 
        if not liveInitializedB
            for b = 0 to vpBins - 1
                float v = array.get(binVolB, b)
                float binBot = legLowRunning + spanB * b / vpBins
                float binTop = legLowRunning + spanB * (b + 1) / vpBins
                int barLen = math.max(1, math.round(v / maxVolB * maxBarWidthBars))
                bool isVA  = array.get(inValueAreaB, b)
                bool isLVN = v < maxVolB * lvnThreshold
                color fillC   = isVA ? colorValueAreaBear : colorNormalBear
                color borderC = isLVN ? lvnBorderColor : effectiveNormalBorder
                box newBox = box.new(legTopBar, binTop, legTopBar + barLen, binBot, border_color=borderC, border_width=isLVN ? 2 : 1, bgcolor=fillC)
                array.push(liveBarsB, newBox)
                label newLbl = label.new(legTopBar, (binTop + binBot) / 2, showVolLabels ? str.tostring(v, format.volume) : "", style=label.style_label_left, color=color(na), textcolor=effectiveLabelColor, size=size.small)
                array.push(liveLabelsB, newLbl)
            float pocBot0 = legLowRunning + spanB * pocBinB / vpBins
            float pocTop0 = legLowRunning + spanB * (pocBinB + 1) / vpBins
            float pocMid0 = (pocBot0 + pocTop0) / 2
            livePocLineB     := line.new(legTopBar, pocMid0, bar_index, pocMid0, color=showPOC ? pocColorBear : color(na), width=2, style=line.style_dashed)
            liveDividerLineB := line.new(legTopBar, legLowRunning, legTopBar, legTop, color=showDivider ? effectiveDividerColorBear : color(na), style=line.style_dotted, width=1)
            liveInitializedB := true
        else
            for b = 0 to vpBins - 1
                float v = array.get(binVolB, b)
                float binBot = legLowRunning + spanB * b / vpBins
                float binTop = legLowRunning + spanB * (b + 1) / vpBins
                int barLen = math.max(1, math.round(v / maxVolB * maxBarWidthBars))
                bool isVA  = array.get(inValueAreaB, b)
                bool isLVN = v < maxVolB * lvnThreshold
                color fillC   = isVA ? colorValueAreaBear : colorNormalBear
                color borderC = isLVN ? lvnBorderColor : effectiveNormalBorder
                box bx = array.get(liveBarsB, b)
                box.set_top(bx, binTop)
                box.set_bottom(bx, binBot)
                box.set_right(bx, legTopBar + barLen)
                box.set_bgcolor(bx, fillC)
                box.set_border_color(bx, borderC)
                box.set_border_width(bx, isLVN ? 2 : 1)
                label lb = array.get(liveLabelsB, b)
                label.set_xy(lb, legTopBar, (binTop + binBot) / 2)
                label.set_text(lb, showVolLabels ? str.tostring(v, format.volume) : "")
                label.set_textcolor(lb, effectiveLabelColor)
            float pocBot = legLowRunning + spanB * pocBinB / vpBins
            float pocTop = legLowRunning + spanB * (pocBinB + 1) / vpBins
            float pocMid = (pocBot + pocTop) / 2
            line.set_y1(livePocLineB, pocMid)
            line.set_y2(livePocLineB, pocMid)
            line.set_x2(livePocLineB, bar_index)
            line.set_color(livePocLineB, showPOC ? pocColorBear : color(na))
            line.set_y2(liveDividerLineB, legLowRunning)
            line.set_color(liveDividerLineB, showDivider ? effectiveDividerColorBear : color(na))
 
// End of script.

← 返回列表