Volume Profile Heatmap [TradingFinder] POC VAH & VAL Vol Trading

TradingFinder · study · 693 行 · 点赞 157 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradingFinder
//@version=6
indicator("Volume Profile Heatmap [TradingFinder] POC VAH & VAL Vol Trading", "Volume Profile", overlay = true, max_boxes_count = 500, max_lines_count = 100, max_labels_count = 100, max_polylines_count = 20, max_bars_back = 3000)
 
//Inputs
RangeMode = input.string("Visible Range", "Profile Range", options = ["Visible Range", "Last N Bars", "Anchored Time", "Current Session"], group = "Profile Range", tooltip = "Choose the candles included in the volume profile.", display = display.none)
RowCount = input.int(76, "Price Rows", minval = 24, maxval = 120, group = "Profile Range", inline = "bins", tooltip = "More rows show finer price detail.", display = display.none)
ValuePct = input.int(70, "Value Area %", minval = 50, maxval = 90, group = "Profile Range", inline = "bins", tooltip = "Percent of volume used to calculate VAH and VAL.", display = display.none)
Lookback = input.int(240, "Lookback Bars", minval = 20, maxval = 2400, group = "Profile Range", active = RangeMode == "Last N Bars", tooltip = "Number of recent candles to include.", display = display.none)
AnchorStart = input.time(timestamp("01 Oct 2026 00:00 +0000"), "Start Time", group = "Profile Range", active = RangeMode == "Anchored Time", tooltip = "First time included in the anchored profile.", display = display.none)
AnchorEnd = input.time(timestamp("31 Dec 2026 23:59 +0000"), "End Time", group = "Profile Range", active = RangeMode == "Anchored Time", tooltip = "Last time included in the anchored profile.", display = display.none)
SessionTF = input.string("D", "Session Length", options = ["D", "W"], group = "Profile Range", active = RangeMode == "Current Session", tooltip = "D = daily profile; W = weekly profile.", display = display.none)
DataMode = input.string("Lower TF (estimated)", "Volume Data", options = ["Lower TF (estimated)", "Chart OHLCV"], group = "Volume Data", tooltip = "Use lower-timeframe candles when available, or estimate from chart candles. Not true bid/ask volume.", display = display.none)
IntrabarChoice = input.string("Auto", "Lower Timeframe", options = ["Auto", "1", "3", "5", "15", "60"], group = "Volume Data", active = DataMode == "Lower TF (estimated)", tooltip = "Auto selects a smaller timeframe. Numbers are minutes.", display = display.none)
CacheBars = input.int(2400, "History Bars", minval = 300, maxval = 2600, step = 100, group = "Volume Data", tooltip = "Maximum chart candles kept for calculations. More history uses more memory.", display = display.none)
RequireFull = input.bool(true, "Require Complete Range", group = "Volume Data", tooltip = "ON: hide incomplete profiles. OFF: display available data with a partial-range warning.", display = display.none)
PanelMode = "On"
SegmentLayout = input.string("Stacked", "Buy & Sell Layout", options = ["Stacked", "Opposing"], group = "Display", active = "Directional Proxy" == "Directional Proxy", tooltip = "Stacked joins both sides. Opposing shows them on opposite sides of a center line.", display = display.none)
PanelPlace = input.string("Top Right", "Panel Position", options = ["Top Right", "Bottom Right", "Top Left"], group = "Display", active = PanelMode != "Off", tooltip = "Choose where the information panel appears.", display = display.none)
EnableAlerts = input.bool(false, "Dynamic POC Alert (Beta)", group = "Alerts", tooltip = "Alert when price crosses the current moving POC on a closed bar. This is experimental.", display = display.none)
 
//Volume Data
ChartSec = timeframe.in_seconds()
LowerTF = IntrabarChoice == "Auto" ? ChartSec >= 86400 ? "60" : ChartSec >= 3600 ? "5" : "1" : IntrabarChoice
LowerTFValid = timeframe.in_seconds(LowerTF) < ChartSec
RequestLower = DataMode == "Lower TF (estimated)" and LowerTFValid
[LoO, LoH, LoL, LoC, LoV] = request.security_lower_tf(syminfo.tickerid, LowerTF, [open, high, low, close, volume], ignore_invalid_timeframe = true)
CurrentATR = ta.atr(14)
FastEMA = ta.ema(close, 9)
SlowEMA = ta.ema(close, 21)
PriceMove = not na(close[5]) and not na(CurrentATR) and CurrentATR > 0 ? (close - close[5]) / CurrentATR : na
SessionKey = time(SessionTF)
const int Micro = 8
var RecIndex = array.new_int()
var RecTime = array.new_int()
var RecSession = array.new_int()
var RecHigh = array.new_float()
var RecLow = array.new_float()
var RecVolume = array.new_float()
var RecIntrabar = array.new_bool()
var RecCoverage = array.new_float()
var MicroVolume = array.new_float()
var MicroUp = array.new_float()
var DrawingBoxes = array.new_box()
var DrawingLines = array.new_line()
var DrawingLabels = array.new_label()
var DrawingContours = array.new<polyline>()
 
//Volume Sampling
 
