本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
// https://creativecommons.org/licenses/by-nc-sa/4.0/
// © BigBeluga
//@version=6
indicator("Session VWAP Profile & Candle Delta [BigBeluga]", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_polylines_count = 100, calc_bars_count = 2000, max_bars_back = 500)
// INPUTS ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――{
// Timeframe Settings
autoHTF = input.bool(true, "Use Auto Timeframe", tooltip = "Automatically selects an optimal Higher Timeframe (HTF) session duration targeting ~200 candles.", group = "Timeframe Settings")
manualHTF = input.timeframe("1D", "Manual Timeframe", active = not autoHTF, tooltip = "Manual Higher Timeframe session duration used when Auto Timeframe is disabled.", group = "Timeframe Settings")
// Profile & VWAP Core Settings
stdevMult = input.float(2.0, "Band Multiplier (StdDev)", minval = 0.1, step = 0.1, tooltip = "Multiplier for Standard Deviation bands around the central VWAP.", group = "Profile Settings")
autoBins = input.bool(true, "Auto Bins Resolution", tooltip = "Dynamically calculates bin counts based on ATR volatility.", group = "Profile Settings")
manualBins = input.int(50, "Manual Bins Count", minval = 10, maxval = 250, active = not autoBins, tooltip = "Fixed number of price bins when Auto Bins Resolution is disabled.", group = "Profile Settings")
maxSessions = input.int(3, "Max Sessions Displayed", minval = 1, maxval = 50, tooltip = "Maximum number of historical sessions retained on the chart before old drawings are removed.", group = "Profile Settings")
// Visuals & Offsets
rightOffset = input.int(35, "Real-Time Profile Offset (Bars)", minval = 5, maxval = 200, tooltip = "Horizontal offset (in bars) to shift the live active profile to the right edge of the chart.", group = "Visual Settings")
showLabels = input.bool(true, "Show Candle Count Labels", tooltip = "Displays bullish and bearish candle count distribution boxes on profile bins.", group = "Visual Settings")
showPoc = input.bool(true, "Show Point of Control (POC)", tooltip = "Draws the Point of Control (POC) level representing the bin with highest volume.", group = "Visual Settings")
showSignals = input.bool(true, "Show Outer Band Signals", tooltip = "Displays triangle signals when price crosses and closes back inside the outer standard deviation bands.", group = "Visual Settings")
// Palette Settings
upColor = input.color(color.blue, "Profile Up Color (Green)", tooltip = "Color gradient target for bullish volume density and rising VWAP.", group = "Palette Settings")
dnColor = input.color(color.red, "Profile Down Color (Purple)", tooltip = "Color gradient target for bearish volume density and falling VWAP.", group = "Palette Settings")
baseGray = input.color(#787b86, "Base Color", tooltip = "Base color for lower density volume bins and session band fill background.", group = "Palette Settings")
pocColor = input.color(color.red, "POC Line Color", tooltip = "Color used to draw the Point of Control (POC) dashed/solid line.", group = "Palette Settings")
// }
// TYPES ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――{
// Consolidated Container for Session Profile Visual Objects
type SessionElements
polyline fillPoly
polyline vwapPoly
polyline upperPoly
polyline lowerPoly
line[] profileLines
box[] profileBoxes
line pocLine
// Helper to delete and clear all drawing objects in a SessionElements instance
deleteSessionElements(SessionElements inst) =>
if not na(inst)
if not na(inst.fillPoly)
polyline.delete(inst.fillPoly)
if not na(inst.vwapPoly)
polyline.delete(inst.vwapPoly)
if not na(inst.upperPoly)
polyline.delete(inst.upperPoly)
if not na(inst.lowerPoly)
polyline.delete(inst.lowerPoly)
if not na(inst.pocLine)
line.delete(inst.pocLine)
if not na(inst.profileLines)
for l in inst.profileLines
line.delete(l)
array.clear(inst.profileLines)
if not na(inst.profileBoxes)
for b in inst.profileBoxes
box.delete(b)
array.clear(inst.profileBoxes)
// }
// CALCULATIONS――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――{
// Auto Timeframe Engine (~200 Candles Target)
getAutoHTF() =>
string result = manualHTF
if autoHTF
if timeframe.isseconds
int s = timeframe.multiplier
result := s <= 5 ? '15' : s <= 15 ? '45' : '120'
else if timeframe.isintraday
int m = timeframe.multiplier
switch m
1 => result := '200'
2 => result := '360'
5 => result := '720'
15 => result := '2D'
30 => result := '4D'
60 => result := 'W'
120 => result := '2W'
=> result := m < 60 ? 'D' : m < 360 ? 'M' : '3M'
else if timeframe.isdaily
int d = timeframe.multiplier
result := d == 1 ? '7M' : d == 2 ? '12M' : '18M'
else if timeframe.isweekly
result := '48M'
else if timeframe.ismonthly
result := '240M'
result
tfInput = getAutoHTF()
tfChange = timeframe.change(tfInput)
atrVal = ta.atr(14)
// Persistent Data State
var float sumVol = 0.0
var float sumPV = 0.0
var float sumP2V = 0.0
var int startBar = 0
// Polyline Point Buffers
var chart.point[] vwapPoints = array.new<chart.point>(0)
var chart.point[] upperPoints = array.new<chart.point>(0)
var chart.point[] lowerPoints = array.new<chart.point>(0)
// Single Array storing active and historical SessionElements instances
var SessionElements[] sessionHistory = array.new<SessionElements>(0)
// Dynamic Garbage Collection based on maxSessions input
trimSessionHistory() =>
while array.size(sessionHistory) > maxSessions
SessionElements oldest = array.shift(sessionHistory)
deleteSessionElements(oldest)
// Dynamic Bins Resolution Calculator
calcBins(float uBand, float lBand, float currentAtr) =>
int numBins = manualBins
if autoBins and currentAtr > 0 and uBand > lBand
bandSpan = uBand - lBand
calculatedBins = math.round(bandSpan / (currentAtr * 0.5))
numBins := int(math.min(250, math.max(10, calculatedBins)))
numBins
// Bin volume distribution logic
distributeBinVolume(float[] binTotalVol, int[] binBullCount, int[] binBearCount, int binIndex, float v, bool isUp, int binCount) =>
if binIndex >= 0 and binIndex < binCount
array.set(binTotalVol, binIndex, array.get(binTotalVol, binIndex) + (v * 0.50))
if isUp
array.set(binBullCount, binIndex, array.get(binBullCount, binIndex) + 1)
else
array.set(binBearCount, binIndex, array.get(binBearCount, binIndex) + 1)
if binIndex - 1 >= 0
array.set(binTotalVol, binIndex - 1, array.get(binTotalVol, binIndex - 1) + (v * 0.25))
if binIndex + 1 < binCount
array.set(binTotalVol, binIndex + 1, array.get(binTotalVol, binIndex + 1) + (v * 0.25))
// Dynamic Gradient Selector using color.from_gradient() with Bin Volume Density
getBinColor(int binIdx, int totalBins, float currentBinVol, float maxBinVol, bool isVwapUp) =>
color selectedColor = baseGray
if maxBinVol > 0 and totalBins > 1
float volWeight = currentBinVol / maxBinVol
if isVwapUp
selectedColor := color.from_gradient(volWeight, 0.0, 1.0, baseGray, upColor)
else
selectedColor := color.from_gradient(volWeight, 0.0, 1.0, baseGray, dnColor)
selectedColor
// Constructs a closed polygon array wrapping upper and lower bands for fill rendering
createFillPolygon(chart.point[] uPts, chart.point[] lPts) =>
chart.point[] fillPts = array.new<chart.point>(0)
int sz = array.size(uPts)
if sz > 0
for i = 0 to sz - 1
array.push(fillPts, array.get(uPts, i))
for i = sz - 1 to 0
array.push(fillPts, array.get(lPts, i))
fillPts
// Rendering Engine for Historical Profiles
renderProfile(float uBand, float lBand, int sBar, int eBar, int binCount, bool isVwapUp, SessionElements sess) =>
int len = eBar - sBar
if uBand > lBand and len >= 0
binStep = (uBand - lBand) / binCount
binTotalVol = array.new_float(binCount, 0.0)
binBullCount = array.new_int(binCount, 0)
binBearCount = array.new_int(binCount, 0)
for i = 0 to len
p = close[i + 1]
v = volume[i + 1]
isUp = close[i + 1] >= open[i + 1]
if p >= lBand and p <= uBand
binIndex = math.min(binCount - 1, math.floor((p - lBand) / binStep))
distributeBinVolume(binTotalVol, binBullCount, binBearCount, binIndex, v, isUp, binCount)
maxBinVol = 0.0
pocBinIndex = 0
for b = 0 to binCount - 1
totV = array.get(binTotalVol, b)
if totV > maxBinVol
maxBinVol := totV
pocBinIndex := b
pocLeft = 0
if maxBinVol > 0
for b = 0 to binCount - 1
totV = array.get(binTotalVol, b)
bullCount = array.get(binBullCount, b)
bearCount = array.get(binBearCount, b)
if totV > 0
bLow = lBand + (b * binStep)
bHigh = bLow + binStep
bMid = (bLow + bHigh) / 2.0
barSpan = math.max(1, math.round((totV / maxBinVol) * 30))
leftBar = math.max(sBar, eBar - barSpan)
rightBar = eBar
if b == pocBinIndex
pocLeft := leftBar
binLineColor = getBinColor(b, binCount, totV, maxBinVol, isVwapUp)
pLine = line.new(
x1 = leftBar, y1 = bMid, x2 = rightBar, y2 = bMid, xloc = xloc.bar_index,
color = binLineColor,
style = line.style_dotted, width = 1
)
array.push(sess.profileLines, pLine)
if showLabels
bBox = box.new(
left = rightBar, top = bHigh, right = rightBar + 7, bottom = bLow,
xloc = xloc.bar_index,
bgcolor = color.new(color.black, 100),
border_color = color.new(color.black, 100),
text = "[+" + str.tostring(bullCount) + " | -" + str.tostring(bearCount) + "]",
text_size = size.auto,
text_color = color.rgb(153, 161, 189),
text_halign = text.align_left,
text_valign = text.align_center
)
array.push(sess.profileBoxes, bBox)
if showPoc
pocPrice = lBand + (pocBinIndex * binStep) + (binStep / 2.0)
sess.pocLine := line.new(x1 = pocLeft, y1 = pocPrice, x2 = sBar, y2 = pocPrice, xloc = xloc.bar_index, color = pocColor, style = line.style_dashed, width = 2)
// Accumulate Metrics
sumVol += volume
sumPV += close * volume
sumP2V += math.pow(close, 2) * volume
// Dynamic Calculations
vwapVal = sumPV / sumVol
variance = math.max(0.0, (sumP2V / sumVol) - math.pow(vwapVal, 2))
stdevVal = math.sqrt(variance)
upperBand = vwapVal + (stdevVal * stdevMult)
lowerBand = vwapVal - (stdevVal * stdevMult)
// Fix unconfirmed bar logic on non-session reset bars
if not tfChange
upperBand := barstate.isconfirmed ? upperBand : upperBand[1]
lowerBand := barstate.isconfirmed ? lowerBand : lowerBand[1]
bool isVwapRising = vwapVal >= vwapVal[1]
// Store bar coordinates for polylines
if not tfChange
array.push(vwapPoints, chart.point.from_index(bar_index, vwapVal))
array.push(upperPoints, chart.point.from_index(bar_index, upperBand))
array.push(lowerPoints, chart.point.from_index(bar_index, lowerBand))
// Session Anchor Reset & Historical Polyline Drawing
if tfChange and bar_index > 0 and barstate.isconfirmed
prevVWAP = sumPV[1] / sumVol[1]
prevVar = math.max(0.0, (sumP2V[1] / sumVol[1]) - math.pow(prevVWAP, 2))
prevStdev = math.sqrt(prevVar)
prevUpper = prevVWAP + (prevStdev * stdevMult)
prevLower = prevVWAP - (prevStdev * stdevMult)
prevBins = calcBins(prevUpper, prevLower, atrVal[1])
// Instantiate new SessionElements container for completed historical session
SessionElements histSession = SessionElements.new(
fillPoly = na,
vwapPoly = na,
upperPoly = na,
lowerPoly = na,
profileLines = array.new_line(0),
profileBoxes = array.new_box(0),
pocLine = na
)
// Render historical volume profile for ended session
renderProfile(prevUpper, prevLower, startBar, bar_index - 1, prevBins, isVwapRising, histSession)
// Render completed session polylines and closed band fill polygon
if array.size(vwapPoints) > 1
chart.point[] fillPts = createFillPolygon(upperPoints, lowerPoints)
histSession.fillPoly := polyline.new(fillPts, line_color = color.new(color.white, 100), fill_color = color.new(baseGray, 95))
histSession.vwapPoly := polyline.new(vwapPoints, line_color = isVwapRising ? upColor : dnColor, line_width = 2)
histSession.upperPoly := polyline.new(upperPoints, line_color = color.gray, line_width = 1)
histSession.lowerPoly := polyline.new(lowerPoints, line_color = color.gray, line_width = 1)
// Push into session history array and enforce limits
array.push(sessionHistory, histSession)
trimSessionHistory()
// Reset tracking structures for new session
array.clear(vwapPoints)
array.clear(upperPoints)
array.clear(lowerPoints)
// Reset metric variables
sumVol := volume
sumPV := close * volume
sumP2V := math.pow(close, 2) * volume
startBar := bar_index
// Recalculate clean initial VWAP and Band values for bar 0 of the new session
vwapVal := sumPV / sumVol
upperBand := vwapVal
lowerBand := vwapVal
array.push(vwapPoints, chart.point.from_index(bar_index, vwapVal))
array.push(upperPoints, chart.point.from_index(bar_index, upperBand))
array.push(lowerPoints, chart.point.from_index(bar_index, lowerBand))
activeBins = calcBins(upperBand, lowerBand, atrVal)
// Real-Time Profile & Real-Time Polyline Rendering
int rtLen = bar_index - startBar
// Track active real-time elements using a dedicated SessionElements variable
var SessionElements rtSession = na
if upperBand >= lowerBand and rtLen >= 0 and barstate.islast
// Clear existing real-time elements
deleteSessionElements(rtSession)
rtSession := SessionElements.new(
fillPoly = na,
vwapPoly = na,
upperPoly = na,
lowerPoly = na,
profileLines = array.new_line(0),
profileBoxes = array.new_box(0),
pocLine = na
)
// Render current open session dynamic polylines and live band fill polygon
if array.size(vwapPoints) > 1
chart.point[] fillPts = createFillPolygon(upperPoints, lowerPoints)
rtSession.fillPoly := polyline.new(fillPts, line_color = color.new(color.white, 100), fill_color = color.new(baseGray, 95))
rtSession.vwapPoly := polyline.new(vwapPoints, line_color = isVwapRising ? upColor : dnColor, line_width = 2)
rtSession.upperPoly := polyline.new(upperPoints, line_color = color.gray, line_width = 1)
rtSession.lowerPoly := polyline.new(lowerPoints, line_color = color.gray, line_width = 1)
binStep = upperBand > lowerBand ? (upperBand - lowerBand) / activeBins : 0.0
binTotalVol = array.new_float(activeBins, 0.0)
binBullCount = array.new_int(activeBins, 0)
binBearCount = array.new_int(activeBins, 0)
if binStep > 0
for i = 0 to rtLen
p = close[i]
v = volume[i]
isUp = close[i] >= open[i]
if p >= lowerBand and p <= upperBand
binIndex = math.min(activeBins - 1, math.floor((p - lowerBand) / binStep))
distributeBinVolume(binTotalVol, binBullCount, binBearCount, binIndex, v, isUp, activeBins)
maxBinVol = 0.0
pocBinIndex = 0
for b = 0 to activeBins - 1
totV = array.get(binTotalVol, b)
if totV > maxBinVol
maxBinVol := totV
pocBinIndex := b
if maxBinVol > 0
rtRightEdge = bar_index + rightOffset
rtPocLeft = 0
for b = 0 to activeBins - 1
totV = array.get(binTotalVol, b)
bullCount = array.get(binBullCount, b)
bearCount = array.get(binBearCount, b)
if totV > 0
bLow = lowerBand + (b * binStep)
bHigh = bLow + binStep
bMid = (bLow + bHigh) / 2.0
barSpan = math.max(1, math.round((totV / maxBinVol) * 30))
leftBar = rtRightEdge - barSpan
if b == pocBinIndex
rtPocLeft := leftBar
binLineColor = getBinColor(b, activeBins, totV, maxBinVol, isVwapRising)
// Profile Lines
pLine = line.new(
x1 = leftBar, y1 = bMid, x2 = rtRightEdge, y2 = bMid, xloc = xloc.bar_index,
color = binLineColor,
style = line.style_solid, width = 1
)
array.push(rtSession.profileLines, pLine)
// Profile Labels
if showLabels
bBox = box.new(
left = rtRightEdge, top = bHigh, right = rtRightEdge + 12, bottom = bLow,
xloc = xloc.bar_index,
bgcolor = color.new(color.black, 100),
border_color = color.new(color.black, 100),
text = "[+" + str.tostring(bullCount) + " | -" + str.tostring(bearCount) + "]",
text_size = size.auto,
text_color = chart.fg_color,
text_halign = text.align_left,
text_valign = text.align_center
)
array.push(rtSession.profileBoxes, bBox)
if showPoc
pocPrice = lowerBand + (pocBinIndex * binStep) + (binStep / 2.0)
rtSession.pocLine := line.new(x1 = rtPocLeft, y1 = pocPrice, x2 = startBar, y2 = pocPrice, xloc = xloc.bar_index, color = pocColor, style = line.style_solid, width = 2)
// Signals
var int lastSignalBar = -9999
bool gapMet = (bar_index - lastSignalBar) >= 10
bool upperSignal = high > upperBand and close < upperBand and showSignals and gapMet and barstate.isconfirmed
bool lowerSignal = low < lowerBand and close > lowerBand and showSignals and gapMet and barstate.isconfirmed
if upperSignal or lowerSignal
lastSignalBar := bar_index
// Signal Shapes
plotshape(upperSignal ? high + atrVal : na, "Upper Reversal", shape.triangledown, location.absolute, color = dnColor, size = size.small)
plotshape(lowerSignal ? low - atrVal : na, "Lower Reversal", shape.triangleup, location.absolute, color = upColor, size = size.small)