本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("5D Opportunity Zones — POC, LVN & Anchored VWAPs", "5D Opp V38", overlay=true, max_boxes_count=120, max_lines_count=100, max_labels_count=100, max_bars_back=5000)
// Inputs
string G1 = "1. Profiles"
int rows = input.int(100, "Price rows per session", minval=24, maxval=120, group=G1)
int days = input.int(5, "Completed sessions", minval=1, maxval=5, group=G1)
int maxHVN = input.int(5, "Maximum HVN zones", minval=1, maxval=10, group=G1)
int maxLVN = input.int(6, "Maximum LVN zones", minval=0, maxval=10, group=G1)
float hvnFraction = input.float(0.55, "HVN threshold (fraction of peak)", minval=0.2, maxval=0.95, step=0.05, group=G1)
float lvnFraction = input.float(0.25, "LVN threshold (fraction of peak)", minval=0.05, maxval=0.60, step=0.05, group=G1)
bool includeToday = input.bool(true, "Include developing RTH profile", group=G1)
string G2 = "2. Display"
int extendBars = input.int(70, "Zone history (bars)", minval=5, maxval=400, group=G2)
int forwardBars = input.int(15, "Right extension (bars)", minval=1, maxval=80, group=G2)
bool showPoc = input.bool(true, "POC center lines", group=G2)
bool showLabels = input.bool(true, "Zone labels", group=G2)
bool showRefs = input.bool(true, "PDH / PDL", group=G2)
bool showPm = input.bool(true, "Premarket high / low", group=G2)
bool showTable = input.bool(true, "Opportunity table", group=G2)
int hvnOpacity = input.int(95, "HVN zone transparency", minval=70, maxval=98, group=G2)
int lvnOpacity = input.int(94, "LVN zone transparency", minval=70, maxval=98, group=G2)
int pdOpacity = input.int(89, "Previous-day HVN transparency", minval=65, maxval=95, group=G2)
string labelSizeInput = input.string("Small", "Zone label size", options=["Tiny", "Small", "Normal"], group=G2)
string targetLineInput = input.string("Dotted", "Target line style", options=["Solid", "Dotted", "Dashed"], group=G2)
int zoneLabelOffset = input.int(4, "Zone label offset right (bars)", minval=0, maxval=60, group=G2)
int pocExtraOffset = input.int(18, "Extra POC label offset (bars)", minval=4, maxval=70, group=G2)
int lvnExtraOffset = input.int(8, "Extra LVN / edge label offset (bars)", minval=0, maxval=40, group=G2)
int keyLabelOffset = input.int(1, "Key-level label offset (bars)", minval=0, maxval=20, group=G2)
string avLabelSizeInput = input.string("Small", "AVWAP label size", options=["Small", "Normal", "Large"], group=G2)
int pdBorderTransparency = input.int(83, "Previous-day zone border transparency", minval=35, maxval=100, group=G2)
int targetLabelOffset = input.int(14, "Target label offset (bars)", minval=2, maxval=60, group=G2)
bool showSourceDay = input.bool(true, "Show source day on HVNs", group=G2)
bool emphasizePD = input.bool(true, "Highlight previous-day POC", group=G2)
bool showPrices = input.bool(false, "Show POC price in labels", group=G2)
bool showVolumes = input.bool(true, "Show POC volume in labels", group=G2)
bool showStars = input.bool(true, "Show structure stars", group=G2)
bool showEdges = input.bool(true, "Show developing profile edges", group=G2)
int edgeRows = input.int(3, "Profile edge width (rows)", minval=1, maxval=6, group=G2)
int rowTicks = input.int(4, "Original POC ticks per row (match 5D POC)", minval=1, maxval=200, group=G1)
labelSize = labelSizeInput == "Normal" ? size.normal : labelSizeInput == "Small" ? size.small : size.tiny
avLabelSize = avLabelSizeInput == "Large" ? size.large : avLabelSizeInput == "Normal" ? size.normal : size.small
targetLineStyle = targetLineInput == "Solid" ? line.style_solid : targetLineInput == "Dotted" ? line.style_dotted : line.style_dashed
string G3 = "3. Confirmation"
int confirmBars = input.int(1, "Consecutive confirmed closes", minval=1, maxval=3, group=G3)
float breakBuffer = input.float(0.0, "Breakout buffer (price units)", minval=0, step=0.01, group=G3)
float avConfluence = input.float(0.25, "PD AVWAP confluence distance (SPY pts)", minval=0.01, maxval=2.0, step=0.05, group=G3)
string G4 = "4. Anchored VWAPs"
bool showDailyAV = input.bool(true, "Show PDH-VWAP / PDL-VWAP", group=G4)
bool showWeeklyAV = input.bool(true, "Show WH-VWAP / WL-VWAP", group=G4)
bool useAVTargets = input.bool(true, "Include AVWAPs in runway targets", group=G4)
// Publication-ready proximity and breakout alerts.
string G5 = "5. Alerts"
bool alertPdPoc = input.bool(true, "Previous-day POC approaching", group=G5)
bool alertDailyAv = input.bool(true, "Daily AVWAP approach alerts", group=G5)
bool alertWeeklyAv = input.bool(true, "Weekly AVWAP approach alerts", group=G5)
bool alertAnyAv = input.bool(false, "Combined: any AVWAP approaching", group=G5)
bool alertConfluence = input.bool(true, "POC + AVWAP structural confluence", group=G5)
bool alertPmBreak = input.bool(true, "Premarket breakout alerts", group=G5)
string proximityMode = input.string("ATR", "Approach distance mode", options=["ATR", "Percent", "Price"], group=G5)
float proximityAtr = input.float(0.15, "Approach distance: ATR multiple", minval=0.01, step=0.05, group=G5)
float proximityPercent = input.float(0.05, "Approach distance: percent", minval=0.001, step=0.01, group=G5)
float proximityPrice = input.float(0.25, "Approach distance: price units", minval=0.01, step=0.05, group=G5)
int proximityAtrLength = input.int(14, "ATR length", minval=1, group=G5)
int alertCooldown = input.int(5, "Minimum bars between repeat alerts", minval=0, maxval=100, group=G5)
int pmConfirmBars = input.int(1, "Premarket break: confirmed closes", minval=1, maxval=3, group=G5)
// Session definitions (US stocks, New York time)
string tz = "America/New_York"
bool inRth = not na(time(timeframe.period, "0930-1600:23456", tz))
bool newRth = inRth and not inRth[1]
bool inPm = not na(time(timeframe.period, "0400-0930:23456", tz))
bool newPm = inPm and not inPm[1]
// Same previous-RTH-extreme anchor accumulation as the verified AVWAP V3.
// Select extremes only 09:30-16:00 ET; continue PV accumulation overnight.
var float buildHi = na
var float buildLo = na
var float buildHiPV = na
var float buildLoPV = na
var float buildHiV = na
var float buildLoV = na
var float pdHiPV = na
var float pdLoPV = na
var float pdHiV = na
var float pdLoV = na
float sourceAV = hlc3
if newRth
pdHiPV := buildHiPV
pdLoPV := buildLoPV
pdHiV := buildHiV
pdLoV := buildLoV
buildHi := high
buildLo := low
buildHiPV := sourceAV * volume
buildLoPV := sourceAV * volume
buildHiV := volume
buildLoV := volume
else
if inRth and (na(buildHi) or high > buildHi)
buildHi := high
buildHiPV := sourceAV * volume
buildHiV := volume
else if not na(buildHiPV)
buildHiPV += sourceAV * volume
buildHiV += volume
if inRth and (na(buildLo) or low < buildLo)
buildLo := low
buildLoPV := sourceAV * volume
buildLoV := volume
else if not na(buildLoPV)
buildLoPV += sourceAV * volume
buildLoV += volume
if not na(pdHiPV)
pdHiPV += sourceAV * volume
pdHiV += volume
if not na(pdLoPV)
pdLoPV += sourceAV * volume
pdLoV += volume
float pdhAV = not na(pdHiV) and pdHiV > 0 ? pdHiPV / pdHiV : na
float pdlAV = not na(pdLoV) and pdLoV > 0 ? pdLoPV / pdLoV : na
// Weekly extreme AVWAPs: select new high/low anchors during RTH only.
// Accumulate volume after each anchor, including extended hours when available.
bool newWeek = timeframe.change("W")
var float weekHi = na
var float weekLo = na
var float whPV = na
var float whVol = na
var float wlPV = na
var float wlVol = na
if newWeek
weekHi := na
weekLo := na
whPV := na
whVol := na
wlPV := na
wlVol := na
if inRth and (na(weekHi) or high > weekHi)
weekHi := high
whPV := sourceAV * volume
whVol := volume
else if not na(whPV)
whPV += sourceAV * volume
whVol += volume
if inRth and (na(weekLo) or low < weekLo)
weekLo := low
wlPV := sourceAV * volume
wlVol := volume
else if not na(wlPV)
wlPV += sourceAV * volume
wlVol += volume
float whAV = not na(whVol) and whVol > 0 ? whPV / whVol : na
float wlAV = not na(wlVol) and wlVol > 0 ? wlPV / wlVol : na
// Plot the full bar-by-bar AVWAP history, not a flat line at the latest value.
// This makes the anchored curves visible across the chart and lets them evolve
// as price/volume change. The right-edge labels are drawn separately below.
plot(showDailyAV ? pdhAV : na, title="PDH-VWAP (Previous Day High AVWAP)", color=color.new(color.red, 0), linewidth=2, style=plot.style_linebr)
plot(showDailyAV ? pdlAV : na, title="PDL-VWAP (Previous Day Low AVWAP)", color=color.new(color.lime, 0), linewidth=2, style=plot.style_linebr)
plot(showWeeklyAV ? whAV : na, title="WH-VWAP (Weekly High AVWAP)", color=color.rgb(176, 90, 158), linewidth=2, style=plot.style_linebr)
plot(showWeeklyAV ? wlAV : na, title="WL-VWAP (Weekly Low AVWAP)", color=color.rgb(67, 140, 168), linewidth=2, style=plot.style_linebr)
// Intraday-only indicator. Store each session as a fixed number of price/volume samples.
// Rebuild completed profiles from samples once at each new RTH session.
var array<float> dayLows = array.new_float()
var array<float> dayHighs = array.new_float()
var array<float> dayVols = array.new_float()
var array<int> dayEnds = array.new_int()
var array<int> dayDates = array.new_int()
var float runHigh = na
var float runLow = na
var float prevHigh = na
var float prevLow = na
var float pmHigh = na
var float pmLow = na
if newPm
pmHigh := high
pmLow := low
else if inPm
pmHigh := math.max(nz(pmHigh, high), high)
pmLow := math.min(nz(pmLow, low), low)
if newRth
prevHigh := runHigh
prevLow := runLow
runHigh := high
runLow := low
array.push(dayEnds, array.size(dayLows))
array.push(dayDates, time)
if array.size(dayEnds) > 6
int removeN = array.shift(dayEnds)
array.shift(dayDates)
// Compact stored samples and shift session boundaries.
if removeN > 0
for z = 0 to removeN - 1
array.shift(dayLows)
array.shift(dayHighs)
array.shift(dayVols)
for z = 0 to array.size(dayEnds) - 1
array.set(dayEnds, z, array.get(dayEnds, z) - removeN)
if inRth
runHigh := math.max(nz(runHigh, high), high)
runLow := math.min(nz(runLow, low), low)
array.push(dayLows, low)
array.push(dayHighs, high)
array.push(dayVols, volume)
// Profile builders. Bin candle volume proportionally by overlap with each price row.
f_profile(int startAt, int endAt, int nRows) =>
array<float> bins = array.new_float(nRows, 0.0)
float lo = na
float hi = na
if endAt > startAt
for i = startAt to endAt - 1
lo := math.min(nz(lo, array.get(dayLows, i)), array.get(dayLows, i))
hi := math.max(nz(hi, array.get(dayHighs, i)), array.get(dayHighs, i))
float step = (hi - lo) / nRows
if step > 0
for i = startAt to endAt - 1
float l = array.get(dayLows, i)
float h = array.get(dayHighs, i)
float v = array.get(dayVols, i)
int first = math.max(0, math.min(nRows - 1, int(math.floor((l - lo) / step))))
int last = math.max(0, math.min(nRows - 1, int(math.floor((h - lo) / step))))
if h > l and v > 0
for j = first to last
float bottom = lo + j * step
float overlap = math.max(0.0, math.min(h, bottom + step) - math.max(l, bottom))
array.set(bins, j, array.get(bins, j) + v * overlap / (h - l))
else if v > 0
array.set(bins, first, array.get(bins, first) + v)
[bins, lo, hi]
// Exact fixed-tick row assignment from original 5 Days of POC v2:
// equal volume per intersected row, with price bins fixed to mintick*rowTicks.
f_exactPoc(int startAt, int endAt) =>
array<int> keys = array.new_int()
array<float> vols = array.new_float()
if endAt > startAt
for i = startAt to endAt - 1
float loBar = array.get(dayLows, i)
float hiBar = array.get(dayHighs, i)
float vv = array.get(dayVols, i)
if vv > 0
int k1 = int(math.floor((loBar / syminfo.mintick) / rowTicks))
int k2 = int(math.floor((hiBar / syminfo.mintick) / rowTicks))
int count = math.max(1, k2 - k1 + 1)
for k = k1 to k2
int at = array.indexof(keys, k)
if at < 0
array.push(keys, k)
array.push(vols, vv / count)
else
array.set(vols, at, array.get(vols, at) + vv / count)
float price = na
float peak = na
if array.size(keys) > 0
int best = array.indexof(vols, array.max(vols))
price := (array.get(keys, best) * rowTicks + rowTicks * 0.5) * syminfo.mintick
peak := array.get(vols, best)
[price, peak]
// Previous completed RTH POC, calculated once at the new session boundary.
// Unlike the drawing-only profile, this series exists on historical bars too.
var float alertPrevPoc = na
if newRth
int countEnds = array.size(dayEnds)
if countEnds >= 2
int priorStart = array.get(dayEnds, countEnds - 2)
int priorEnd = array.get(dayEnds, countEnds - 1)
[pocAtOpen, volAtOpen] = f_exactPoc(priorStart, priorEnd)
alertPrevPoc := pocAtOpen
else
alertPrevPoc := na
// Candidate zones are stored as [bottom, top, center, volume, kind] arrays.
// kind=1 HVN; kind=-1 LVN. An HVN is a contiguous run of bins above threshold.
var array<float> zBot = array.new_float()
var array<float> zTop = array.new_float()
var array<float> zMid = array.new_float()
var array<float> zVol = array.new_float()
var array<int> zKind = array.new_int()
var array<int> zSource = array.new_int()
var array<int> zDate = array.new_int()
f_dayTag(int t) =>
na(t) ? "?" : dayofweek(t, tz) == dayofweek.monday ? "Mon" : dayofweek(t, tz) == dayofweek.tuesday ? "Tue" : dayofweek(t, tz) == dayofweek.wednesday ? "Wed" : dayofweek(t, tz) == dayofweek.thursday ? "Thu" : dayofweek(t, tz) == dayofweek.friday ? "Fri" : "Day"
f_addCandidates(array<float> bins, float lo, float hi, int nRows, int sourceAge, int sourceDate) =>
float step = (hi - lo) / nRows
if step > 0
float peak = array.max(bins)
if peak > 0
int pocIdx = array.indexof(bins, peak)
// HVNs: contiguous elevated-volume bins; POC is strongest bin inside cluster.
bool inside = false
int first = 0
for j = 0 to nRows
bool hot = j < nRows ? array.get(bins, j) >= peak * hvnFraction : false
if hot and not inside
first := j
inside := true
if not hot and inside
int last = j - 1
float best = -1.0
int bestI = first
float total = 0.0
for k = first to last
float vv = array.get(bins, k)
total += vv
if vv > best
best := vv
bestI := k
array.push(zBot, lo + first * step)
array.push(zTop, lo + (last + 1) * step)
array.push(zMid, lo + (bestI + 0.5) * step)
array.push(zVol, total)
array.push(zKind, 1)
array.push(zSource, sourceAge)
array.push(zDate, sourceDate)
inside := false
// Original LVN Profile's neighborhood-valley idea: a bin must be
// below all neighbors in a 7%-of-rows window, but not near-zero noise.
int radius = math.max(1, int(nRows * 0.07))
if nRows >= 3
for j = 1 to nRows - 2
float v = array.get(bins, j)
bool valley = v > peak * 0.01 and v < peak * lvnFraction
if valley
for k = 1 to radius
if j - k >= 0 and v >= array.get(bins, j - k)
valley := false
if j + k < nRows and v >= array.get(bins, j + k)
valley := false
if valley
array.push(zBot, lo + j * step)
array.push(zTop, lo + (j + 1) * step)
array.push(zMid, lo + (j + 0.5) * step)
array.push(zVol, v)
array.push(zKind, -1)
array.push(zSource, sourceAge)
array.push(zDate, sourceDate)
var array<float> pPrices = array.new_float()
var array<float> pVolumes = array.new_float()
var array<int> pAges = array.new_int()
var array<int> pDates = array.new_int()
// Reusable drawings
var array<box> drawnBoxes = array.new<box>()
var array<line> drawnLines = array.new<line>()
var array<label> drawnLabels = array.new<label>()
var table dashboard = table.new(position.top_right, 2, 4, border_width=1)
var float target = na
var float runway = na
var int direction = 0
var string marketState = "WAIT"
var bool bullSignal = false
var bool bearSignal = false
// Draw/update on the final chart bar. Historical session samples are retained.
if barstate.islast
for b in drawnBoxes
box.delete(b)
for l in drawnLines
line.delete(l)
for lab in drawnLabels
label.delete(lab)
array.clear(drawnBoxes)
array.clear(drawnLines)
array.clear(drawnLabels)
array.clear(zBot)
array.clear(zTop)
array.clear(zMid)
array.clear(zVol)
array.clear(zKind)
array.clear(zSource)
array.clear(zDate)
array.clear(pPrices)
array.clear(pVolumes)
array.clear(pAges)
array.clear(pDates)
int totalSamples = array.size(dayLows)
int boundaryCount = array.size(dayEnds)
// dayEnds stores each RTH opening sample index. The last entry is today's start.
// Previous day = interval [last-1, last), not [last-2, last-1).
int completedCount = math.max(0, boundaryCount - 1)
int useCount = math.min(days, completedCount)
if useCount > 0
for d = 0 to useCount - 1
int startIndex = array.get(dayEnds, boundaryCount - 2 - d)
int endIndex = array.get(dayEnds, boundaryCount - 1 - d)
int sourceDate = array.get(dayDates, boundaryCount - 2 - d)
[bins, lo, hi] = f_profile(startIndex, endIndex, rows)
f_addCandidates(bins, lo, hi, rows, d + 1, sourceDate)
[pp, pv] = f_exactPoc(startIndex, endIndex)
if not na(pp)
array.push(pPrices, pp)
array.push(pVolumes, pv)
array.push(pAges, d + 1)
array.push(pDates, sourceDate)
if includeToday and boundaryCount > 0 and totalSamples > array.get(dayEnds, boundaryCount - 1)
int startToday = array.get(dayEnds, boundaryCount - 1)
[binsToday, loToday, hiToday] = f_profile(startToday, totalSamples, rows)
f_addCandidates(binsToday, loToday, hiToday, rows, 0, array.get(dayDates, boundaryCount - 1))
[todayPP, todayPV] = f_exactPoc(startToday, totalSamples)
if not na(todayPP)
array.push(pPrices, todayPP)
array.push(pVolumes, todayPV)
array.push(pAges, 0)
array.push(pDates, array.get(dayDates, boundaryCount - 1))
// Pick highest-volume HVNs, then nearest LVNs, with duplicate-zone suppression.
array<int> chosen = array.new_int()
int totalZones = array.size(zBot)
float strongest = 0.0
if totalZones > 0
for i = 0 to totalZones - 1
if array.get(zKind, i) == 1
strongest := math.max(strongest, array.get(zVol, i))
for pass = 0 to 1
int quota = pass == 0 ? maxHVN : maxLVN
for rank = 0 to quota - 1
int bestIndex = -1
float bestScore = -1e30
for i = 0 to totalZones - 1
int kind = array.get(zKind, i)
if (pass == 0 ? kind == 1 : kind == -1) and not array.includes(chosen, i)
float mid = array.get(zMid, i)
float score = pass == 0 ? array.get(zVol, i) * (emphasizePD and array.get(zSource, i) == 1 ? 1.5 : 1.0) : -math.abs(mid - close)
bool duplicate = false
for chosenIndex in chosen
if array.get(zKind, chosenIndex) == kind
float overlap = math.min(array.get(zTop, i), array.get(zTop, chosenIndex)) - math.max(array.get(zBot, i), array.get(zBot, chosenIndex))
if overlap > 0
duplicate := true
if not duplicate and score > bestScore
bestScore := score
bestIndex := i
if bestIndex >= 0
array.push(chosen, bestIndex)
int x1 = math.max(0, bar_index - extendBars)
int x2 = bar_index + forwardBars
int xZoneLabel = x2 + zoneLabelOffset
int xPocLabel = xZoneLabel + pocExtraOffset
int xLvnLabel = xZoneLabel + lvnExtraOffset
int xKeyLabel = x2 + keyLabelOffset
int xAVLabel = xKeyLabel + 5
for i in chosen
float bot = array.get(zBot, i)
float top = array.get(zTop, i)
float mid = array.get(zMid, i)
float vol = array.get(zVol, i)
bool hvn = array.get(zKind, i) == 1
bool above = close > top
bool below = close < bot
bool isPD = hvn and array.get(zSource, i) == 1
color base = hvn ? (above ? color.lime : below ? color.red : color.yellow) : color.orange
int transparency = hvn ? (isPD and emphasizePD ? pdOpacity : math.max(75, hvnOpacity - int(math.round(4.0 * vol / math.max(strongest, 1))))) : lvnOpacity
color borderColor = isPD and emphasizePD ? color.new(color.aqua, pdBorderTransparency) : color.new(base, 92)
array.push(drawnBoxes, box.new(x1, top, x2, bot, border_color=borderColor, border_width=1, bgcolor=color.new(base, transparency)))
if not hvn and showLabels
array.push(drawnLabels, label.new(xLvnLabel, mid, "LVN", style=label.style_label_left, textcolor=color.orange, color=color.new(color.black, 90), size=labelSize))
// Original POC lines and rank-first labels, separate from adaptive HVN bands.
// Rank is strictly by original POC row volume; today developing is unranked.
int pc = array.size(pPrices)
if pc > 0
array<int> ranked = array.new_int()
for rank = 0 to pc - 1
int best = -1
float bestVol = -1.0
for j = 0 to pc - 1
if not array.includes(ranked, j) and array.get(pAges, j) > 0 and array.get(pVolumes, j) > bestVol
best := j
bestVol := array.get(pVolumes, j)
if best >= 0
array.push(ranked, best)
for j = 0 to pc - 1
float price = array.get(pPrices, j)
float pv = array.get(pVolumes, j)
int age = array.get(pAges, j)
bool pd = age == 1
int rank = array.indexof(ranked, j) + 1
// 5-star structure score: volume, recency, distinct POC convergence,
// and V3 previous-day high/low AVWAP proximity. Heuristic, not probability.
float volRatio = pv / math.max(array.max(pVolumes), 1.0)
float score = 1.0 + volRatio * 1.2 + (age == 0 ? 0.5 : (6.0 - age) / 5.0)
int matches = 0
for k = 0 to pc - 1
if k != j and math.abs(price - array.get(pPrices, k)) <= 0.35
matches += 1
score += math.min(1.0, matches * 0.5)
bool nearAV = (not na(pdhAV) and math.abs(price - pdhAV) <= avConfluence) or (not na(pdlAV) and math.abs(price - pdlAV) <= avConfluence) or (not na(whAV) and math.abs(price - whAV) <= avConfluence) or (not na(wlAV) and math.abs(price - wlAV) <= avConfluence)
if nearAV
score += 1.0
int stars = math.max(1, math.min(5, int(math.round(score))))
string starText = ""
if showStars
for st = 1 to stars
starText += "★"
color pcColor = pd and emphasizePD ? color.aqua : close > price ? color.lime : color.red
if showPoc
array.push(drawnLines, line.new(x1, price, x2, price, color=color.new(pcColor, pd ? 5 : 30), width=pd ? 3 : 1))
if showLabels
string name = age == 0 ? "TODAY POC" : "#" + str.tostring(rank) + " " + (pd ? "PD" : f_dayTag(array.get(pDates, j))) + " POC"
string info = (showPrices ? " " + str.tostring(price, format.mintick) : "") + (showVolumes ? " · " + str.tostring(pv, format.volume) : "")
array.push(drawnLabels, label.new(xPocLabel, price, name + (showStars ? " " + starText : "") + info, style=label.style_label_left, textcolor=pcColor, color=color.new(color.black, 85), size=pd ? size.normal : labelSize))
// Original LVN Profile edge idea: three rows inward from developing profile extremes.
// These are PROFILE EDGES, not true low-volume valleys.
if showEdges and includeToday and boundaryCount > 0 and totalSamples > array.get(dayEnds, boundaryCount - 1)
[edgeBins, edgeLo, edgeHi] = f_profile(array.get(dayEnds, boundaryCount - 1), totalSamples, rows)
float edgeStep = (edgeHi - edgeLo) / rows
if edgeStep > 0
float upperBot = edgeHi - edgeStep * edgeRows
float lowerTop = edgeLo + edgeStep * edgeRows
array.push(drawnBoxes, box.new(x1, edgeHi, x2, upperBot, bgcolor=color.new(color.red, 94), border_color=color.new(color.red, 75)))
array.push(drawnBoxes, box.new(x1, lowerTop, x2, edgeLo, bgcolor=color.new(color.lime, 94), border_color=color.new(color.lime, 75)))
if showLabels
array.push(drawnLabels, label.new(xLvnLabel, (upperBot + edgeHi) / 2, "EDGE HIGH", style=label.style_label_left, textcolor=color.red, color=color.new(color.black, 90), size=labelSize))
array.push(drawnLabels, label.new(xLvnLabel, (lowerTop + edgeLo) / 2, "EDGE LOW", style=label.style_label_left, textcolor=color.lime, color=color.new(color.black, 90), size=labelSize))
if showRefs
if not na(prevHigh)
array.push(drawnLines, line.new(x1, prevHigh, x2, prevHigh, color=color.new(color.red, 25), width=1))
if showLabels
array.push(drawnLabels, label.new(xKeyLabel, prevHigh, "PDH", style=label.style_label_left, textcolor=color.red, color=color.new(color.black, 85), size=size.small))
if not na(prevLow)
array.push(drawnLines, line.new(x1, prevLow, x2, prevLow, color=color.new(color.lime, 25), width=1))
if showLabels
array.push(drawnLabels, label.new(xKeyLabel, prevLow, "PDL", style=label.style_label_left, textcolor=color.lime, color=color.new(color.black, 85), size=size.small))
if showPm
if not na(pmHigh)
array.push(drawnLines, line.new(x1, pmHigh, x2, pmHigh, color=color.yellow, width=1))
if showLabels
array.push(drawnLabels, label.new(xKeyLabel, pmHigh, "PMH", style=label.style_label_left, textcolor=color.yellow, color=color.new(color.black, 85), size=size.small))
if not na(pmLow)
array.push(drawnLines, line.new(x1, pmLow, x2, pmLow, color=color.yellow, width=1))
if showLabels
array.push(drawnLabels, label.new(xKeyLabel, pmLow, "PML", style=label.style_label_left, textcolor=color.yellow, color=color.new(color.black, 85), size=size.small))
// AVWAP curve extensions and labels; daily red/green, weekly magenta/blue.
if showDailyAV
if not na(pdhAV)
// Extend the live AVWAP curve to the same right edge as the zones.
array.push(drawnLines, line.new(bar_index, pdhAV, x2, pdhAV, color=color.red, width=2))
if showLabels
array.push(drawnLabels, label.new(xAVLabel, pdhAV, "PDH-VWAP", style=label.style_label_left, textcolor=color.red, color=color.new(color.black, 45), size=avLabelSize))
if not na(pdlAV)
// Extend the live AVWAP curve to the same right edge as the zones.
array.push(drawnLines, line.new(bar_index, pdlAV, x2, pdlAV, color=color.lime, width=2))
if showLabels
array.push(drawnLabels, label.new(xAVLabel + (not na(pdhAV) and math.abs(pdlAV - pdhAV) <= syminfo.mintick * 20 ? 8 : 0), pdlAV, "PDL-VWAP", style=label.style_label_left, textcolor=color.lime, color=color.new(color.black, 45), size=avLabelSize))
if showWeeklyAV
if not na(whAV)
// Extend the live AVWAP curve to the same right edge as the zones.
array.push(drawnLines, line.new(bar_index, whAV, x2, whAV, color=color.rgb(176, 90, 158), width=2))
if showLabels
array.push(drawnLabels, label.new(xAVLabel + ((not na(pdhAV) and math.abs(whAV - pdhAV) <= syminfo.mintick * 20) or (not na(pdlAV) and math.abs(whAV - pdlAV) <= syminfo.mintick * 20) ? 14 : 0), whAV, "WH-VWAP", style=label.style_label_left, textcolor=color.rgb(176, 90, 158), color=color.new(color.black, 45), size=avLabelSize))
if not na(wlAV)
// Extend the live AVWAP curve to the same right edge as the zones.
array.push(drawnLines, line.new(bar_index, wlAV, x2, wlAV, color=color.rgb(67, 140, 168), width=2))
if showLabels
array.push(drawnLabels, label.new(xAVLabel + ((not na(pdlAV) and math.abs(wlAV - pdlAV) <= syminfo.mintick * 20) or (not na(whAV) and math.abs(wlAV - whAV) <= syminfo.mintick * 20) ? 20 : 0), wlAV, "WL-VWAP", style=label.style_label_left, textcolor=color.rgb(67, 140, 168), color=color.new(color.black, 45), size=avLabelSize))
// Detect whether the current price is inside a displayed HVN.
bool balanced = false
float nearestAbove = na
float nearestBelow = na
for i in chosen
float bot = array.get(zBot, i)
float top = array.get(zTop, i)
if array.get(zKind, i) == 1 and close >= bot and close <= top
balanced := true
if bot > close + breakBuffer
nearestAbove := na(nearestAbove) ? bot : math.min(nearestAbove, bot)
if top < close - breakBuffer
nearestBelow := na(nearestBelow) ? top : math.max(nearestBelow, top)
// Include session extremes as possible nearer obstacles.
if showRefs
if not na(prevHigh) and prevHigh > close + breakBuffer
nearestAbove := na(nearestAbove) ? prevHigh : math.min(nearestAbove, prevHigh)
if not na(prevLow) and prevLow < close - breakBuffer
nearestBelow := na(nearestBelow) ? prevLow : math.max(nearestBelow, prevLow)
if showPm
if not na(pmHigh) and pmHigh > close + breakBuffer
nearestAbove := na(nearestAbove) ? pmHigh : math.min(nearestAbove, pmHigh)
if not na(pmLow) and pmLow < close - breakBuffer
nearestBelow := na(nearestBelow) ? pmLow : math.max(nearestBelow, pmLow)
// AVWAP obstacles are independent of their chart visibility toggles.
if useAVTargets
array<float> avTargets = array.from(pdhAV, pdlAV, whAV, wlAV)
for av in avTargets
if not na(av)
if av > close + breakBuffer
nearestAbove := na(nearestAbove) ? av : math.min(nearestAbove, av)
if av < close - breakBuffer
nearestBelow := na(nearestBelow) ? av : math.max(nearestBelow, av)
// No stale trend assumption: a directional state requires a fresh confirmed
// boundary cross in the last N closed candles. Otherwise BALANCE/WAIT.
bool bullConfirmed = false
bool bearConfirmed = false
if barstate.isconfirmed and not balanced
for i in chosen
if array.get(zKind, i) == 1
float top = array.get(zTop, i)
float bot = array.get(zBot, i)
bool up = close > top + breakBuffer and close[confirmBars] <= top + breakBuffer
bool dn = close < bot - breakBuffer and close[confirmBars] >= bot - breakBuffer
for k = 0 to confirmBars - 1
up := up and close[k] > top + breakBuffer
dn := dn and close[k] < bot - breakBuffer
bullConfirmed := bullConfirmed or up
bearConfirmed := bearConfirmed or dn
direction := bullConfirmed and not bearConfirmed ? 1 : bearConfirmed and not bullConfirmed ? -1 : 0
target := direction == 1 ? nearestAbove : direction == -1 ? nearestBelow : na
runway := na(target) ? na : math.abs(target - close)
marketState := balanced ? "BALANCE" : direction == 1 ? "BULL BREAK" : direction == -1 ? "BEAR BREAK" : "WAIT"
bullSignal := direction == 1 and not na(target)
bearSignal := direction == -1 and not na(target)
if not na(target)
color tc = direction == 1 ? color.lime : color.red
array.push(drawnLines, line.new(bar_index, target, x2 + targetLabelOffset, target, color=color.new(tc, 15), style=targetLineStyle, width=1))
array.push(drawnLabels, label.new(xZoneLabel + targetLabelOffset, target, "TARGET " + str.tostring(target, format.mintick), style=label.style_label_left, textcolor=tc, color=color.new(color.black, 15), size=labelSize))
if showTable
table.cell(dashboard, 0, 0, "5D OPPORTUNITY", bgcolor=color.new(color.gray, 75), text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 0, marketState, bgcolor=color.new(direction == 1 ? color.green : direction == -1 ? color.red : color.gray, 65), text_color=color.white, text_size=size.small)
table.cell(dashboard, 0, 1, "TARGET", text_color=color.white, text_size=size.small)
table.cell(dashboard, 1, 1, na(target) ? "—" : str.tostring(target, format.mintick), text_color=color.white, text_size=size.small)
table.cell(dashboard, 0, 2, "", text_color=color.white)
table.cell(dashboard, 1, 2, "", text_color=color.white)
table.cell(dashboard, 0, 3, "", text_color=color.white)
table.cell(dashboard, 1, 3, "", text_color=color.white)
else
table.clear(dashboard, 0, 0, 1, 3)
// ALERT ENGINE: evaluate on every bar, independent of barstate.islast drawings.
// A proximity alert triggers upon entering the approach band, not on every bar inside it.
float alertAtr = ta.atr(proximityAtrLength)
float alertDistance = proximityMode == "ATR" ? alertAtr * proximityAtr : proximityMode == "Percent" ? close * proximityPercent / 100.0 : proximityPrice
alertDistance := math.max(nz(alertDistance, proximityPrice), syminfo.mintick)
f_near(float level, float distance) =>
not na(level) and math.abs(close - level) <= distance
f_approach(float level, float distance) =>
bool nowNear = f_near(level, distance)
bool beforeNear = not na(level[1]) and math.abs(close[1] - level[1]) <= distance[1]
nowNear and not beforeNear
// Separate cooldowns so one AVWAP alert cannot suppress another.
var int lastPdPoc = na
var int lastPdhAv = na
var int lastPdlAv = na
var int lastWhAv = na
var int lastWlAv = na
var int lastAnyAv = na
var int lastConfluence = na
bool validRthAlert = inRth and barstate.isconfirmed
bool pocApproach = validRthAlert and alertPdPoc and f_approach(alertPrevPoc, alertDistance)
bool pdhApproach = validRthAlert and alertDailyAv and f_approach(pdhAV, alertDistance)
bool pdlApproach = validRthAlert and alertDailyAv and f_approach(pdlAV, alertDistance)
bool whApproach = validRthAlert and alertWeeklyAv and f_approach(whAV, alertDistance)
bool wlApproach = validRthAlert and alertWeeklyAv and f_approach(wlAV, alertDistance)
pocApproach := pocApproach and (na(lastPdPoc) or bar_index - lastPdPoc > alertCooldown)
pdhApproach := pdhApproach and (na(lastPdhAv) or bar_index - lastPdhAv > alertCooldown)
pdlApproach := pdlApproach and (na(lastPdlAv) or bar_index - lastPdlAv > alertCooldown)
whApproach := whApproach and (na(lastWhAv) or bar_index - lastWhAv > alertCooldown)
wlApproach := wlApproach and (na(lastWlAv) or bar_index - lastWlAv > alertCooldown)
if pocApproach
lastPdPoc := bar_index
if pdhApproach
lastPdhAv := bar_index
if pdlApproach
lastPdlAv := bar_index
if whApproach
lastWhAv := bar_index
if wlApproach
lastWlAv := bar_index
bool anyAvNear = f_near(pdhAV, alertDistance) or f_near(pdlAV, alertDistance) or f_near(whAV, alertDistance) or f_near(wlAV, alertDistance)
bool anyAvWasNear = (not na(pdhAV[1]) and math.abs(close[1] - pdhAV[1]) <= alertDistance[1]) or (not na(pdlAV[1]) and math.abs(close[1] - pdlAV[1]) <= alertDistance[1]) or (not na(whAV[1]) and math.abs(close[1] - whAV[1]) <= alertDistance[1]) or (not na(wlAV[1]) and math.abs(close[1] - wlAV[1]) <= alertDistance[1])
bool anyAvApproach = validRthAlert and alertAnyAv and anyAvNear and not anyAvWasNear and (na(lastAnyAv) or bar_index - lastAnyAv > alertCooldown)
if anyAvApproach
lastAnyAv := bar_index
// Confluence requires the PD POC and an AVWAP to overlap within the approach distance,
// AND price to enter the same neighborhood. No directional claim is made.
bool avNearPoc = (not na(pdhAV) and math.abs(alertPrevPoc - pdhAV) <= alertDistance) or (not na(pdlAV) and math.abs(alertPrevPoc - pdlAV) <= alertDistance) or (not na(whAV) and math.abs(alertPrevPoc - whAV) <= alertDistance) or (not na(wlAV) and math.abs(alertPrevPoc - wlAV) <= alertDistance)
bool confluentNow = not na(alertPrevPoc) and avNearPoc and f_near(alertPrevPoc, alertDistance) and anyAvNear
bool confluenceApproach = validRthAlert and alertConfluence and confluentNow and not confluentNow[1] and (na(lastConfluence) or bar_index - lastConfluence > alertCooldown)
if confluenceApproach
lastConfluence := bar_index
// Premarket range is established before RTH; require a genuine transition across
// the frozen level, with the requested number of confirmed closes beyond it.
bool pmAvailable = not na(pmHigh) and not na(pmLow) and pmHigh > pmLow
bool pmUp = validRthAlert and alertPmBreak and pmAvailable and close > pmHigh + breakBuffer and close[pmConfirmBars] <= pmHigh + breakBuffer
bool pmDown = validRthAlert and alertPmBreak and pmAvailable and close < pmLow - breakBuffer and close[pmConfirmBars] >= pmLow - breakBuffer
for k = 0 to pmConfirmBars - 1
pmUp := pmUp and close[k] > pmHigh + breakBuffer
pmDown := pmDown and close[k] < pmLow - breakBuffer
alertcondition(pocApproach, "PD POC Approaching", "5D Opportunity Zones: price approaching previous-day POC on {{ticker}} at {{close}}")
alertcondition(pdhApproach, "PDH-VWAP Approaching", "5D Opportunity Zones: approaching previous-day HIGH AVWAP on {{ticker}} at {{close}}")
alertcondition(pdlApproach, "PDL-VWAP Approaching", "5D Opportunity Zones: approaching previous-day LOW AVWAP on {{ticker}} at {{close}}")
alertcondition(whApproach, "WH-VWAP Approaching", "5D Opportunity Zones: approaching WEEKLY HIGH AVWAP on {{ticker}} at {{close}}")
alertcondition(wlApproach, "WL-VWAP Approaching", "5D Opportunity Zones: approaching WEEKLY LOW AVWAP on {{ticker}} at {{close}}")
alertcondition(anyAvApproach, "Any AVWAP Approaching", "5D Opportunity Zones: approaching at least one AVWAP on {{ticker}} at {{close}}")
alertcondition(confluenceApproach, "STRUCTURAL CONFLUENCE", "5D Opportunity Zones: previous-day POC and an AVWAP overlap near price on {{ticker}} at {{close}}")
alertcondition(pmUp, "Premarket HIGH Break", "5D Opportunity Zones: confirmed premarket HIGH breakout on {{ticker}} at {{close}}")
alertcondition(pmDown, "Premarket LOW Break", "5D Opportunity Zones: confirmed premarket LOW breakdown on {{ticker}} at {{close}}")
alertcondition(pmUp or pmDown, "Either Premarket Break", "5D Opportunity Zones: confirmed premarket HIGH or LOW break on {{ticker}} at {{close}}")
// Alerts are evaluated on bar closes; the status engine above updates on the last chart bar.
alertcondition(bullSignal and barstate.isconfirmed, "5D Bull Target", "5D Opportunity Zones: confirmed bullish context with an upside structural target")
alertcondition(bearSignal and barstate.isconfirmed, "5D Bear Target", "5D Opportunity Zones: confirmed bearish context with a downside structural target")