Consolidation Range POC

Jizzany17 · study · 544 行 · 点赞 39 · 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/
// © LonesomeTheBlue — original consolidation detection
// © Jizzany17 — consolidation redesign, swing anchoring, per-range footprint POC, liquidity, and gap-aware ranges
//@version=6
indicator("Consolidation Range POC", overlay = true, behind_chart = true, max_bars_back = 1100, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 100, max_polylines_count = 100)
 
int prd = input.int(10, "Lookback", minval = 2, maxval = 50, group = "Consolidation", inline = "detect")
int conslen = input.int(5, "Min bars", minval = 2, maxval = 20, group = "Consolidation", inline = "detect", tooltip = "Lookback: candles used to find rolling highs/lows. Min bars: consolidation counter required before drawing a box. Price structure determines which candles qualify.")
bool closeOnly = input.bool(false, "On candle close", group = "Consolidation", inline = "commit", tooltip = "On commits range geometry on completed candles. Breakout, liquidity, and POC retest alerts always wait for candle close.")
bool paintcons = input.bool(true, "Fill area", group = "Consolidation Box", inline = "boxcolors")
color zonecol = input.color(color.new(color.rgb(60, 62, 196), 72), "Fill", group = "Consolidation Box", inline = "boxcolors")
color zoneBorder = input.color(color.new(color.navy, 54.5), "Border", group = "Consolidation Box", inline = "boxcolors")
string zoneStyleName = input.string("Solid", "Style", options = ["Solid", "Dotted", "Dashed"], group = "Consolidation Box", inline = "boxline")
int zoneBorderWidth = input.int(2, "Thickness", minval = 1, maxval = 4, group = "Consolidation Box", inline = "boxline")
string zoneBorderStyle = zoneStyleName == "Solid" ? line.style_solid : zoneStyleName == "Dotted" ? line.style_dotted : line.style_dashed
 
bool showExpansion = input.bool(true, "Show expansion", group = "POC", inline = "pocshow")
string expansionMode = input.string("Until next POC line", "Extend", options = ["Until next POC line", "Keep extending"], group = "POC", inline = "pocshow")
int pocWidth = input.int(2, "Width", minval = 1, maxval = 4, group = "POC", inline = "pocstyle")
color expansionColor = input.color(color.white, "Color", group = "POC", inline = "pocstyle")
string expansionStyle = input.string("Solid", "Style", options = ["Solid", "Dotted", "Dashed"], group = "POC", inline = "pocstyle")
string expansionLineStyle = expansionStyle == "Solid" ? line.style_solid : expansionStyle == "Dotted" ? line.style_dotted : line.style_dashed
bool showCurrentPoc = input.bool(true, "Current POC", group = "POC", inline = "poccurrent")
int currentPocBars = input.int(3, "Length (bars)", minval = 1, maxval = 20, group = "POC", inline = "poccurrent")
 
bool showLiquidity = input.bool(true, "Show liquidity", group = "Liquidity", inline = "liqshow")
color lowLiquidityColor = input.color(color.green, "Low", group = "Liquidity", inline = "liqcolor")
color highLiquidityColor = input.color(color.red, "High", group = "Liquidity", inline = "liqcolor")
string liquidityStyle = input.string("Dotted", "Style", options = ["Solid", "Dotted", "Dashed"], group = "Liquidity", inline = "liqcolor")
int liquidityWidth = input.int(1, "Stopped width", minval = 1, maxval = 4, group = "Liquidity", inline = "liqwidth")
int unsweptLiquidityWidth = input.int(2, "Unswept width", minval = 1, maxval = 4, group = "Liquidity", inline = "liqwidth")
int liquidityKeep = input.int(100, "Keep levels", minval = 2, maxval = 100, group = "Liquidity", inline = "liqshow", tooltip = "Uses a separate drawing budget from the 480 range boxes and POC lines. At capacity, removes the oldest stopped level first, otherwise the oldest active level. These are potential liquidity levels inferred from range boundaries.")
string liquidityLineStyle = liquidityStyle == "Solid" ? line.style_solid : liquidityStyle == "Dotted" ? line.style_dotted : line.style_dashed
 