Sample(int Root, float PriceLow, float PriceHigh, float SampleLow, float SampleHigh, float Amount, float UpAmount) =>
    Span = PriceHigh - PriceLow
    if Amount > 0 and Span > 0
        Lower = math.max(PriceLow, math.min(SampleLow, SampleHigh))
        Upper = math.min(PriceHigh, math.max(SampleLow, SampleHigh))
        if Upper <= Lower
            Target = int(math.max(0, math.min(Micro - 1, math.floor((Lower - PriceLow) / Span * Micro))))
            array.set(MicroVolume, Root + Target, array.get(MicroVolume, Root + Target) + Amount)
            array.set(MicroUp, Root + Target, array.get(MicroUp, Root + Target) + UpAmount)
        else
            Unit = Span / Micro
            for M = 0 to Micro - 1
                A = PriceLow + M * Unit
                B = A + Unit
                Overlap = math.max(0.0, math.min(B, Upper) - math.max(A, Lower))
                if Overlap > 0
                    Portion = Overlap / (Upper - Lower)
                    array.set(MicroVolume, Root + M, array.get(MicroVolume, Root + M) + Amount * Portion)
                    array.set(MicroUp, Root + M, array.get(MicroUp, Root + M) + UpAmount * Portion)
    else if Amount > 0
        array.set(MicroVolume, Root, array.get(MicroVolume, Root) + Amount)
        array.set(MicroUp, Root, array.get(MicroUp, Root) + UpAmount)
HistorySize = array.size(RecIndex)
ExistingBar = HistorySize > 0 and array.get(RecIndex, HistorySize - 1) == bar_index
if not ExistingBar
    array.push(RecIndex, bar_index)
    array.push(RecTime, time)
    array.push(RecSession, SessionKey)
    array.push(RecHigh, high)
    array.push(RecLow, low)
    array.push(RecVolume, nz(volume))
    array.push(RecIntrabar, false)
    array.push(RecCoverage, 0.0)
    for M = 0 to Micro - 1
        array.push(MicroVolume, 0.0)
        array.push(MicroUp, 0.0)
    if array.size(RecIndex) > CacheBars
        array.shift(RecIndex)
        array.shift(RecTime)
        array.shift(RecSession)
        array.shift(RecHigh)
        array.shift(RecLow)
        array.shift(RecVolume)
        array.shift(RecIntrabar)
        array.shift(RecCoverage)
        for M = 0 to Micro - 1
            array.shift(MicroVolume)
            array.shift(MicroUp)
Record = array.size(RecIndex) - 1
RecordRoot = Record * Micro
array.set(RecHigh, Record, high)
array.set(RecLow, Record, low)
array.set(RecVolume, Record, nz(volume))
for M = 0 to Micro - 1
    array.set(MicroVolume, RecordRoot + M, 0.0)
    array.set(MicroUp, RecordRoot + M, 0.0)
IntrabarN = na(LoV) ? 0 : array.size(LoV)
ChartVolume = math.max(0.0, nz(volume))
ObservedVolume = 0.0
if RequestLower and IntrabarN > 0
    for M = 0 to IntrabarN - 1
        ObservedVolume += math.max(0.0, nz(array.get(LoV, M)))
HasIntrabars = RequestLower and ObservedVolume > 0 and ChartVolume > 0
if HasIntrabars
    Reduction = math.min(1.0, ChartVolume / ObservedVolume)
    Represented = 0.0
    for M = 0 to IntrabarN - 1
        V = math.max(0.0, nz(array.get(LoV, M))) * Reduction
        O = array.get(LoO, M)
        C = array.get(LoC, M)
        Positive = C > O ? V : C < O ? 0.0 : V * 0.5
        Sample(RecordRoot, low, high, array.get(LoL, M), array.get(LoH, M), V, Positive)
        Represented += V
    Remaining = math.max(0.0, ChartVolume - Represented)
    if Remaining > 0
        Positive = close > open ? Remaining : close < open ? 0.0 : Remaining * 0.5
        Sample(RecordRoot, low, high, low, high, Remaining, Positive)
    array.set(RecCoverage, Record, math.max(0.0, math.min(1.0, Represented / ChartVolume)))
else
    Positive = close > open ? ChartVolume : close < open ? 0.0 : ChartVolume * 0.5
    Sample(RecordRoot, low, high, low, high, ChartVolume, Positive)
    array.set(RecCoverage, Record, 0.0)
array.set(RecIntrabar, Record, HasIntrabars)
 
//Volume Profile
 
Profile(int First, int Last, int Bins) =>
    array<float> Amounts = array.new_float(Bins, 0.0)
    array<float> Rising = array.new_float(Bins, 0.0)
    float FloorPrice = na
    float CeilingPrice = na
    if First >= 0 and Last >= First
        for I = First to Last
            FloorPrice := na(FloorPrice) ? array.get(RecLow, I) : math.min(FloorPrice, array.get(RecLow, I))
            CeilingPrice := na(CeilingPrice) ? array.get(RecHigh, I) : math.max(CeilingPrice, array.get(RecHigh, I))
    Valid = not na(FloorPrice) and CeilingPrice > FloorPrice
    Resolution = Valid ? (CeilingPrice - FloorPrice) / Bins : na
    GrandTotal = 0.0
    WithIntrabars = 0
    Contributing = 0
    CoveredVolume = 0.0
    if Valid
        for I = First to Last
            Span = array.get(RecHigh, I) - array.get(RecLow, I)
            MicroStep = Span / Micro
            CandleV = array.get(RecVolume, I)
            if CandleV > 0
                Contributing += 1
                CoveredVolume += CandleV * array.get(RecCoverage, I)
                if array.get(RecIntrabar, I)
                    WithIntrabars += 1
            for M = 0 to Micro - 1
                SampleIdx = I * Micro + M
                V = array.get(MicroVolume, SampleIdx)
                if V > 0
                    U = array.get(MicroUp, SampleIdx)
                    PartL = array.get(RecLow, I) + M * MicroStep
                    PartH = PartL + MicroStep
                    if PartH <= PartL
                        K = int(math.max(0, math.min(Bins - 1, math.floor((PartL - FloorPrice) / Resolution))))
                        array.set(Amounts, K, array.get(Amounts, K) + V)
                        array.set(Rising, K, array.get(Rising, K) + U)
                    else
                        LowerBin = int(math.max(0, math.min(Bins - 1, math.floor((PartL - FloorPrice) / Resolution))))
                        UpperBin = int(math.max(0, math.min(Bins - 1, math.floor((PartH - FloorPrice) / Resolution))))
                        for K = LowerBin to UpperBin
                            BinLow = FloorPrice + K * Resolution
                            Width = math.max(0, math.min(PartH, BinLow + Resolution) - math.max(PartL, BinLow))
                            if Width > 0
                                Scale = Width / (PartH - PartL)
                                array.set(Amounts, K, array.get(Amounts, K) + V * Scale)
                                array.set(Rising, K, array.get(Rising, K) + U * Scale)
    Peak = -1.0
    PocRow = 0
    for K = 0 to Bins - 1
        V = array.get(Amounts, K)
        GrandTotal += V
        if V > Peak
            Peak := V
            PocRow := K
    ValLowRow = PocRow
    ValHighRow = PocRow
    Enclosed = array.get(Amounts, PocRow)
    Requested = GrandTotal * ValuePct / 100.0
    if GrandTotal > 0
        for Step = 0 to Bins - 1
            if Enclosed < Requested and (ValLowRow > 0 or ValHighRow < Bins - 1)
                Below = ValLowRow > 0 ? array.get(Amounts, ValLowRow - 1) : -1.0
                Above = ValHighRow < Bins - 1 ? array.get(Amounts, ValHighRow + 1) : -1.0
                if Above > Below and ValHighRow < Bins - 1
                    ValHighRow += 1
                    Enclosed += array.get(Amounts, ValHighRow)
                else if ValLowRow > 0
                    ValLowRow -= 1
                    Enclosed += array.get(Amounts, ValLowRow)
                else if ValHighRow < Bins - 1
                    ValHighRow += 1
                    Enclosed += array.get(Amounts, ValHighRow)
    [Amounts, Rising, FloorPrice, Resolution, PocRow, ValLowRow, ValHighRow, math.max(Peak, 0.0), GrandTotal, Contributing, WithIntrabars, CoveredVolume, Valid and GrandTotal > 0]
 
