VWAP Heatmap Profile [CandleChasers]

CandleChasers · study · 598 行 · 点赞 43 · TradingView 原页

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

Pine Script

//@version=6
// VWAP Heatmap Profile [CandleChasers] | 1.1
// Anchored bar-source VWAP + candle-range volume-at-price ESTIMATE.
indicator("VWAP Heatmap Profile [CandleChasers]", shorttitle="[CC] VWAP", overlay=true, scale=scale.none, max_boxes_count=500, max_lines_count=100, max_labels_count=60, max_bars_back=1000)
 
string GA="1 · Anchor and VWAP"
string anchorMode=input.string("Trading day","Anchor",options=["Trading day","Recent X trading days","Week","Month","Custom session","Manual time"],group=GA,display=display.none)
int recentDays=input.int(5,"Recent trading days (including current)",minval=1,maxval=30,group=GA,display=display.none)
string sourceChoice=input.string("HLC3","VWAP source",options=["HLC3","HL2","OHLC4","Close"],group=GA,display=display.none)
string sessionHours=input.session("0930-1600","Custom session",group=GA,display=display.none)
string sessionZone=input.string("America/New_York","Session timezone (IANA)",group=GA,display=display.none)
string sessionDays=input.string("23456","Session days: 1=Sun ... 7=Sat",group=GA,display=display.none)
int manualStart=input.time(timestamp("01 Jan 2026 00:00 +0000"),"Manual anchor time",group=GA,display=display.none)
bool holdOutside=input.bool(true,"Hold completed profile outside custom session",group=GA,display=display.none)
bool breakResets=input.bool(true,"Break plot lines at first anchor candle",group=GA,display=display.none)
string GB="2 · VWAP deviation heatmap"
bool showVWAP=input.bool(true,"Show anchored VWAP",group=GB,display=display.none)
bool slopeColor=input.bool(true,"Color VWAP by slope",group=GB,display=display.none)
bool showBands=input.bool(true,"Show weighted deviation bands",group=GB,display=display.none)
float band1=input.float(1,"Inner deviation multiplier",minval=0.1,step=0.25,group=GB,display=display.none)
float band2=input.float(2,"Middle deviation multiplier",minval=0.2,step=0.25,group=GB,display=display.none)
float band3=input.float(3,"Outer deviation multiplier",minval=0.3,step=0.25,group=GB,display=display.none)
bool shadeBands=input.bool(true,"Shade VWAP deviation zones",group=GB,display=display.none)
bool showPrevious=input.bool(false,"Show previous anchor's final VWAP",group=GB,display=display.none)
string GP="3 · Estimated volume profile"
bool showProfile=input.bool(true,"Show current right-side volume profile",group=GP,display=display.none)
bool showHeatmap=input.bool(true,"Show current volume-concentration heatmap",group=GP,display=display.none)
int rowCount=input.int(60,"Requested profile rows",minval=12,maxval=120,group=GP,display=display.none)
int sampleLimit=input.int(3000,"Maximum retained profile samples",minval=100,maxval=5000,group=GP,display=display.none)
string allocation=input.string("Uniform candle range","Volume allocation",options=["Uniform candle range","Selected source price"],group=GP,display=display.none)
bool useLower=input.bool(false,"Use lower-timeframe profile samples",group=GP,display=display.none)
string lowerTF=input.timeframe("1","Profile sampling timeframe",group=GP,display=display.none)
float valuePercent=input.float(70,"Value area / percent",minval=1,maxval=100,step=1,group=GP,display=display.none)
float heatContrast=input.float(0.6,"Volume-intensity contrast exponent",minval=0.1,maxval=2,step=0.1,group=GP,display=display.none)
string GH="4 · Completed daily profiles"
bool saveDaily=input.bool(true,"Retain completed daily profiles",group=GH,display=display.none)
int savedDays=input.int(5,"Completed days to show",minval=1,maxval=10,group=GH,display=display.none)
int savedRows=input.int(24,"Requested rows per saved day",minval=12,maxval=40,group=GH,display=display.none)
string dailyDisplay=input.string("Profile + heatmap","Saved daily display",options=["Profile + heatmap","Profile only","Heatmap only"],group=GH,display=display.none)
float dailyWidth=input.float(25,"Saved histogram width / percent of day",minval=5,maxval=50,step=5,group=GH,display=display.none)
bool dailyLevels=input.bool(true,"Saved POC / VAH / VAL lines",group=GH,display=display.none)
bool dailyVWAP=input.bool(true,"Saved final daily VWAP level",group=GH,display=display.none)
bool limitCurrentHeat=input.bool(true,"Limit current heatmap to latest day when daily heatmaps shown",group=GH,display=display.none)
bool dailyTags=input.bool(true,"Saved day label / tooltip",group=GH,display=display.none)
string GV="5 · Appearance"
int profileWidth=input.int(55,"Profile maximum width / bars",minval=10,maxval=180,group=GV,display=display.none)
int profileOffset=input.int(8,"Profile right offset / bars",minval=2,maxval=100,group=GV,display=display.none)
bool showLevels=input.bool(true,"Show profile POC / VAH / VAL levels",group=GV,display=display.none)
bool showLabels=input.bool(true,"Show level price labels",group=GV,display=display.none)
string labelSize=input.string("Medium","Price label size",options=["Small","Medium","Large","Extra Large"],group=GV,display=display.none)
string panelSize=input.string("Small","Dashboard size",options=["Small","Medium","Large","Hidden"],group=GV,display=display.none)
string panelCorner=input.string("Top Right","Dashboard corner",options=["Top Left","Top Right","Bottom Left","Bottom Right"],group=GV,display=display.none)
color bullColor=input.color(#20D9B0,"Rising VWAP",group=GV,display=display.none)
color bearColor=input.color(#F17694,"Falling VWAP",group=GV,display=display.none)
color coldColor=input.color(#286FC1,"Low-volume profile color",group=GV,display=display.none)
color hotColor=input.color(#FFAD45,"High-volume profile color",group=GV,display=display.none)
color pocColor=input.color(#FFDC65,"POC",group=GV,display=display.none)
color vaColor=input.color(#BCA3FF,"Value area boundaries",group=GV,display=display.none)
string GE="6 · Closed-candle alerts"
bool alertVWAP=input.bool(true,"VWAP close crosses",group=GE,display=display.none)
bool alertBand=input.bool(false,"Outer-band breaks / middle-band returns",group=GE,display=display.none)
bool alertProfile=input.bool(false,"Prior-snapshot POC crosses / value-area transitions",group=GE,display=display.none)
 
color panelBG=color.rgb(18,24,35)
string font=labelSize=="Extra Large" ? size.huge : labelSize=="Large" ? size.large : labelSize=="Medium" ? size.normal : size.small
bool rolling=anchorMode=="Recent X trading days"
float chartSeconds=timeframe.in_seconds()
float lowerSeconds=timeframe.in_seconds(lowerTF)
bool lowerValid=lowerSeconds<chartSeconds and lowerSeconds>0 and chartSeconds/lowerSeconds<=500
if barstate.isfirst
    if not (band1<band2 and band2<band3)
        runtime.error("Deviation multipliers must satisfy inner < middle < outer.")
    if useLower and not lowerValid
        runtime.error("Profile sampling TF must be lower than chart TF, with at most 500 nominal intrabars per chart candle. Choose a coarser sampling TF.")
    if (rolling or saveDaily) and chartSeconds>timeframe.in_seconds("1D")
        runtime.error("Recent-day windows and completed daily profiles require a chart timeframe of one day or lower. Disable daily history for higher chart timeframes.")
    if anchorMode=="Custom session" and not timeframe.isintraday
        runtime.error("Custom-session mode requires an intraday time-based chart.")
    if (anchorMode=="Trading day" and chartSeconds>=timeframe.in_seconds("1D")) or (anchorMode=="Week" and chartSeconds>=timeframe.in_seconds("1W")) or (anchorMode=="Month" and chartSeconds>=timeframe.in_seconds("1M"))
        runtime.error("Choose an anchor period strictly longer than the chart timeframe, or use Manual time.")
f_source() =>
    sourceChoice=="Close" ? close : sourceChoice=="HL2" ? hl2 : sourceChoice=="OHLC4" ? ohlc4 : hlc3
f_price(float value) =>
    na(value) ? "Unavailable" : str.tostring(value,format.mintick)
f_event(string events,bool enabled,string name) =>
    enabled ? events+(str.length(events)>0 ? " | " : "")+name : events
f_sessionKey() =>
    int sh=int(str.tonumber(str.substring(sessionHours,0,2)))
    int sm=int(str.tonumber(str.substring(sessionHours,2,4)))
    bool beforeStart=hour(time,sessionZone)*60+minute(time,sessionZone)<sh*60+sm
    timestamp(sessionZone,year(time,sessionZone),month(time,sessionZone),dayofmonth(time,sessionZone)-(beforeStart ? 1 : 0),sh,sm)
float priceSource=f_source()
bool inSession=not na(time(timeframe.period,sessionHours+":"+sessionDays,sessionZone))
bool active=anchorMode=="Custom session" ? inSession : anchorMode=="Manual time" ? time>=manualStart : true
int tradingKey=time("1D")
bool newTradingDay=na(tradingKey[1]) or tradingKey!=tradingKey[1]
int proposedKey=(anchorMode=="Trading day" or rolling) ? time("1D") : anchorMode=="Week" ? time("1W") : anchorMode=="Month" ? time("1M") : anchorMode=="Custom session" ? f_sessionKey() : manualStart
type DayStats
    int key
    float weight=0.0
    float mean=na
    float m2=0.0
    int missing=0
    int bars=0
    bool partial=false
var array<DayStats> days=array.new<DayStats>()
if newTradingDay
    DayStats d=DayStats.new(tradingKey)
    d.partial:=barstate.isfirst and time>tradingKey
    array.push(days,d)
    if array.size(days)>recentDays
        array.shift(days)
DayStats currentDay=array.get(days,array.size(days)-1)
currentDay.bars+=1
if na(volume) or volume<0 or na(priceSource)
    currentDay.missing+=1
if not na(volume) and volume>0 and not na(priceSource)
    float newWeight=currentDay.weight+volume
    float oldMean=na(currentDay.mean) ? priceSource : currentDay.mean
    float delta=priceSource-oldMean
    float updatedMean=oldMean+volume/newWeight*delta
    currentDay.m2+=volume*delta*(priceSource-updatedMean)
    currentDay.mean:=updatedMean
    currentDay.weight:=newWeight
float dayMeanNow=currentDay.mean
bool dayPartialNow=currentDay.partial
DayStats oldestStats=array.get(days,0)
int oldestDay=oldestStats.key
var int anchorKey=na
var float totalWeight=0.0
var float mean=na
var float moment2=0.0
var float previousVWAP=na
var int missingBars=0
var int anchorBars=0
var bool partialAnchor=false
bool newAnchor=active and (na(anchorKey) or proposedKey!=anchorKey)
if newAnchor
    bool initial=na(anchorKey)
    if totalWeight>0
        previousVWAP:=mean
    anchorKey:=proposedKey
    if not rolling
        totalWeight:=0
        mean:=na
        moment2:=0
        missingBars:=0
        anchorBars:=0
        partialAnchor:=initial and (anchorMode=="Manual time" ? barstate.isfirst and time>manualStart : time>proposedKey)
if rolling
    totalWeight:=0
    mean:=na
    moment2:=0
    missingBars:=0
    anchorBars:=0
    partialAnchor:=array.size(days)<recentDays or oldestStats.partial
    for i=0 to array.size(days)-1
        DayStats d=array.get(days,i)
        missingBars+=d.missing
        anchorBars+=d.bars
        if d.weight>0
            float combinedWeight=totalWeight+d.weight
            float oldMean=na(mean) ? d.mean : mean
            float delta=d.mean-oldMean
            moment2+=d.m2+delta*delta*totalWeight*d.weight/combinedWeight
            mean:=oldMean+delta*d.weight/combinedWeight
            totalWeight:=combinedWeight
else if active
    anchorBars+=1
    if na(volume) or volume<0 or na(priceSource)
        missingBars+=1
    if not na(volume) and volume>0 and not na(priceSource)
        float nextWeight=totalWeight+volume
        float oldMean=na(mean) ? priceSource : mean
        float delta=priceSource-oldMean
        float nextMean=oldMean+volume/nextWeight*delta
        moment2+=volume*delta*(priceSource-nextMean)
        mean:=nextMean
        totalWeight:=nextWeight
float deviation=totalWeight>0 ? math.sqrt(math.max(0,moment2/totalWeight)) : na
float zDistance=deviation>0 ? (close-mean)/deviation : na
bool plotActive=active and not (breakResets and newAnchor)
float plotVWAP=plotActive ? mean : na
color vwapTint=slopeColor ? (not newAnchor and not na(mean[1]) and mean<mean[1] ? bearColor : bullColor) : bullColor
pV=plot(showVWAP or (showBands and shadeBands) ? plotVWAP : na,"Anchored VWAP",color=showVWAP ? vwapTint : color.new(vwapTint,100),linewidth=2,style=plot.style_linebr,force_overlay=true)
pU1=plot(showBands and plotActive ? mean+band1*deviation : na,"Upper inner band",color=color.new(coldColor,25),style=plot.style_linebr,force_overlay=true)
pL1=plot(showBands and plotActive ? mean-band1*deviation : na,"Lower inner band",color=color.new(coldColor,25),style=plot.style_linebr,force_overlay=true)
pU2=plot(showBands and plotActive ? mean+band2*deviation : na,"Upper middle band",color=color.new(hotColor,20),style=plot.style_linebr,force_overlay=true)
pL2=plot(showBands and plotActive ? mean-band2*deviation : na,"Lower middle band",color=color.new(hotColor,20),style=plot.style_linebr,force_overlay=true)
pU3=plot(showBands and plotActive ? mean+band3*deviation : na,"Upper outer band",color=color.new(bearColor,10),style=plot.style_linebr,force_overlay=true)
pL3=plot(showBands and plotActive ? mean-band3*deviation : na,"Lower outer band",color=color.new(bearColor,10),style=plot.style_linebr,force_overlay=true)
fill(pV,pU1,color=shadeBands and showBands ? color.new(coldColor,95) : na,title="Upper inner heat")
fill(pV,pL1,color=shadeBands and showBands ? color.new(coldColor,95) : na,title="Lower inner heat")
fill(pU1,pU2,color=shadeBands and showBands ? color.new(hotColor,94) : na,title="Upper middle heat")
fill(pL1,pL2,color=shadeBands and showBands ? color.new(hotColor,94) : na,title="Lower middle heat")
fill(pU2,pU3,color=shadeBands and showBands ? color.new(bearColor,94) : na,title="Upper outer heat")
fill(pL2,pL3,color=shadeBands and showBands ? color.new(bearColor,94) : na,title="Lower outer heat")
plot(showPrevious ? previousVWAP : na,"Previous anchor/window final VWAP",color=vaColor,style=plot.style_stepline,force_overlay=true)
 
type Sample
    float hi
    float lo
    float vol
    float price
    int stamp
    bool fallback
    int tradingDay=na
 
type Buffer
    array<Sample> data
    int head=0
    int dropped=0
    int lastDroppedDay=na
var Buffer buffer=Buffer.new(array.new<Sample>())
var Buffer dayBuffer=Buffer.new(array.new<Sample>())
var int lastDailyEnd=na
var int bufferKey=na
var int lastIncludedEnd=na
f_push(Buffer b,Sample sample) =>
    if sample.vol>0 and not na(sample.price) and not na(sample.hi) and not na(sample.lo)
        if array.size(b.data)<sampleLimit
            array.push(b.data,sample)
            true
        else
            Sample removed=array.get(b.data,b.head)
            b.lastDroppedDay:=removed.tradingDay
            array.set(b.data,b.head,sample)
            b.head:=(b.head+1)%sampleLimit
            b.dropped+=1
            true
    true
// Uniform range allocation uses two partial bins plus a difference array for full bins.
// Complexity is O(samples + rows), rather than a samples-by-rows nested scan.
f_build(Buffer b,float reference,int requestedRows) =>
    float lowest=na
    float highest=na
    int earliest=na
    int fallbacks=0
    if array.size(b.data)>0
        for i=0 to array.size(b.data)-1
            Sample s=array.get(b.data,i)
            lowest:=na(lowest) ? s.lo : math.min(lowest,s.lo)
            highest:=na(highest) ? s.hi : math.max(highest,s.hi)
            earliest:=na(earliest) ? s.stamp : math.min(earliest,s.stamp)
            fallbacks+=s.fallback ? 1 : 0
    float bottom=na(lowest) ? na : math.floor(lowest/syminfo.mintick)*syminfo.mintick
    float rangeTicks=na(lowest) ? 1.0 : math.max(1,math.ceil((highest-bottom)/syminfo.mintick-0.0000001))
    float ticksPerRow=math.max(1,math.ceil(rangeTicks/requestedRows))
    int rows=int(math.max(1,math.min(requestedRows,math.ceil(rangeTicks/ticksPerRow))))
    float step=ticksPerRow*syminfo.mintick
    array<float> bins=array.new<float>(rows,0.0)
    array<float> diff=array.new<float>(rows+1,0.0)
    if array.size(b.data)>0
        for i=0 to array.size(b.data)-1
            Sample s=array.get(b.data,i)
            int first=int(math.max(0,math.min(rows-1,math.floor((s.lo-bottom)/step))))
            int last=int(math.max(0,math.min(rows-1,math.floor((s.hi-bottom)/step))))
            if allocation=="Selected source price" or s.hi<=s.lo
                int slot=int(math.max(0,math.min(rows-1,math.floor((s.price-bottom)/step))))
                array.set(bins,slot,array.get(bins,slot)+s.vol)
            else if first==last
                array.set(bins,first,array.get(bins,first)+s.vol)
            else
                float density=s.vol/(s.hi-s.lo)
                float firstPart=math.max(0,math.min(s.hi,bottom+(first+1)*step)-s.lo)*density
                float lastPart=math.max(0,s.hi-math.max(s.lo,bottom+last*step))*density
                array.set(bins,first,array.get(bins,first)+firstPart)
                array.set(bins,last,array.get(bins,last)+lastPart)
                if last>first+1
                    float full=density*step
                    array.set(diff,first+1,array.get(diff,first+1)+full)
                    array.set(diff,last,array.get(diff,last)-full)
    float running=0
    float total=0
    float peak=-1
    int pocIndex=0
    float nearest=1e100
    float tieReference=na(reference) ? bottom+rows*step/2 : reference
    for i=0 to rows-1
        running+=array.get(diff,i)
        float v=math.max(0,array.get(bins,i)+running)
        array.set(bins,i,v)
        total+=v
        float distance=math.abs(bottom+(i+0.5)*step-tieReference)
        if v>peak or (v==peak and distance<nearest)
            peak:=v
            pocIndex:=i
            nearest:=distance
    int lower=pocIndex
    int upper=pocIndex
    float covered=array.get(bins,pocIndex)
    float target=total*valuePercent/100
    while covered<target and (lower>0 or upper<rows-1)
        float down=lower>0 ? array.get(bins,lower-1) : -1.0
        float up=upper<rows-1 ? array.get(bins,upper+1) : -1.0
        if up<0 or down>up
            lower-=1
            covered+=array.get(bins,lower)
        else if down<0 or up>down
            upper+=1
            covered+=array.get(bins,upper)
        else
            lower-=1
            upper+=1
            covered+=array.get(bins,lower)+array.get(bins,upper)
    float poc=total>0 ? bottom+(pocIndex+0.5)*step : na
    float val=total>0 ? bottom+lower*step : na
    float vah=total>0 ? bottom+(upper+1)*step : na
    [bins,bottom,step,total,peak,poc,val,vah,pocIndex,lower,upper,earliest,fallbacks]
 
// Prune by trading-day identity, not calendar-hour subtraction. Preserve chronological order.
f_prune(Buffer b,int oldest) =>
    array<Sample> kept=array.new<Sample>()
    int count=array.size(b.data)
    int first=count<sampleLimit ? 0 : b.head
    if count>0
        for j=0 to count-1
            Sample sample=array.get(b.data,(first+j)%count)
            if sample.tradingDay>=oldest
                array.push(kept,sample)
    b.data:=kept
    b.head:=0
    if na(b.lastDroppedDay) or b.lastDroppedDay<oldest
        b.dropped:=0
    true
f_ingest(Sample sample) =>
    sample.tradingDay:=tradingKey
    if active
        f_push(buffer,sample)
    if saveDaily
        f_push(dayBuffer,sample)
    true
 
type SavedDay
    array<box> areas
    array<line> levels
    label tag=na
var array<SavedDay> saved=array.new<SavedDay>()
f_deleteDay(SavedDay d) =>
    if array.size(d.areas)>0
        for i=0 to array.size(d.areas)-1
            box.delete(array.get(d.areas,i))
    if array.size(d.levels)>0
        for i=0 to array.size(d.levels)-1
            line.delete(array.get(d.levels,i))
    if not na(d.tag)
        label.delete(d.tag)
    true
int layers=dailyDisplay=="Profile + heatmap" ? 2 : 1
// Reserve two full current-profile row layers, plus safety room below 500 boxes.
int effectiveSavedRows=int(math.max(1,math.min(savedRows,math.floor((480-2*rowCount)/(savedDays*layers)))))
f_archive(Buffer b,float dailyMean,int finish,int key,bool partialDay) =>
    // Delete the oldest before creating the next day to avoid transient object overflow.
    while array.size(saved)>=savedDays
        f_deleteDay(array.shift(saved))
    [bins,bottom,step,total,peak,dpoc,dval,dvah,pi,vl,vu,start,fallbacks]=f_build(b,dailyMean,effectiveSavedRows)
    if total>0
        SavedDay d=SavedDay.new(array.new<box>(),array.new<line>())
        int duration=int(math.max(1,finish-start))
        int maxWidth=int(math.max(1,duration*dailyWidth/100))
        for i=0 to array.size(bins)-1
            float v=array.get(bins,i)
            if v>0
                float top=bottom+(i+1)*step
                float rowBottom=bottom+i*step
                float intensity=math.pow(v/peak,heatContrast)
                color tint=i==pi ? pocColor : color.from_gradient(intensity,0,1,coldColor,hotColor)
                if dailyDisplay!="Profile only"
                    array.push(d.areas,box.new(start,top,finish,rowBottom,xloc=xloc.bar_time,border_color=color.new(tint,100),bgcolor=color.new(tint,int(math.round(98-8*intensity))),force_overlay=true))
                if dailyDisplay!="Heatmap only"
                    int width=int(math.max(1,maxWidth*v/peak))
                    array.push(d.areas,box.new(finish-width,top,finish,rowBottom,xloc=xloc.bar_time,border_color=color.new(tint,100),bgcolor=color.new(tint,i>=vl and i<=vu ? 45 : 75),force_overlay=true))
        if dailyLevels
            array.push(d.levels,line.new(start,dpoc,finish,dpoc,xloc=xloc.bar_time,color=color.new(pocColor,20),force_overlay=true))
            array.push(d.levels,line.new(start,dvah,finish,dvah,xloc=xloc.bar_time,color=color.new(vaColor,40),style=line.style_dashed,force_overlay=true))
            array.push(d.levels,line.new(start,dval,finish,dval,xloc=xloc.bar_time,color=color.new(vaColor,40),style=line.style_dashed,force_overlay=true))
        if dailyVWAP and not na(dailyMean)
            array.push(d.levels,line.new(start,dailyMean,finish,dailyMean,xloc=xloc.bar_time,color=color.new(bullColor,20),style=line.style_dotted,force_overlay=true))
        if dailyTags
            string caption=str.format_time(key,"MMM dd",syminfo.timezone)+" · DAILY"+(partialDay ? " · partial" : "")+(b.dropped>0 ? " · capped" : "")
            d.tag:=label.new(finish,dpoc,caption,xloc=xloc.bar_time,style=label.style_label_lower_right,color=panelBG,textcolor=pocColor,size=font,tooltip="Completed daily profile estimate. Dates use the symbol's trading-day opening timestamp.\nPOC: "+f_price(dpoc)+"\nVA: "+f_price(dval)+" – "+f_price(dvah)+"\nFinal full-day chart-source VWAP: "+f_price(dailyMean)+"\nRows: "+str.tostring(array.size(bins))+"\nFallback samples: "+str.tostring(fallbacks)+"\nThis completed-day snapshot was only knowable at the day rollover, not at earlier candles.",force_overlay=true)
        array.push(saved,d)
    true
 
if barstate.isconfirmed and newTradingDay
    if saveDaily and array.size(dayBuffer.data)>0 and not na(lastDailyEnd)
        f_archive(dayBuffer,dayMeanNow[1],lastDailyEnd,tradingKey[1],dayPartialNow[1])
    array.clear(dayBuffer.data)
    dayBuffer.head:=0
    dayBuffer.dropped:=0
    dayBuffer.lastDroppedDay:=na
    lastDailyEnd:=na
if barstate.isconfirmed and newAnchor
    bufferKey:=anchorKey
    if rolling
        f_prune(buffer,oldestDay)
    else
        lastIncludedEnd:=na
        array.clear(buffer.data)
        buffer.head:=0
        buffer.dropped:=0
        buffer.lastDroppedDay:=na
if barstate.isconfirmed and active
    lastIncludedEnd:=na(time_close) ? time : time_close
if barstate.isconfirmed and saveDaily
    lastDailyEnd:=na(time_close) ? time : time_close
if useLower and lowerValid
    [hs,ls,vs,ps,ts]=request.security_lower_tf(syminfo.tickerid,lowerTF,[high,low,volume,f_source(),time])
    if barstate.isconfirmed and (active or saveDaily)
        float usable=0
        if array.size(vs)>0
            for i=0 to array.size(vs)-1
                float v=array.get(vs,i)
                if not na(v) and v>0
                    usable+=v
                    f_ingest(Sample.new(array.get(hs,i),array.get(ls,i),v,array.get(ps,i),array.get(ts,i),false))
        if usable<=0 and not na(volume) and volume>0
            f_ingest(Sample.new(high,low,volume,priceSource,time,true))
else if barstate.isconfirmed and (active or saveDaily) and not na(volume) and volume>0
    f_ingest(Sample.new(high,low,volume,priceSource,time,false))
 
var array<float> snapshotBins=array.new<float>()
var float profileBottom=na
var float profileStep=na
var float profileTotal=na
var float profilePeak=na
var float poc=na
var float val=na
var float vah=na
var int pocIndex=na
var int vaLower=na
var int vaUpper=na
var int profileStart=na
var int profileEnd=na
var int profileKey=na
var int profileBar=na
var int fallbackSamples=0
var bool snapshotCapped=false
bool sameAnchor=active and active[1] and not newAnchor and anchorKey==anchorKey[1]
bool vwapUp=barstate.isconfirmed and sameAnchor and not na(mean[1]) and close>mean and close[1]<=mean[1]
bool vwapDown=barstate.isconfirmed and sameAnchor and not na(mean[1]) and close<mean and close[1]>=mean[1]
bool bandComparable=sameAnchor and deviation>0 and deviation[1]>0
bool outerUp=barstate.isconfirmed and bandComparable and close>mean+band3*deviation and close[1]<=mean[1]+band3*deviation[1]
bool outerDown=barstate.isconfirmed and bandComparable and close<mean-band3*deviation and close[1]>=mean[1]-band3*deviation[1]
bool returnUpper=barstate.isconfirmed and bandComparable and close<mean+band2*deviation and close[1]>=mean[1]+band2*deviation[1]
bool returnLower=barstate.isconfirmed and bandComparable and close>mean-band2*deviation and close[1]<=mean[1]-band2*deviation[1]
// Compare with previous closed snapshot BEFORE replacing its levels.
float alertPOC=poc
float alertVAL=val
float alertVAH=vah
bool priorSnapshot=barstate.isconfirmed and active and not newAnchor and profileKey==anchorKey and not na(profileBar) and profileBar==bar_index-1 and not na(poc)
bool pocUp=priorSnapshot and close>poc and close[1]<=poc
bool pocDown=priorSnapshot and close<poc and close[1]>=poc
bool vaInsideBefore=not na(val) and close[1]>=val and close[1]<=vah
bool vaInsideNow=not na(val) and close>=val and close<=vah
bool valueEnter=priorSnapshot and not vaInsideBefore and vaInsideNow
bool valueExit=priorSnapshot and vaInsideBefore and not vaInsideNow
bool rebuild=barstate.islastconfirmedhistory or (barstate.islast and barstate.isconfirmed)
if rebuild and bufferKey==anchorKey and array.size(buffer.data)>0 and (active or holdOutside)
    [bins,bottom,step,total,peak,newPOC,newVAL,newVAH,pi,vl,vu,start,fallbacks]=f_build(buffer,mean,rowCount)
    snapshotBins:=bins
    profileBottom:=bottom
    profileStep:=step
    profileTotal:=total
    profilePeak:=peak
    poc:=newPOC
    val:=newVAL
    vah:=newVAH
    pocIndex:=pi
    vaLower:=vl
    vaUpper:=vu
    profileStart:=start
    profileEnd:=lastIncludedEnd
    profileKey:=anchorKey
    profileBar:=bar_index
    fallbackSamples:=fallbacks
    snapshotCapped:=buffer.dropped>0
 
var array<box> profileBoxes=array.new<box>(120,na)
var array<box> heatBoxes=array.new<box>(120,na)
var array<line> levelLines=array.new<line>(3,na)
var array<label> levelTags=array.new<label>(4,na)
bool profileReady=profileKey==anchorKey and profileTotal>0 and (active or holdOutside)
if barstate.islast
    int rightEdge=bar_index+profileOffset+profileWidth
    int heatStart=saveDaily and limitCurrentHeat and dailyDisplay!="Profile only" ? math.max(profileStart,tradingKey) : profileStart
    for i=0 to 119
        box histogram=array.get(profileBoxes,i)
        box heat=array.get(heatBoxes,i)
        bool rowReady=profileReady and i<array.size(snapshotBins)
        float rowVol=rowReady ? array.get(snapshotBins,i) : 0.0
        if rowReady and rowVol>0
            float top=profileBottom+(i+1)*profileStep
            float bottom=profileBottom+i*profileStep
            float intensity=math.pow(rowVol/profilePeak,heatContrast)
            color tint=i==pocIndex ? pocColor : color.from_gradient(intensity,0,1,coldColor,hotColor)
            bool inVA=i>=vaLower and i<=vaUpper
            if showProfile
                int width=int(math.max(1,math.round(profileWidth*rowVol/profilePeak)))
                if na(histogram)
                    histogram:=box.new(rightEdge-width,top,rightEdge,bottom,border_color=color.new(tint,100),bgcolor=tint,force_overlay=true)
                    array.set(profileBoxes,i,histogram)
                box.set_left(histogram,rightEdge-width)
                box.set_right(histogram,rightEdge)
                box.set_top(histogram,top)
                box.set_bottom(histogram,bottom)
                box.set_bgcolor(histogram,color.new(tint,inVA ? 25 : 65))
            else if not na(histogram)
                box.delete(histogram)
                array.set(profileBoxes,i,na)
            if showHeatmap and heatStart<profileEnd
                if na(heat)
                    heat:=box.new(heatStart,top,profileEnd,bottom,xloc=xloc.bar_time,border_color=color.new(tint,100),bgcolor=tint,force_overlay=true)
                    array.set(heatBoxes,i,heat)
                box.set_left(heat,heatStart)
                box.set_right(heat,profileEnd)
                box.set_top(heat,top)
                box.set_bottom(heat,bottom)
                box.set_bgcolor(heat,color.new(tint,int(math.round(98-8*intensity))))
            else if not na(heat)
                box.delete(heat)
                array.set(heatBoxes,i,na)
        else
            if not na(histogram)
                box.delete(histogram)
                array.set(profileBoxes,i,na)
            if not na(heat)
                box.delete(heat)
                array.set(heatBoxes,i,na)
    array<float> prices=array.from(poc,vah,val,mean)
    array<string> captions=array.from(rolling ? str.tostring(recentDays)+"D POC ≈" : "POC ≈",rolling ? str.tostring(recentDays)+"D VAH ≈" : "VAH ≈",rolling ? str.tostring(recentDays)+"D VAL ≈" : "VAL ≈",rolling ? str.tostring(recentDays)+"D VWAP" : active ? "VWAP" : "VWAP · held")
    for i=0 to 3
        float price=array.get(prices,i)
        color tint=i==0 ? pocColor : i==3 ? vwapTint : vaColor
        bool visible=i==3 ? showVWAP and totalWeight>0 and (active or holdOutside) : profileReady and showLevels
        if i<3
            line level=array.get(levelLines,i)
            if visible
                int endTime=time+int(chartSeconds*1000)*(profileOffset+profileWidth)
                if na(level)
                    level:=line.new(profileStart,price,endTime,price,xloc=xloc.bar_time,color=tint,style=i==0 ? line.style_solid : line.style_dashed,width=i==0 ? 2 : 1,force_overlay=true)
                    array.set(levelLines,i,level)
                line.set_xy1(level,profileStart,price)
                line.set_xy2(level,endTime,price)
            else if not na(level)
                line.delete(level)
                array.set(levelLines,i,na)
        label tag=array.get(levelTags,i)
        if visible and showLabels
            if na(tag)
                tag:=label.new(rightEdge+3,price,"",style=label.style_label_left,color=panelBG,textcolor=tint,size=font,force_overlay=true)
                array.set(levelTags,i,tag)
            label.set_xy(tag,rightEdge+3,price)
            label.set_text(tag,array.get(captions,i)+" "+f_price(price))
            label.set_textcolor(tag,tint)
            label.set_tooltip(tag,i==3 ? "VWAP covers the full selected anchor or recent-day window using chart source prices weighted by chart volume. Bands are weighted population deviation of those source observations." : "Estimated volume profile from retained candle samples. Profile rows/levels refresh at chart close. If capped, its range is shorter than full-anchor VWAP.")
        else if not na(tag)
            label.delete(tag)
            array.set(levelTags,i,na)
 
string panelPosition=panelCorner=="Top Left" ? position.top_left : panelCorner=="Bottom Left" ? position.bottom_left : panelCorner=="Bottom Right" ? position.bottom_right : position.top_right
var table panel=table.new(panelPosition,2,17,bgcolor=panelBG,frame_color=color.gray,frame_width=1)
if barstate.islast
    if panelSize!="Hidden"
        string panelFont=panelSize=="Large" ? size.large : panelSize=="Medium" ? size.normal : size.small
        string state=not active ? (anchorMode=="Manual time" ? "Before manual anchor" : holdOutside ? "Outside session · held" : "Outside session · hidden") : totalWeight<=0 ? "No usable chart-volume VWAP" : not profileReady ? "Waiting for first profile close" : "Live VWAP · closed profile"
        string coverage=not profileReady ? "Awaiting current anchor profile" : snapshotCapped ? "CAPPED · VWAP has wider scope" : partialAnchor ? (rolling ? "Fewer days / partial first day" : "Loaded mid-anchor") : "Within anchor / sample cap"
        string positionText=not profileReady ? "—" : close>vah ? "Above value area" : close<val ? "Below value area" : "Inside value area"
        array<string> keys=array.from("[CandleChasers]","State","Anchor / source","VWAP","Weighted deviation","Price distance / σ","POC estimate","Value area estimate","Price / value area","Profile sampling","Retained samples / rows","Coverage","Fallback samples","Missing-volume bars","Method","Rolling window","Saved days / rows")
        array<string> values=array.from("VWAP HEATMAP PROFILE 1.1",state,(rolling ? "Recent "+str.tostring(recentDays)+" trading days" : anchorMode)+" / "+sourceChoice,f_price(mean),f_price(deviation),na(zDistance) ? "Unavailable" : str.tostring(zDistance,"#.##"),profileReady ? f_price(poc) : "—",profileReady ? f_price(val)+" – "+f_price(vah) : "—",positionText,useLower ? lowerTF+" lower TF" : "Chart candles",str.tostring(bufferKey==anchorKey ? array.size(buffer.data) : 0)+" / "+(profileReady ? str.tostring(array.size(snapshotBins)) : "—"),coverage,profileReady ? str.tostring(fallbackSamples) : "—",str.tostring(missingBars),"Estimated VAP · no bid/ask delta",rolling ? str.tostring(array.size(days))+" / "+str.tostring(recentDays)+" observed days" : "Off",saveDaily ? str.tostring(array.size(saved))+" / "+str.tostring(effectiveSavedRows) : "Off")
        for row=0 to 16
            table.cell(panel,0,row,array.get(keys,row),bgcolor=panelBG,text_color=color.rgb(205,213,225),text_size=panelFont)
            table.cell(panel,1,row,array.get(values,row),bgcolor=panelBG,text_color=row==11 and profileReady and snapshotCapped ? pocColor : color.white,text_size=panelFont)
    else
        table.clear(panel,0,0,1,16)
if barstate.isconfirmed
    string events=""
    events:=f_event(events,alertVWAP and vwapUp,"VWAP_CROSS_UP")
    events:=f_event(events,alertVWAP and vwapDown,"VWAP_CROSS_DOWN")
    events:=f_event(events,alertBand and outerUp,"OUTER_BAND_BREAK_UP")
    events:=f_event(events,alertBand and outerDown,"OUTER_BAND_BREAK_DOWN")
    events:=f_event(events,alertBand and returnUpper,"RETURN_BELOW_UPPER_MIDDLE_BAND")
    events:=f_event(events,alertBand and returnLower,"RETURN_ABOVE_LOWER_MIDDLE_BAND")
    events:=f_event(events,alertProfile and pocUp,"PRIOR_POC_CROSS_UP")
    events:=f_event(events,alertProfile and pocDown,"PRIOR_POC_CROSS_DOWN")
    events:=f_event(events,alertProfile and valueEnter,"ENTER_PRIOR_VALUE_AREA")
    events:=f_event(events,alertProfile and valueExit,"EXIT_PRIOR_VALUE_AREA")
    if str.length(events)>0
        string snapshotDetails=(alertProfile and (pocUp or pocDown or valueEnter or valueExit)) ? " | Prior POC="+f_price(alertPOC)+" | Prior VA="+f_price(alertVAL)+"–"+f_price(alertVAH) : ""
        alert("[CandleChasers] "+syminfo.tickerid+" "+timeframe.period+" | "+events+" | Anchor="+anchorMode+" | VWAP="+f_price(mean)+snapshotDetails+" | Profile levels are estimated; profile events used previous closed snapshot.",alert.freq_once_per_bar_close)
alertcondition(alertVWAP and vwapUp,"VWAP cross up","[CandleChasers] Close crossed above anchored VWAP on {{ticker}} {{interval}}.")
alertcondition(alertVWAP and vwapDown,"VWAP cross down","[CandleChasers] Close crossed below anchored VWAP on {{ticker}} {{interval}}.")
alertcondition(alertBand and outerUp,"Upper outer-band break","[CandleChasers] Close moved above the outer deviation band on {{ticker}} {{interval}}.")
alertcondition(alertBand and outerDown,"Lower outer-band break","[CandleChasers] Close moved below the outer deviation band on {{ticker}} {{interval}}.")
alertcondition(alertBand and (returnUpper or returnLower),"Return through middle band","[CandleChasers] Close returned through a middle deviation boundary on {{ticker}} {{interval}}.")
alertcondition(alertProfile and (pocUp or pocDown),"Prior POC cross","[CandleChasers] Close crossed the previous closed estimated POC on {{ticker}} {{interval}}.")
alertcondition(alertProfile and valueEnter,"Enter prior value area","[CandleChasers] Close entered the previous closed estimated value area on {{ticker}} {{interval}}.")
alertcondition(alertProfile and valueExit,"Exit prior value area","[CandleChasers] Close exited the previous closed estimated value area on {{ticker}} {{interval}}.")

← 返回列表