bool showProfile = input.bool(false, "Show histogram", group = "Volume Profile", inline = "profile")
int rowCount = input.int(24, "Display rows", minval = 8, maxval = 60, group = "Volume Profile", inline = "profiledims")
int widthPct = input.int(40, "Width (%)", minval = 10, maxval = 80, group = "Volume Profile", inline = "profiledims")
int keepRequested = input.int(480, "Keep ranges", minval = 1, maxval = 480, group = "Consolidation", inline = "commit", tooltip = "With profiles hidden, keeps up to 480 consolidation boxes and their POC lines from loaded chart history. Showing volume profiles reduces this limit to fit TradingView's drawing budget.")
// One-tick footprint rows keep price levels aligned across all range candles.
// Requires TradingView Premium or Ultimate; never substitutes candle estimates.
footprint barFootprint = request.footprint(1)
 
color profileColor = input.color(color.new(color.teal, 45), "Color", group = "Volume Profile", inline = "profile")
 
// No Gaps - Jizzany: adjusted candle geometry also drives ranges and liquidity.
// Footprint volume always remains the actual supplied data.
bool showOverlay = input.bool(true, "Enable", group = "Candle Fill", inline = "overlay")
string overlayStyle = input.string("Candles", "Type", options = ["Candles", "Bars"], group = "Candle Fill", inline = "overlay", tooltip = "Bridges price gaps from the previous close. Consolidation bounds and liquidity use the complete adjusted candle; footprint volume is unchanged. Pine cannot read chart candle colors: match the color controls below to your chart.")
color bullBody = input.color(#4caf50, "Bull body", group = "Candle Fill", inline = "bull")
color bearBody = input.color(#ef5350, "Bear body", group = "Candle Fill", inline = "bear")
color bullWick = input.color(#4caf50, "Wick", group = "Candle Fill", inline = "bull")
color bearWick = input.color(#ef5350, "Wick", group = "Candle Fill", inline = "bear")
color bullBorder = input.color(color.new(#4caf50, 100), "Border", group = "Candle Fill", inline = "bull")
color bearBorder = input.color(color.new(#ef5350, 100), "Border", group = "Candle Fill", inline = "bear")
[overlayOpen, overlayHigh, overlayLow, overlayClose] = request.security(syminfo.tickerid, timeframe.period, [open, high, low, close], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
 
gapCandle(float sourceOpen, float sourceHigh, float sourceLow, float sourceClose, float previousClose) =>
    float candleOpen = na(previousClose) ? sourceOpen : previousClose
    float candleHigh = math.max(sourceHigh, math.max(candleOpen, sourceClose))
    float candleLow = math.min(sourceLow, math.min(candleOpen, sourceClose))
    [candleOpen, candleHigh, candleLow, sourceClose]
 
[gapOpen, gapHigh, gapLow, gapClose] = gapCandle(overlayOpen, overlayHigh, overlayLow, overlayClose, overlayClose[1])
float rangeOpen = showOverlay ? gapOpen : open
float rangeHigh = showOverlay ? gapHigh : high
float rangeLow = showOverlay ? gapLow : low
float rangeClose = showOverlay ? gapClose : close
// Direction belongs to the adjusted body; its palette matches the user's chart.
bool overlayBull = rangeClose >= rangeOpen
bool drawCandles = showOverlay and overlayStyle == "Candles"
bool drawBars = showOverlay and overlayStyle == "Bars"
 
// Preserve the supplied displacement rule on the native chart candles.
bool showDisplacement = input.bool(true, "Enable", group = "Displacement", inline = "dispshow")
string dispType = input.string("High to Low", "Type", options = ["Open to Close", "High to Low"], group = "Displacement", inline = "disptype")
int stdLen = input.int(50, "Length", minval = 1, group = "Displacement", inline = "dispstrength")
int stdStrength = input.int(3, "Strength", minval = 0, group = "Displacement", inline = "dispstrength")
color dispColor = input.color(color.yellow, "Color", group = "Displacement", inline = "disptype")
bool requireFvg = input.bool(true, "Require FVG", group = "Displacement", inline = "dispshow", tooltip = "Confirms displacement on the following candle and colors the preceding candle. Confirmation can change while the following candle is open.")
float candleRange = dispType == "Open to Close" ? math.abs(open - close) : high - low
float displacementThreshold = ta.stdev(candleRange, stdLen) * stdStrength
bool displacementFvg = close[1] > open[1] ? high[2] < low : low[2] > high
bool displacement = requireFvg ? candleRange[1] > displacementThreshold[1] and displacementFvg : candleRange > displacementThreshold
// Native candle plots size themselves with the chart. No drawing substitutes.
// FVG confirmation colors the original preceding chart candle with barcolor.
barcolor(showOverlay ? color.new(color.white, 100) : na, title = "Overlay base visibility")
barcolor(showDisplacement and displacement ? dispColor : showOverlay ? color.new(color.white, 100) : na, offset = requireFvg ? -1 : 0, title = "Original displacement")
 
bool highlightNow = showDisplacement and not requireFvg and displacement
color bodyColor = highlightNow ? dispColor : overlayBull ? bullBody : bearBody
color wickColor = highlightNow ? dispColor : overlayBull ? bullWick : bearWick
color configuredBorder = overlayBull ? bullBorder : bearBorder
color borderColor = highlightNow ? dispColor : color.t(configuredBorder) == 100 ? bodyColor : configuredBorder
plotcandle(drawCandles ? rangeOpen : na, rangeHigh, rangeLow, rangeClose, title = "Candle Fill", color = bodyColor, wickcolor = wickColor, bordercolor = borderColor, display = display.pane)
plotbar(drawBars ? rangeOpen : na, rangeHigh, rangeLow, rangeClose, title = "Candle Fill Bars", color = bodyColor, display = display.pane)
 
// Each zone owns its drawings, so deleting an old zone removes the entire profile.
type Zone
    box area
    line expansion
    array<box> rows
    int leftTime
    int rightTime
    float pocPrice
    float topPrice
    float bottomPrice
    int completedAt
    bool pocTouched
    bool pocBullRetested
    bool pocBearRetested
 
deleteZone(Zone z) =>
    box.delete(z.area)
    line.delete(z.expansion)
    for rowBox in z.rows
        box.delete(rowBox)
 
type LiquidityLevel
    polyline drawing
    bool lowSide
    bool touched
    bool stopped
    float price
    int origin
    int endTime
 
liquidityTouched(bool lowSide, float price, float barHigh, float barLow) =>
    lowSide ? barLow <= price : barHigh >= price
 
// 1 = exact contact, 2 = wick beyond with close back inside, 3 = close beyond.
classifyLiquidity(bool lowSide, float price, float barHigh, float barLow, float barClose) =>
    int eventType = 0
    if liquidityTouched(lowSide, price, barHigh, barLow)
        if lowSide
            eventType := barClose < price ? 3 : barLow < price ? 2 : 1
        else
            eventType := barClose > price ? 3 : barHigh > price ? 2 : 1
    eventType
 
advanceLiquidity(LiquidityLevel level, float barHigh, float barLow, float barClose, int barTime, bool confirmed) =>
    int eventType = 0
    // The origin candle belongs to the range, so cannot sweep its own boundary.
    // Classify only completed candles so a breakout cannot be called a sweep.
    if not level.stopped and barTime > level.origin
        level.endTime := barTime
        if confirmed
            eventType := classifyLiquidity(level.lowSide, level.price, barHigh, barLow, barClose)
            if eventType == 1
                if level.touched
                    eventType := 0
                else
                    level.touched := true
            else if eventType > 1
                level.touched := true
                level.stopped := true
    eventType
 
newLiquidity(array<LiquidityLevel> levels, bool lowSide, float price, int origin) =>
    while array.size(levels) >= liquidityKeep
        int removeAt = 0
        for i = 0 to array.size(levels) - 1
            if array.get(levels, i).stopped
                removeAt := i
                break
        LiquidityLevel old = array.remove(levels, removeAt)
        polyline.delete(old.drawing)
    array.push(levels, LiquidityLevel.new(na, lowSide, false, false, price, origin, origin))
 
advancePocTouch(Zone z, float barHigh, float barLow, float barClose, float previousClose, int barTime, bool confirmed) =>
    bool touched = false
    bool bullRetest = false
    bool bearRetest = false
    if confirmed and not na(z.completedAt) and barTime > z.completedAt and not na(z.pocPrice)
        if barLow <= z.pocPrice and barHigh >= z.pocPrice
            if not z.pocTouched
                z.pocTouched := true
                touched := true
            if not z.pocBullRetested and previousClose > z.pocPrice and barClose > z.pocPrice
                z.pocBullRetested := true
                bullRetest := true
            if not z.pocBearRetested and previousClose < z.pocPrice and barClose < z.pocPrice
                z.pocBearRetested := true
                bearRetest := true
    [touched, bullRetest, bearRetest]
 
renderLiquidity(LiquidityLevel level) =>
    // Recreate when stopped or on the last chart bar, not every historical bar.
    polyline.delete(level.drawing)
    array<chart.point> points = array.from(chart.point.from_time(level.origin, level.price), chart.point.from_time(level.endTime, level.price))
    level.drawing := polyline.new(points, xloc = xloc.bar_time, line_color = level.lowSide ? lowLiquidityColor : highLiquidityColor, line_style = liquidityLineStyle, line_width = level.stopped ? liquidityWidth : unsweptLiquidityWidth)
 
// Integer half-tick keys preserve the centers supplied by one-tick footprint rows.
addFootprintRow(map<int, float> totals, int priceKey, float rowVolume) =>
    if not na(rowVolume) and rowVolume > 0
        if not map.contains(totals, priceKey) and map.size(totals) >= 40000
            runtime.error("A range exceeded 40,000 footprint price levels. Use a shorter consolidation setting.")
        map.put(totals, priceKey, nz(map.get(totals, priceKey), 0.0) + rowVolume)
 
accumulateFootprint(map<int, float> totals, footprint fp) =>
    bool available = not na(fp)
    if available
        array<volume_row> rows = fp.rows()
        available := array.size(rows) > 0
        for row in rows
            float rowVolume = row.total_volume()
            if na(rowVolume)
                available := false
            else
                int priceKey = int(math.round((row.down_price() + row.up_price()) / syminfo.mintick))
                addFootprintRow(totals, priceKey, rowVolume)
    available
 
footprintPocKey(map<int, float> totals) =>
    float peak = 0.0
    int bestKey = na
    for priceKey in map.keys(totals)
        float rowVolume = map.get(totals, priceKey)
        if rowVolume > peak or (rowVolume == peak and (na(bestKey) or priceKey < bestKey))
            peak := rowVolume
            bestKey := priceKey
    bestKey
 
// Histogram display allocation only; never used to calculate the footprint POC.
// Allocate a candle's volume by the fraction of its high-low interval in each row.
// Zero-range candles contribute all volume to the row containing their price.
addVolume(array<float> bins, float candleLow, float candleHigh, float candleVol, float base, float step) =>
    if not na(candleVol) and candleVol > 0
        int count = array.size(bins)
        int first = math.max(0, math.min(count - 1, int(math.floor((candleLow - base) / step))))
        int last = math.max(0, math.min(count - 1, int(math.floor((candleHigh - base) / step))))
        float span = candleHigh - candleLow
        if span <= 0
            array.set(bins, first, array.get(bins, first) + candleVol)
        else
            for row = first to last
                float bottom = base + row * step
                float overlap = math.max(0.0, math.min(candleHigh, bottom + step) - math.max(candleLow, bottom))
                array.set(bins, row, array.get(bins, row) + candleVol * overlap / span)
 
// Original rolling-extreme / direction logic, with explicit v6 boolean checks.
float hb = ta.highestbars(rangeHigh, prd) == 0 ? rangeHigh : na
float lb = ta.lowestbars(rangeLow, prd) == 0 ? rangeLow : na
bool hasHigh = not na(hb) and hb != 0
bool hasLow = not na(lb) and lb != 0
var int dir = 0
dir := hasHigh and not hasLow ? 1 : hasLow and not hasHigh ? -1 : dir
float zz = hasHigh and hasLow ? (dir == 1 ? hb : lb) : hasHigh ? hb : hasLow ? lb : na
float pp = na
for x = 0 to 1000
    if x > bar_index or dir != dir[x]
        break
    if not na(zz[x]) and zz[x] != 0
        if na(pp)
            pp := zz[x]
        else if dir[x] == 1 and zz[x] > pp
            pp := zz[x]
        else if dir[x] == -1 and zz[x] < pp
            pp := zz[x]
 
float pivotChange = ta.change(pp)
float seedHigh = ta.highest(rangeHigh, conslen)
float seedLow = ta.lowest(rangeLow, conslen)
var int conscnt = 0
var float condhigh = na
var float condlow = na
var int candidateSide = 0
var float candidateExtreme = na
bool breakoutup = false
bool breakoutdown = false
bool pocBreakoutUp = false
bool pocBreakoutDown = false
bool zoneCreated = false
bool liquidityStarted = false
bool liquidityTouchedAlert = false
bool liquiditySweptAlert = false
bool liquidityBrokenAlert = false
bool pocTouchedAlert = false
bool pocBullRetestAlert = false
bool pocBearRetestAlert = false
 
var array<Zone> zones = array.new<Zone>()
var Zone active = na
var line lastExpansion = na
var Zone lastPocZone = na
var line currentPocLine = na
var map<int, float> footprintTotals = map.new<int, float>()
var int footprintBars = 0
var int missingFootprintBars = 0
var int incompleteRanges = 0
var array<float> bins = array.new_float(rowCount, 0.0)
var array<LiquidityLevel> liquidityLevels = array.new<LiquidityLevel>()
int keepCount = math.min(keepRequested, int(math.floor(480.0 / (showProfile ? rowCount + 1 : 1))))
 
if not closeOnly or barstate.isconfirmed
    // Grow completed-zone expansions only to the current candle, like Master Pattern.
    // Only a new POC expansion clips the previous line, at the new line's start.
    if expansionMode == "Keep extending"
        for z in zones
            if not na(z.expansion)
                line.set_x2(z.expansion, time)
    else if not na(lastExpansion)
        line.set_x2(lastExpansion, time)
 
    // A close outside the established range ends it before this candle can
    // expand the box or contribute its footprint. The exit candle begins the
    // next candidate window; its immediate predecessor can anchor the left
    // edge only when it is a qualifying swing high or swing low.
    bool priceBreakoutUp = false
    bool priceBreakoutDown = false
    if not na(active)
        priceBreakoutUp := rangeClose > active.topPrice
        priceBreakoutDown := rangeClose < active.bottomPrice
 
    bool resetCandidate = false
    int resetSide = 0
    bool pivotChanged = not na(pivotChange) and pivotChange != 0
    if not na(active)
        if priceBreakoutUp or priceBreakoutDown
            // A breakout alert means a confirmed close beyond the box.
            breakoutup := priceBreakoutUp and barstate.isconfirmed
            breakoutdown := priceBreakoutDown and barstate.isconfirmed
            pocBreakoutUp := breakoutup and not na(active.pocPrice)
            pocBreakoutDown := breakoutdown and not na(active.pocPrice)
            resetCandidate := true
            resetSide := priceBreakoutUp ? 1 : -1
        else if pivotChanged
            if conscnt > 0 and pp <= condhigh and pp >= condlow
                conscnt += 1
            else
                resetCandidate := true
                resetSide := pp > condhigh ? 1 : pp < condlow ? -1 : dir
        else
            conscnt += 1
    else
        // Count from the last directional swing extreme. New highs during an
        // upward move or new lows during a downward move restart the minimum
        // consolidation length at that candle, even if only its wick extends.
        bool candidateAbove = conscnt > 0 and not na(condhigh) and rangeClose > condhigh
        bool candidateBelow = conscnt > 0 and not na(condlow) and rangeClose < condlow
        bool freshSwingExtreme = conscnt > 0 and not na(candidateExtreme) and ((candidateSide == 1 and rangeHigh > candidateExtreme) or (candidateSide == -1 and rangeLow < candidateExtreme))
        if candidateAbove or candidateBelow
            resetCandidate := true
            resetSide := candidateAbove ? 1 : -1
        else if freshSwingExtreme
            resetCandidate := true
            resetSide := candidateSide
        else if conscnt > 0 and not na(condhigh) and not na(condlow)
            conscnt += 1
            condhigh := math.max(condhigh, rangeHigh)
            condlow := math.min(condlow, rangeLow)
        else
            resetCandidate := true
 
    if resetCandidate
        candidateSide := resetSide != 0 ? resetSide : dir != 0 ? dir : rangeClose >= rangeOpen ? 1 : -1
        candidateExtreme := candidateSide == 1 ? rangeHigh : rangeLow
        conscnt := 1
        condhigh := rangeHigh
        condlow := rangeLow
        // The extra left candle may shape the candidate only if it turns
        // beyond the candle on its own left. The seed confirms its right side.
        if bar_index > 1 and (rangeHigh[1] > rangeHigh[2] or rangeLow[1] < rangeLow[2])
            condhigh := math.max(condhigh, rangeHigh[1])
            condlow := math.min(condlow, rangeLow[1])
 
    // End BEFORE processing this candle's volume: the terminating bar is excluded.
    if not na(active) and conscnt < conslen
        line.delete(currentPocLine)
        currentPocLine := na
        active.completedAt := time
        // Freeze BOTH boundaries immediately; no two-sided close-crossing gate.
        // The sweep pass below includes this terminating candle.
        if showLiquidity
            newLiquidity(liquidityLevels, true, active.bottomPrice, active.rightTime)
            newLiquidity(liquidityLevels, false, active.topPrice, active.rightTime)
            liquidityStarted := barstate.isconfirmed
        if showExpansion and not na(active.pocPrice)
            if expansionMode != "Keep extending" and not na(lastExpansion)
                line.set_x2(lastExpansion, active.rightTime)
            active.expansion := line.new(active.rightTime, active.pocPrice, time, active.pocPrice, xloc = xloc.bar_time, extend = extend.none, color = expansionColor, style = expansionLineStyle, width = pocWidth)
            lastExpansion := active.expansion
        if not na(active.pocPrice)
            lastPocZone := active
        if missingFootprintBars > 0
            incompleteRanges += 1
        active := na
        map.clear(footprintTotals)
        footprintBars := 0
        missingFootprintBars := 0
 
    if conscnt >= conslen and bar_index >= conslen - 1
        bool starting = conscnt == conslen
        int seedOffset = conslen - 1
        if starting
            condhigh := seedHigh
            condlow := seedLow
            // Include only the immediately preceding LEFT swing: its high
            // exceeds the candle on its left and the entire seed, or its low
            // is below both. Include its full adjusted candle and footprint.
            if bar_index >= conslen + 1
                bool priorSwingHigh = rangeHigh[conslen] > rangeHigh[conslen + 1] and rangeHigh[conslen] > seedHigh
                bool priorSwingLow = rangeLow[conslen] < rangeLow[conslen + 1] and rangeLow[conslen] < seedLow
                if priorSwingHigh or priorSwingLow
                    seedOffset := conslen
                    condhigh := math.max(seedHigh, rangeHigh[conslen])
                    condlow := math.min(seedLow, rangeLow[conslen])
        else
            condhigh := math.max(condhigh, rangeHigh)
            condlow := math.min(condlow, rangeLow)
 
        if starting
            // Box and profile share the same expanded seed window.
            int leftTime = time[seedOffset]
            while array.size(zones) >= keepCount
                Zone oldest = array.shift(zones)
                if not na(oldest.expansion) and not na(lastExpansion) and line.get_x1(oldest.expansion) == line.get_x1(lastExpansion)
                    lastExpansion := na
                if not na(lastPocZone) and oldest.leftTime == lastPocZone.leftTime
                    lastPocZone := na
                deleteZone(oldest)
            box area = na
            array<box> rowBoxes = array.new_box()
            active := Zone.new(area, na, rowBoxes, leftTime, time, na, condhigh, condlow, na, false, false, false)
            array.push(zones, active)
            map.clear(footprintTotals)
            footprintBars := 0
            missingFootprintBars := 0
            for offset = seedOffset to 0
                bool available = accumulateFootprint(footprintTotals, barFootprint[offset])
                footprintBars += 1
                missingFootprintBars += available ? 0 : 1
            zoneCreated := barstate.isconfirmed
        else if not na(active)
            // Pine rollback restores the committed map before each live update,
            // so the current bar's cumulative footprint is added exactly once.
            bool available = accumulateFootprint(footprintTotals, barFootprint)
            footprintBars += 1
            missingFootprintBars += available ? 0 : 1
 
        if not na(active)
            int bestKey = footprintPocKey(footprintTotals)
            // Never present a partial-range POC as a complete footprint POC.
            float pocPrice = missingFootprintBars == 0 and not na(bestKey) ? math.max(condlow, math.min(condhigh, bestKey * syminfo.mintick / 2.0)) : na
            active.pocPrice := pocPrice
            active.rightTime := time
            active.topPrice := condhigh
            active.bottomPrice := condlow
            // Retained ranges render independently of viewport and zoom.
            if na(active.area)
                active.area := box.new(active.leftTime, condhigh, time, condlow, xloc = xloc.bar_time, border_color = zoneBorder, border_width = zoneBorderWidth, border_style = zoneBorderStyle, bgcolor = paintcons ? zonecol : na)
                if showProfile
                    for row = 0 to rowCount - 1
                        array.push(active.rows, box.new(active.leftTime, condhigh, active.leftTime, condlow, xloc = xloc.bar_time, border_color = na, bgcolor = na))
            box.set_right(active.area, time)
            box.set_top(active.area, condhigh)
            box.set_bottom(active.area, condlow)
            box.set_bgcolor(active.area, paintcons ? zonecol : na)
 
            // One short, developing POC marker at the active range's right edge.
            // It is replaced by the frozen expansion when the range ends.
            if showCurrentPoc and not na(pocPrice)
                if na(currentPocLine)
                    currentPocLine := line.new(bar_index, pocPrice, bar_index + currentPocBars, pocPrice, xloc = xloc.bar_index, color = expansionColor, style = expansionLineStyle, width = pocWidth)
                else
                    line.set_xy1(currentPocLine, bar_index, pocPrice)
                    line.set_xy2(currentPocLine, bar_index + currentPocBars, pocPrice)
            else
                line.delete(currentPocLine)
                currentPocLine := na
 
            if showProfile and array.size(active.rows) > 0
                // Coarse histogram rows are a display choice; POC stays one-tick.
                float step = math.max((condhigh - condlow) / rowCount, syminfo.mintick)
                array.fill(bins, 0.0)
                for priceKey in map.keys(footprintTotals)
                    float rowPrice = math.max(condlow, math.min(condhigh, priceKey * syminfo.mintick / 2.0))
                    addVolume(bins, rowPrice, rowPrice, map.get(footprintTotals, priceKey), condlow, step)
                float maxVolume = array.max(bins)
                int pocRow = not na(pocPrice) ? math.max(0, math.min(rowCount - 1, int(math.floor((pocPrice - condlow) / step)))) : -1
                int maxWidth = int((time - active.leftTime) * widthPct / 100.0)
                for row = 0 to rowCount - 1
                    box rowBox = array.get(active.rows, row)
                    float rowVolume = array.get(bins, row)
                    float bottom = condlow + row * step
                    float top = math.min(condhigh, bottom + step)
                    int rowWidth = maxVolume > 0 ? int(maxWidth * rowVolume / maxVolume) : 0
                    box.set_left(rowBox, active.leftTime)
                    box.set_right(rowBox, active.leftTime + rowWidth)
                    box.set_bottom(rowBox, math.min(bottom, condhigh))
                    box.set_top(rowBox, top)
                    box.set_bgcolor(rowBox, missingFootprintBars == 0 and rowVolume > 0 ? (row == pocRow ? expansionColor : profileColor) : na)
 
    // The alert follows each completed POC's expansion lifetime, even if its
    // drawing is hidden. Retained POCs stay eligible in Keep extending mode.
    if expansionMode == "Keep extending"
        for z in zones
            [newPocTouch, newBullRetest, newBearRetest] = advancePocTouch(z, rangeHigh, rangeLow, rangeClose, rangeClose[1], time, barstate.isconfirmed)
            pocTouchedAlert := pocTouchedAlert or newPocTouch
            pocBullRetestAlert := pocBullRetestAlert or newBullRetest
            pocBearRetestAlert := pocBearRetestAlert or newBearRetest
    else if not na(lastPocZone)
        [newPocTouch, newBullRetest, newBearRetest] = advancePocTouch(lastPocZone, rangeHigh, rangeLow, rangeClose, rangeClose[1], time, barstate.isconfirmed)
        pocTouchedAlert := newPocTouch
        pocBullRetestAlert := newBullRetest
        pocBearRetestAlert := newBearRetest
 
    if showLiquidity
        // Every retained range level remains independent of later consolidations.
        for level in liquidityLevels
            int levelEvent = advanceLiquidity(level, rangeHigh, rangeLow, rangeClose, time, barstate.isconfirmed)
            liquidityTouchedAlert := liquidityTouchedAlert or levelEvent == 1
            liquiditySweptAlert := liquiditySweptAlert or levelEvent == 2
            liquidityBrokenAlert := liquidityBrokenAlert or levelEvent == 3
            if level.stopped and levelEvent > 1 or (barstate.islast and not level.stopped)
                renderLiquidity(level)
 
// Show a small data-quality notice only when needed; never show POC price labels.
var table status = table.new(position.bottom_right, 1, 1)
if barstate.islast
    string volumeNotice = ""
    if not na(active) and missingFootprintBars > 0
        volumeNotice := "POC unavailable: footprint missing for " + str.tostring(missingFootprintBars) + "/" + str.tostring(footprintBars) + " range candles"
    else if not na(active) and na(active.pocPrice)
        volumeNotice := "POC unavailable: no positive footprint volume"
    if incompleteRanges > 0
        volumeNotice += (volumeNotice != "" ? "\n" : "") + str.tostring(incompleteRanges) + " completed ranges lack full footprint data"
    table.cell(status, 0, 0, volumeNotice, text_color = color.silver, text_size = size.tiny, bgcolor = volumeNotice != "" ? color.new(color.black, 80) : na)
 
// A POC expansion is the confirmed box breakout, regardless of displacement/FVG.
bool bullishPocExpansion = pocBreakoutUp
bool bearishPocExpansion = pocBreakoutDown
 
alertcondition(zoneCreated, title = "Consolidation Created", message = "A qualified consolidation range was created.")
alertcondition(breakoutup, title = "Breakout Up", message = "Price closed above the active consolidation range; its POC is frozen.")
alertcondition(breakoutdown, title = "Breakout Down", message = "Price closed below the active consolidation range; its POC is frozen.")
alertcondition(liquidityStarted, title = "Range Liquidity Created", message = "A completed consolidation created high and low potential liquidity levels.")
alertcondition(liquidityTouchedAlert, title = "Liquidity Level Touched", message = "Price touched a completed range boundary without crossing it.")
alertcondition(liquiditySweptAlert, title = "Liquidity Swept", message = "Price crossed a completed range boundary and closed back at or inside it.")
alertcondition(liquidityBrokenAlert, title = "Liquidity Level Broken", message = "Price closed beyond a completed range boundary.")
alertcondition(pocTouchedAlert, title = "POC Touched", message = "Price revisited a completed range POC after the range ended.")
alertcondition(pocBullRetestAlert, title = "Bullish POC Retest", message = "Price retested a completed range POC from above and closed back above it.")
alertcondition(pocBearRetestAlert, title = "Bearish POC Retest", message = "Price retested a completed range POC from below and closed back below it.")
alertcondition(bullishPocExpansion, title = "Bullish POC Expansion", message = "Price closed above a consolidation range with a valid POC.")
alertcondition(bearishPocExpansion, title = "Bearish POC Expansion", message = "Price closed below a consolidation range with a valid POC.")

← 返回列表