Clear() =>
    for Item in DrawingBoxes
        box.delete(Item)
    for Item in DrawingLines
        line.delete(Item)
    for Item in DrawingLabels
        label.delete(Item)
    for Item in DrawingContours
        polyline.delete(Item)
    array.clear(DrawingBoxes)
    array.clear(DrawingLines)
    array.clear(DrawingLabels)
    array.clear(DrawingContours)
 
Box(int X1, float Y1, int X2, float Y2, color Fill) =>
    box Obj = box.new(X1, Y1, X2, Y2, border_color = color.new(Fill, 100), bgcolor = Fill)
    array.push(DrawingBoxes, Obj)
 
Line(int X1, float Y, int X2, color Ink, string Kind, int Thickness) =>
    line Obj = line.new(X1, Y, X2, Y, color = Ink, style = Kind, width = Thickness)
    array.push(DrawingLines, Obj)
 
Divider(int X, float Top, float Bottom, color Ink, int Thickness) =>
    line Obj = line.new(X, Top, X, Bottom, color = Ink, width = Thickness)
    array.push(DrawingLines, Obj)
 
Tag(int X, float Y, string Msg, color Ink) =>
    label Obj = label.new(X, Y, Msg, color = color.new(color.black, 100), textcolor = Ink, style = label.style_label_left, size = Msg == "POC" or Msg == "VAH" or Msg == "VAL" ? size.normal : size.tiny)
    array.push(DrawingLabels, Obj)
 
//Heatmap||||
 
ColorMap(float Value) =>
    Rv = 100.0 - math.max(0.0, math.min(100.0, Value))
    color Result = na
    if Rv < 10.0
        Result := color.from_gradient(Rv, 0.0, 10.0, #990000, #CC0000)
    else if Rv < 20.0
        Result := color.from_gradient(Rv, 10.0, 20.0, #CC0000, #FF6600)
    else if Rv < 30.0
        Result := color.from_gradient(Rv, 20.0, 30.0, #FF6600, #FFCC00)
    else if Rv < 40.0
        Result := color.from_gradient(Rv, 30.0, 40.0, #FFCC00, #CCFF66)
    else if Rv < 50.0
        Result := color.from_gradient(Rv, 40.0, 50.0, #CCFF66, #66FF66)
    else if Rv < 60.0
        Result := color.from_gradient(Rv, 50.0, 60.0, #66FF66, #66FFCC)
    else if Rv < 70.0
        Result := color.from_gradient(Rv, 60.0, 70.0, #66FFCC, #33CCFF)
    else if Rv < 80.0
        Result := color.from_gradient(Rv, 70.0, 80.0, #33CCFF, #3399FF)
    else if Rv < 90.0
        Result := color.from_gradient(Rv, 80.0, 90.0, #3399FF, #0066FF)
    else if Rv < 95.0
        Result := color.from_gradient(Rv, 90.0, 95.0, #0066FF, #4902BB)
    else
        Result := color.from_gradient(Rv, 95.0, 100.0, #4902BB, #410280)
    Result
 
HeatValue(array<float> Amounts, array<float> Rising, int Index, int Direction, float Peak) =>
    ValueSum = 0.0
    Weights = 0.0
    N = array.size(Amounts)
    for Offset = -3 to 3
        J = Index + Offset
        if J >= 0 and J < N
            Vol = array.get(Amounts, J)
            Up = math.max(0.0, math.min(Vol, array.get(Rising, J)))
            Val = Direction == 0 ? Vol : Direction == 1 ? Up : Vol - Up
            Weight = 1.0 / (1.0 + math.abs(Offset))
            ValueSum += Val * Weight
            Weights += Weight
    Pct = Peak > 0 and Weights > 0 ? 100.0 * ValueSum / Weights / Peak : 0.0
    100.0 * math.pow(math.max(0.0, math.min(1.0, Pct / 100.0)), 1.0)
 
BuyHeatMap(float Pct) =>
    color.from_gradient(Pct, 0.0, 100.0, #16323A, #2AC7B8)
 
BuyHeatMapMid(float Pct) =>
    color.from_gradient(Pct, 0.0, 100.0, #2AC7B8, #58E6D6)
 
BuyHeatMapHigh(float Pct) =>
    color.from_gradient(Pct, 0.0, 100.0, #58E6D6, #42A7FF)
 
SellHeatMap(float Pct) =>
    color.from_gradient(Pct, 0.0, 100.0, #3B2815, #D7B64A)
 
SellHeatMapMid(float Pct) =>
    color.from_gradient(Pct, 0.0, 100.0, #D7B64A, #FF9742)
 
SellHeatMapHigh(float Pct) =>
    color.from_gradient(Pct, 0.0, 100.0, #FF9742, #EF4A4A)
 
Blend(color A, color B, float T) =>
    color.from_gradient(math.max(0.0, math.min(100.0, T)), 0.0, 100.0, A, B)
 
DirHeatColor(float Pct, bool IsBuy) =>
    Clamped = math.max(0.0, math.min(100.0, Pct))
    if IsBuy
        Clamped < 50.0 ? Blend(BuyHeatMap(0), BuyHeatMapMid(100), Clamped * 2.0) : Blend(BuyHeatMapMid(100), BuyHeatMapHigh(100), (Clamped - 50.0) * 2.0)
    else
        Clamped < 50.0 ? Blend(SellHeatMap(0), SellHeatMapMid(100), Clamped * 2.0) : Blend(SellHeatMapMid(100), SellHeatMapHigh(100), (Clamped - 50.0) * 2.0)
 
PosSpectrum(float Pct) =>
    Rv = 100.0 - math.max(0.0, math.min(100.0, Pct))
    color Result = na
    if Rv < 10.0
        Result := color.from_gradient(Rv, 0.0, 10.0, #0B5F28, #0E7A31)
    else if Rv < 20.0
        Result := color.from_gradient(Rv, 10.0, 20.0, #0E7A31, #14A33F)
    else if Rv < 30.0
        Result := color.from_gradient(Rv, 20.0, 30.0, #14A33F, #25C95C)
    else if Rv < 40.0
        Result := color.from_gradient(Rv, 30.0, 40.0, #25C95C, #53DD7F)
    else if Rv < 50.0
        Result := color.from_gradient(Rv, 40.0, 50.0, #53DD7F, #7EE89F)
    else if Rv < 60.0
        Result := color.from_gradient(Rv, 50.0, 60.0, #7EE89F, #9DEFC0)
    else if Rv < 70.0
        Result := color.from_gradient(Rv, 60.0, 70.0, #9DEFC0, #7CE6D4)
    else if Rv < 80.0
        Result := color.from_gradient(Rv, 70.0, 80.0, #7CE6D4, #53D4E9)
    else if Rv < 90.0
        Result := color.from_gradient(Rv, 80.0, 90.0, #53D4E9, #2AAEF2)
    else if Rv < 95.0
        Result := color.from_gradient(Rv, 90.0, 95.0, #2AAEF2, #177EEA)
    else
        Result := color.from_gradient(Rv, 95.0, 100.0, #177EEA, #0E53D9)
    Result
 
NegSpectrum(float Pct) =>
    Rv = 100.0 - math.max(0.0, math.min(100.0, Pct))
    color Result = na
    if Rv < 10.0
        Result := color.from_gradient(Rv, 0.0, 10.0, #7A0F16, #9C131C)
    else if Rv < 20.0
        Result := color.from_gradient(Rv, 10.0, 20.0, #9C131C, #C61A26)
    else if Rv < 30.0
        Result := color.from_gradient(Rv, 20.0, 30.0, #C61A26, #E3342F)
    else if Rv < 40.0
        Result := color.from_gradient(Rv, 30.0, 40.0, #E3342F, #F25A38)
    else if Rv < 50.0
        Result := color.from_gradient(Rv, 40.0, 50.0, #F25A38, #FA7C3A)
    else if Rv < 60.0
        Result := color.from_gradient(Rv, 50.0, 60.0, #FA7C3A, #FFA348)
    else if Rv < 70.0
        Result := color.from_gradient(Rv, 60.0, 70.0, #FFA348, #E58E3F)
    else if Rv < 80.0
        Result := color.from_gradient(Rv, 70.0, 80.0, #E58E3F, #C57335)
    else if Rv < 90.0
        Result := color.from_gradient(Rv, 80.0, 90.0, #C57335, #A45831)
    else if Rv < 95.0
        Result := color.from_gradient(Rv, 90.0, 95.0, #A45831, #88442C)
    else
        Result := color.from_gradient(Rv, 95.0, 100.0, #88442C, #6A342B)
    Result
 
HeatColor(float Pct, color Hue, bool Within, bool Secondary, int Direction) =>
    Base = "Positive / Negative Spectrum" == "Positive / Negative Spectrum" ? (Direction == 1 ? PosSpectrum(Pct) : Direction == 2 ? NegSpectrum(Pct) : ColorMap(Pct)) : "Positive / Negative Spectrum" == "Unified Spectral" or "Positive / Negative Spectrum" == "Spectral + Direction" ? ColorMap(Pct) : "Positive / Negative Spectrum" == "Directional" ? color.from_gradient(Pct, 0.0, 100.0, #202936, Hue) : DirHeatColor(Pct, Direction == 1)
    Alpha = Secondary ? 79 : Within ? 9 : 43
    color.new(Base, Alpha)
 
TintAlpha(bool Within, bool Secondary) =>
    Secondary ? 88 : Within ? 68 : 78
 
//Drawing
 
HeatBar(int X1, int X2, float Top, float Bottom, color Hue, float Power, bool Within, bool Secondary, int Direction) =>
    if X2 > X1 and Top > Bottom
        Box(X1, Top, X2, Bottom, HeatColor(Power, Hue, Within, Secondary, Direction))
        if "Positive / Negative Spectrum" == "Spectral + Direction" and Direction != 0
            Box(X1, Top, X2, Bottom, color.new(Hue, TintAlpha(Within, Secondary)))
    true
 
TraceSurface(array<int> Lefts, array<int> Rights, float FloorPrice, float Resolution, color Hue, bool Secondary) =>
    if false
        Bins = array.size(Lefts)
        AnyWidth = false
        array<chart.point> Points = array.new<chart.point>()
        for K = 0 to Bins - 1
            Xr = array.get(Rights, K)
            AnyWidth := AnyWidth or Xr > array.get(Lefts, K)
            array.push(Points, chart.point.from_index(Xr, FloorPrice + K * Resolution))
            array.push(Points, chart.point.from_index(Xr, FloorPrice + (K + 1) * Resolution))
        for K = Bins - 1 to 0
            Xl = array.get(Lefts, K)
            array.push(Points, chart.point.from_index(Xl, FloorPrice + (K + 1) * Resolution))
            array.push(Points, chart.point.from_index(Xl, FloorPrice + K * Resolution))
        if AnyWidth
            polyline Halo = polyline.new(Points, curved = false, closed = true, xloc = xloc.bar_index, line_color = color.new(Hue, Secondary ? 95 : 86), fill_color = na, line_width = 3)
            polyline Edge = polyline.new(Points, curved = false, closed = true, xloc = xloc.bar_index, line_color = color.new(Hue, Secondary ? 75 : 24), fill_color = na, line_width = 1)
            array.push(DrawingContours, Halo)
            array.push(DrawingContours, Edge)
    true
 
Draw(array<float> Amounts, array<float> Rising, float FloorPrice, float Resolution, int Point, int AreaLow, int AreaHigh, float MaxVolume, int AnchorX, int Side, int ProfileWidth, bool Secondary) =>
    Bins = array.size(Amounts)
    if MaxVolume > 0
        Opposing = "Directional Proxy" == "Directional Proxy" and SegmentLayout == "Opposing"
        HalfWidth = int(math.max(1, math.floor(ProfileWidth / 2.0)))
        MiddleX = Side < 0 ? AnchorX - HalfWidth : AnchorX + HalfWidth
        LargestSide = 0.0
        HeatPeak = 0.0
        if "Directional Proxy" == "Directional Proxy"
            for K = 0 to Bins - 1
                Vol = array.get(Amounts, K)
                Up = math.max(0.0, math.min(Vol, array.get(Rising, K)))
                HeatPeak := math.max(HeatPeak, math.max(Up, Vol - Up))
            if Opposing
                LargestSide := HeatPeak
        array<int> BuyLeft = array.new_int(Bins, AnchorX)
        array<int> BuyRight = array.new_int(Bins, AnchorX)
        array<int> SellLeft = array.new_int(Bins, AnchorX)
        array<int> SellRight = array.new_int(Bins, AnchorX)
        array<int> TotalLeft = array.new_int(Bins, AnchorX)
        array<int> TotalRight = array.new_int(Bins, AnchorX)
        for K = 0 to Bins - 1
            Vol = array.get(Amounts, K)
            if Vol > 0
                Bottom = FloorPrice + K * Resolution
                Top = Bottom + Resolution
                Within = K >= AreaLow and K <= AreaHigh
                BuyVol = math.max(0.0, math.min(Vol, array.get(Rising, K)))
                SellVol = Vol - BuyVol
                if "Directional Proxy" == "Directional Proxy"
                    BuyPower = HeatValue(Amounts, Rising, K, 1, HeatPeak)
                    SellPower = HeatValue(Amounts, Rising, K, 2, HeatPeak)
                    if Opposing
                        BuyLen = LargestSide > 0 ? int(math.round(HalfWidth * BuyVol / LargestSide)) : 0
                        SellLen = LargestSide > 0 ? int(math.round(HalfWidth * SellVol / LargestSide)) : 0
                        Bl = MiddleX - BuyLen
                        Br = MiddleX
                        Sl = MiddleX
                        Sr = MiddleX + SellLen
                        array.set(BuyLeft, K, Bl)
                        array.set(BuyRight, K, Br)
                        array.set(SellLeft, K, Sl)
                        array.set(SellRight, K, Sr)
                        HeatBar(Bl, Br, Top, Bottom, #3CCFB8, BuyPower, Within, Secondary, 1)
                        HeatBar(Sl, Sr, Top, Bottom, #F17F96, SellPower, Within, Secondary, 2)
                    else
                        Width = int(math.max(1, math.round(ProfileWidth * Vol / MaxVolume)))
                        BuyLen = int(math.round(Width * BuyVol / Vol))
                        if BuyVol > 0 and SellVol > 0 and Width >= 2
                            BuyLen := int(math.max(1, math.min(Width - 1, BuyLen)))
                        SellLen = Width - BuyLen
                        Bl = Side < 0 ? AnchorX - Width : AnchorX
                        Br = Bl + BuyLen
                        Sl = Br
                        Sr = Bl + Width
                        array.set(BuyLeft, K, Bl)
                        array.set(BuyRight, K, Br)
                        array.set(SellLeft, K, Sl)
                        array.set(SellRight, K, Sr)
                        HeatBar(Bl, Br, Top, Bottom, #3CCFB8, BuyPower, Within, Secondary, 1)
                        HeatBar(Sl, Sr, Top, Bottom, #F17F96, SellPower, Within, Secondary, 2)
                        if BuyLen > 0 and SellLen > 0
                            Divider(Br, Top, Bottom, color.new(#EAF3FF, 10), 1)
                else
                    Width = int(math.max(1, math.round(ProfileWidth * Vol / MaxVolume)))
                    Left = Side < 0 ? AnchorX - Width : AnchorX
                    Right = Left + Width
                    array.set(TotalLeft, K, Left)
                    array.set(TotalRight, K, Right)
                    Power = HeatValue(Amounts, Rising, K, 0, MaxVolume)
                    HeatBar(Left, Right, Top, Bottom, #74879E, Power, Within, Secondary, 0)
        if "Directional Proxy" == "Directional Proxy"
            TraceSurface(BuyLeft, BuyRight, FloorPrice, Resolution, #3CCFB8, Secondary)
            TraceSurface(SellLeft, SellRight, FloorPrice, Resolution, #F17F96, Secondary)
        else
            TraceSurface(TotalLeft, TotalRight, FloorPrice, Resolution, #74879E, Secondary)
    true
 
NodeLabels(array<float> Amounts, float FloorPrice, float Resolution, int X) =>
    Bins = array.size(Amounts)
    Highest = array.max(Amounts)
    HighNode = -1
    LowNode = -1
    BestHigh = 0.0
    BestLow = 1e100
    if Bins >= 5 and Highest > 0
        for K = 2 to Bins - 3
            V = array.get(Amounts, K)
            Pre = array.get(Amounts, K - 1)
            Next = array.get(Amounts, K + 1)
            if V > Pre and V >= Next and V > Highest * 0.45 and V > BestHigh
                HighNode := K
                BestHigh := V
            if V < Pre and V <= Next and V > Highest * 0.03 and V < Highest * 0.35 and V < BestLow
                LowNode := K
                BestLow := V
    if HighNode >= 0
        Tag(X, FloorPrice + (HighNode + 0.5) * Resolution, "HVN", #3CCFB8)
    if LowNode >= 0
        Tag(X, FloorPrice + (LowNode + 0.5) * Resolution, "LVN", #F17F96)
 
VolumeText(float V) =>
    V >= 1e9 ? str.tostring(V / 1e9, "#.##") + "B" : V >= 1e6 ? str.tostring(V / 1e6, "#.##") + "M" : V >= 1e3 ? str.tostring(V / 1e3, "#.##") + "K" : str.tostring(V, "#.##")
 
TableRow(table Tab, int Row, string Key, string Value, color Emphasis) =>
    Bg = Row % 2 == 0 ? #0C2051 : #10285D
    table.cell(Tab, 0, Row, Key, text_color = #E3EEFF, bgcolor = Bg, text_halign = text.align_left, text_size = size.small)
    table.cell(Tab, 1, Row, Value, text_color = Emphasis, bgcolor = Bg, text_halign = text.align_right, text_size = size.small)
 
//Dashboard
var table Stats = na
var float ScalePoc = na
var float ScaleVah = na
var float ScaleVal = na
 
if barstate.islast
    Clear()
    ScalePoc := na
    ScaleVah := na
    ScaleVal := na
    Saved = array.size(RecIndex)
    Start = -1
    Finish = -1
    if RangeMode == "Last N Bars"
        Start := math.max(0, Saved - Lookback)
        Finish := Saved - 1
    else if RangeMode == "Current Session"
        LastSession = array.get(RecSession, Saved - 1)
        for I = 0 to Saved - 1
            if array.get(RecSession, I) == LastSession
                if Start < 0
                    Start := I
                Finish := I
    else if RangeMode != "Anchored Time" or AnchorEnd >= AnchorStart
        for I = 0 to Saved - 1
            T = array.get(RecTime, I)
            Inside = RangeMode == "Visible Range" ? T >= chart.left_visible_bar_time and T <= chart.right_visible_bar_time : T >= AnchorStart and T <= AnchorEnd
            if Inside
                if Start < 0
                    Start := I
                Finish := I
    Exists = Start >= 0 and Finish >= Start
    FirstStoredTime = array.get(RecTime, 0)
    LastStoredTime = array.get(RecTime, Saved - 1)
    FirstStoredIndex = array.get(RecIndex, 0)
    RangeDesc = "No valid range"
    if Exists
        if RangeMode == "Visible Range"
            RangeDesc := chart.left_visible_bar_time < FirstStoredTime ? FirstStoredIndex > 0 ? "Partial range" : "Not verified" : "Full range"
        else if RangeMode == "Last N Bars"
            RangeDesc := Saved >= Lookback ? "Full range" : FirstStoredIndex > 0 ? "Partial range" : "Not verified"
        else if RangeMode == "Anchored Time"
            RangeDesc := AnchorStart < FirstStoredTime ? FirstStoredIndex > 0 ? "Partial range" : "Not verified" : AnchorEnd > LastStoredTime ? "Not verified" : "Full range"
        else
            RangeDesc := Start > 0 or FirstStoredTime == array.get(RecSession, 0) ? "Full range" : "Not verified"
    FullRange = RangeDesc == "Full range"
    SourceDesc = "Unavailable"
    ShiftDesc = "Unavailable"
    LocationDesc = "Unavailable"
    QualityDesc = FullRange ? "Full range" : RangeDesc
    float Total = na
    float PocPrice = na
    float VahPrice = na
    float ValPrice = na
    float SourceCoverage = na
    float BuyTotal = na
    float SellTotal = na
    ProfileValid = false
    SuppressProfile = false
    if Exists
        [MainV, MainUp, PriceBase, PriceStep, PocIdx, VaBottom, VaTop, Strongest, ProfileTotal, UsedBars, LtfBars, CoverageVolume, Okay] = Profile(Start, Finish, RowCount)
        ProfileValid := Okay
        if Okay
            Total := ProfileTotal
            SourceCoverage := ProfileTotal > 0 ? 100.0 * CoverageVolume / ProfileTotal : na
            SourceDesc := LtfBars == 0 ? "Chart OHLCV proxy" : CoverageVolume >= ProfileTotal * 0.999 ? "Lower-TF proxy" : "LTF + fallback"
            SuppressProfile := RequireFull and not FullRange
            QualityDesc := SuppressProfile ? "Blocked: " + RangeDesc : FullRange ? "Full range" : "PARTIAL PROFILE"
            if not SuppressProfile
                BuyTotal := math.max(0.0, math.min(ProfileTotal, array.sum(MainUp)))
                SellTotal := math.max(0.0, ProfileTotal - BuyTotal)
                PocPrice := PriceBase + (PocIdx + 0.5) * PriceStep
                VahPrice := PriceBase + (VaTop + 1) * PriceStep
                ValPrice := PriceBase + VaBottom * PriceStep
                LocationDesc := close > VahPrice ? "Above Value" : close < ValPrice ? "Below Value" : "Inside Value"
                Right = RangeMode == "Visible Range"
                X = Right ? array.get(RecIndex, Finish) + 20 + 100 * 4 : array.get(RecIndex, Start)
                Dir = Right ? -1 : 1
                Width = Right ? 100 * 4 : int(math.max(8, math.min(100, (array.get(RecIndex, Finish) - array.get(RecIndex, Start) + 1) * 0.75))) * 4
                LeftEdge = array.get(RecIndex, Start)
                RightEdge = Right ? X : array.get(RecIndex, Finish)
                if false
                    Box(LeftEdge, VahPrice, RightEdge, ValPrice, color.new(#74879E, 96))
                Draw(MainV, MainUp, PriceBase, PriceStep, PocIdx, VaBottom, VaTop, Strongest, X, Dir, Width, false)
                if true
                    Line(LeftEdge, PocPrice, RightEdge, #EFCB77, line.style_solid, 2)
                    Line(LeftEdge, VahPrice, RightEdge, color.new(#74879E, 35), line.style_dashed, 1)
                    Line(LeftEdge, ValPrice, RightEdge, color.new(#74879E, 35), line.style_dashed, 1)
                    if true
                        Tag(RightEdge + 2, PocPrice, "POC", #EFCB77)
                        if math.abs(VahPrice - PocPrice) >= PriceStep * 1.7
                            Tag(RightEdge + 2, VahPrice, "VAH", #74879E)
                        if math.abs(ValPrice - PocPrice) >= PriceStep * 1.7 and math.abs(VahPrice - ValPrice) >= PriceStep * 1.7
                            Tag(RightEdge + 2, ValPrice, "VAL", #74879E)
                if false
                    NodeLabels(MainV, PriceBase, PriceStep, Right ? X - 100 * 4 - 10 : X + Width + 2)
                if false
                    ScalePoc := PocPrice
                    ScaleVah := VahPrice
                    ScaleVal := ValPrice
                SessionBegin = Saved - 1
                CurrentSession = array.get(RecSession, Saved - 1)
                while SessionBegin > 0 and array.get(RecSession, SessionBegin - 1) == CurrentSession
                    SessionBegin -= 1
                OldEnd = SessionBegin - 1
                if OldEnd >= 0
                    OldBegin = OldEnd
                    OldSession = array.get(RecSession, OldEnd)
                    while OldBegin > 0 and array.get(RecSession, OldBegin - 1) == OldSession
                        OldBegin -= 1
                    [PresentV, PresentUp, PresentFloor, PresentStep, PresentPOC, PresentVaL, PresentVaH, PresentPeak, PresentTotal, PresentBars, PresentLTF, PresentCoverage, PresentValid] = Profile(SessionBegin, Saved - 1, RowCount)
                    [OldV, OldUp, OldFloor, OldStep, OldPOC, OldVaL, OldVaH, OldPeak, OldTotal, OldBars, OldLTF, OldCoverage, OldValid] = Profile(OldBegin, OldEnd, RowCount)
                    if PresentValid and OldValid and OldBegin > 0
                        NewLevel = PresentFloor + (PresentPOC + 0.5) * PresentStep
                        OldLevel = OldFloor + (OldPOC + 0.5) * OldStep
                        DeltaATR = not na(CurrentATR) and CurrentATR > 0 ? (NewLevel - OldLevel) / CurrentATR : na
                        ShiftDesc := na(DeltaATR) ? "Unavailable" : DeltaATR > 0.25 ? "Higher Value" : DeltaATR < -0.25 ? "Lower Value" : "Stable Value"
                        if true and RangeMode == "Current Session"
                            OldX = array.get(RecIndex, OldBegin)
                            OldWidth = int(math.max(8, math.min(100, (array.get(RecIndex, OldEnd) - OldX + 1) * 0.70))) * 4
                            Draw(OldV, OldUp, OldFloor, OldStep, OldPOC, OldVaL, OldVaH, OldPeak, OldX, 1, OldWidth, true)
                            if false
                                OldPocPrice = OldFloor + (OldPOC + 0.5) * OldStep
                                Line(OldX, OldPocPrice, array.get(RecIndex, OldEnd), color.new(#EFCB77, 60), line.style_dashed, 1)
                if EnableAlerts and FullRange and barstate.isconfirmed and bar_index > 0 and not na(close[1]) and (close[1] - PocPrice) * (close - PocPrice) < 0
                    Direction = close > PocPrice ? "above" : "below"
                    alert(syminfo.ticker + " crossed " + Direction + " Volume Atlas dynamic POC (" + str.tostring(PocPrice, format.mintick) + ")", alert.freq_once_per_bar_close)
    if not ProfileValid and Exists
        QualityDesc := "No valid volume"
    if not FullRange or not ProfileValid
        WarningText = not Exists ? "NO VALID RANGE" : not ProfileValid ? "NO VALID VOLUME" : SuppressProfile ? "PROFILE BLOCKED: " + RangeDesc : "PARTIAL PROFILE: available bars only"
        label WarningLabel = label.new(bar_index + 2, high, WarningText, style = label.style_label_down, color = color.new(#B44A58, 10), textcolor = color.white, size = size.tiny)
        array.push(DrawingLabels, WarningLabel)
    if PanelMode != "Off"
        NRows = PanelMode == "Advanced" ? 16 : 10
        if na(Stats)
            Stats := table.new(PanelPlace == "Top Right" ? position.top_right : PanelPlace == "Bottom Right" ? position.bottom_right : position.top_left, 2, NRows, bgcolor = #0C2051, frame_color = #3A578A, frame_width = 1, border_color = #284478, border_width = 1)
            table.merge_cells(Stats, 0, 0, 1, 0)
        HeaderBg = #112D68
        WhiteText = #F1F5FF
        WarnColor = FullRange and ProfileValid ? #00D7BD : #FF8B5C
        ShiftColor = ShiftDesc == "Higher Value" ? #00E2B4 : ShiftDesc == "Lower Value" ? #FF6685 : WhiteText
        RangeText = RangeMode == "Visible Range" ? "Visible range" : RangeMode == "Last N Bars" ? "Last N bars" : RangeMode == "Anchored Time" ? "Anchored time" : "Current session"
        ShiftText = ShiftDesc == "Higher Value" ? "Higher value" : ShiftDesc == "Lower Value" ? "Lower value" : ShiftDesc == "Stable Value" ? "Stable value" : ShiftDesc
        PriceText = LocationDesc == "Above Value" ? "Above value" : LocationDesc == "Below Value" ? "Below value" : LocationDesc == "Inside Value" ? "Inside value" : LocationDesc
        QualityText = QualityDesc == "PARTIAL PROFILE" ? "Partial profile" : QualityDesc
        table.cell(Stats, 0, 0, "◆ Volume Profile Heatmap ◆", bgcolor = #0B1D48, text_color = #54D8FF, text_size = size.normal, text_halign = text.align_center)
        table.cell(Stats, 0, 1, "Metric", bgcolor = HeaderBg, text_color = WhiteText, text_size = size.small, text_halign = text.align_left)
        table.cell(Stats, 1, 1, "Value", bgcolor = HeaderBg, text_color = WhiteText, text_size = size.small, text_halign = text.align_right)
        TableRow(Stats, 2, "Range", RangeText, WhiteText)
        TableRow(Stats, 3, "POC", na(PocPrice) ? "Unavailable" : str.tostring(PocPrice, format.mintick), #EFCB77)
        TableRow(Stats, 4, "VAH / VAL", na(VahPrice) ? "Unavailable" : str.tostring(VahPrice, format.mintick) + " / " + str.tostring(ValPrice, format.mintick), WhiteText)
        TableRow(Stats, 5, "Value migration", ShiftText, ShiftColor)
        TableRow(Stats, 6, "Data quality", QualityText, WarnColor)
        TableRow(Stats, 7, "Buy volume", na(BuyTotal) ? "Unavailable" : VolumeText(BuyTotal) + " (" + str.tostring(100.0 * BuyTotal / (BuyTotal + SellTotal), "#.1") + "%)", #53DD7F)
        TableRow(Stats, 8, "Sell volume", na(SellTotal) ? "Unavailable" : VolumeText(SellTotal) + " (" + str.tostring(100.0 * SellTotal / (BuyTotal + SellTotal), "#.1") + "%)", #FF8B5C)
        TradeReady = FullRange and ProfileValid and not SuppressProfile and not na(PocPrice) and not na(BuyTotal) and not na(SellTotal) and BuyTotal + SellTotal > 0 and not na(PriceMove) and not na(FastEMA[3])
        BuyScore = (FastEMA > SlowEMA ? 2 : 0) + (FastEMA > FastEMA[3] ? 1 : 0) + (PriceMove > 0.35 ? 2 : 0) + (close > FastEMA ? 1 : 0) + (close > PocPrice ? 1 : 0) + (BuyTotal > SellTotal * 1.06 ? 1 : 0)
        SellScore = (FastEMA < SlowEMA ? 2 : 0) + (FastEMA < FastEMA[3] ? 1 : 0) + (PriceMove < -0.35 ? 2 : 0) + (close < FastEMA ? 1 : 0) + (close < PocPrice ? 1 : 0) + (SellTotal > BuyTotal * 1.06 ? 1 : 0)
        BuyPreferred = TradeReady and BuyScore >= 4 and BuyScore >= SellScore + 2
        SellPreferred = TradeReady and SellScore >= 4 and SellScore >= BuyScore + 2
        TradeText = not TradeReady ? "Unavailable" : BuyPreferred ? "Consider buying" : SellPreferred ? "Consider selling" : "Wait"
        TradeColor = BuyPreferred ? #53DD7F : SellPreferred ? #FF8B5C : #C4D9F6
        TableRow(Stats, 9, "Trade preference", TradeText, TradeColor)
        if PanelMode == "Advanced"
            TableRow(Stats, 10, "Total volume", na(Total) ? "Unavailable" : VolumeText(Total) + (FullRange ? "" : " (sample)"), WhiteText)
            TableRow(Stats, 11, "Price context", PriceText, WhiteText)
            TableRow(Stats, 12, "Sampling", SourceDesc, WhiteText)
            TableRow(Stats, 13, "LTF volume coverage", na(SourceCoverage) ? "Unavailable" : str.tostring(SourceCoverage, "#.0") + "% of retained vol.", WhiteText)
            TableRow(Stats, 14, "Range status", RangeDesc, WarnColor)
            TableRow(Stats, 15, "Directional type", "Estimated from candles", #9ED0E7)
    else if not na(Stats)
        table.delete(Stats)
        Stats := na
plot(ScalePoc, "Profile POC", color = #EFCB77)
plot(ScaleVah, "Profile VAH", color = #74879E)
plot(ScaleVal, "Profile VAL", color = #74879E)

← 返回列表