Session Volume Profile + HVN [DAVIES T]

DAVIES_T · study · 338 行 · 点赞 66 · TradingView 原页

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

Pine Script

//@version=6
indicator("Session Volume Profile + HVN [DAVIES T]", "SVP+HVN", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count=500)
 
// ---------- Inputs ----------
grpS = "Session"
sessMode = input.string("NY RTH", "Session", options=["NY RTH", "London", "Asia", "Full Day", "Custom"], group=grpS, tooltip="NY RTH 09:30-16:00, London 02:00-05:00, Asia 20:00-00:00 (all in the timezone below). Full Day resets on calendar day change - works on 24/7 crypto.")
custSess = input.session("0930-1600", "Custom Session", group=grpS)
tz       = input.string("America/New_York", "Timezone", group=grpS)
showLast = input.int(3, "Sessions with Full Profile", minval=0, maxval=10, group=grpS)
showLive = input.bool(true, "Show Live Session", group=grpS)
 
grpP = "Profile"
resTF    = input.timeframe("1", "Resolution Timeframe", group=grpP, tooltip="Lower timeframe data used to build the profile (more accurate POC/HVN). If it is not lower than the chart timeframe, or no intrabar data exists for older bars, chart bars are used.")
rows     = input.int(40, "Rows", minval=10, maxval=100, group=grpP)
widthPct = input.int(30, "Histogram Width % of Session", minval=5, maxval=100, group=grpP)
vaPct    = input.float(70, "Value Area %", minval=10, maxval=95, group=grpP)
showHist = input.bool(true, "Show Histogram", group=grpP)
showVA   = input.bool(true, "Show VAH / VAL Lines", group=grpP)
 
grpH = "HVN / POC"
showHVN  = input.bool(true, "Show HVN", group=grpH)
hvnThr   = input.float(60, "HVN Min % of POC Volume", minval=10, maxval=100, group=grpH)
hvnSpan  = input.int(2, "HVN Peak Lookaround (rows)", minval=1, maxval=10, group=grpH, tooltip="A row is an HVN only if its volume beats this many rows above and below it.")
hvnMax   = input.int(4, "Max HVNs per Session", minval=1, maxval=10, group=grpH)
extN     = input.int(3, "Extend Last N Sessions POC / HVN", minval=0, maxval=10, group=grpH, tooltip="POC and HVN lines of the last N completed sessions extend right. Sessions older than the full-profile count keep only these lines.")
 
grpC = "Colours"
cVA   = input.color(color.new(#2962FF, 60), "Value Area Rows", group=grpC)
cOut  = input.color(color.new(#787B86, 75), "Outside VA Rows", group=grpC)
cPOC  = input.color(#FFD600, "POC", group=grpC)
cHVN  = input.color(#00E676, "HVN", group=grpC)
cVAL  = input.color(#2962FF, "VAH / VAL Lines", group=grpC)
 
grpL = "PDH/PDL + PWH/PWL"
showPD = input.bool(true, "Show PDH / PDL", group=grpL)
showPW = input.bool(true, "Show PWH / PWL", group=grpL)
lvlTz  = input.string("America/New_York", "Day / Week Timezone", group=grpL, tooltip="Midnight in this timezone starts a new day, Monday starts a new week. Use UTC to match exchange daily/weekly candles on crypto.")
cPD    = input.color(#FF5252, "PDH / PDL", group=grpL)
cPW    = input.color(#E040FB, "PWH / PWL", group=grpL)
 
// ---------- Session detection ----------
sessStr = switch sessMode
    "NY RTH" => "0930-1600"
    "London" => "0200-0500"
    "Asia"   => "2000-0000"
    => custSess
 
isFull  = sessMode == "Full Day"
dayKey  = year(time, tz) * 10000 + month(time, tz) * 100 + dayofmonth(time, tz)
dayChg  = bar_index == 0 or dayKey != nz(dayKey[1])
inSess  = isFull ? true : not na(time(timeframe.period, sessStr, tz))
newSess = isFull ? dayChg : (inSess and not inSess[1])
sessEnd = inSess[1] and (not inSess or newSess)
 
// ---------- Lower timeframe data ----------
ltfOK = timeframe.in_seconds(resTF) < timeframe.in_seconds()
resEff = ltfOK ? resTF : timeframe.period
[lH, lL, lV] = request.security_lower_tf(syminfo.tickerid, resEff, [high, low, volume])
 
// ---------- Drawing groups ----------
type Group
    array<box>   bx
    array<line>  ln
    array<label> lb
    array<line>  ex
    array<label> exl
    int          tEnd
 
newGroup(int t1) =>
    Group.new(array.new<box>(), array.new<line>(), array.new<label>(), array.new<line>(), array.new<label>(), t1)
 
clearVis(Group g) =>
    for b in g.bx
        b.delete()
    for l in g.ln
        l.delete()
    for t in g.lb
        t.delete()
    g.bx.clear()
    g.ln.clear()
    g.lb.clear()
 
clearGroup(Group g) =>
    clearVis(g)
    for l in g.ex
        l.delete()
    for t in g.exl
        t.delete()
    g.ex.clear()
    g.exl.clear()
 
// ---------- Profile maths ----------
// Spreads each bar's volume across the rows its high-low range overlaps
calcProfile(array<float> hs, array<float> ls, array<float> vs, int n) =>
    float top  = hs.max()
    float bot  = ls.min()
    float step = math.max((top - bot) / n, syminfo.mintick)
    array<float> rv = array.new<float>(n, 0.0)
    int sz = vs.size()
    if sz > 0
        for i = 0 to sz - 1
            float h = hs.get(i)
            float l = ls.get(i)
            float v = vs.get(i)
            int r0 = math.max(0, math.min(n - 1, int(math.floor((l - bot) / step))))
            int r1 = math.max(0, math.min(n - 1, int(math.floor((h - bot) / step))))
            if h <= l
                rv.set(r0, rv.get(r0) + v)
            else
                for r = r0 to r1
                    float rb = bot + r * step
                    float ov = math.min(h, rb + step) - math.max(l, rb)
                    if ov > 0
                        rv.set(r, rv.get(r) + v * ov / (h - l))
    [rv, bot, step]
 
calcVA(array<float> rv, float pct) =>
    int   n   = rv.size()
    float tot = rv.sum()
    float mx  = rv.max()
    int   poc = rv.indexof(mx)
    int   up  = poc
    int   dn  = poc
    float acc = mx
    while acc < tot * pct / 100 and (up < n - 1 or dn > 0)
        float vu = up < n - 1 ? rv.get(up + 1) : -1.0
        float vd = dn > 0 ? rv.get(dn - 1) : -1.0
        if vu >= vd
            up  += 1
            acc += vu
        else
            dn  -= 1
            acc += vd
    [poc, up, dn]
 
// HVN = local volume peak (beats hvnSpan rows each side) above a % of POC volume
calcHVN(array<float> rv, int poc, float thr, int span, int maxN) =>
    int n = rv.size()
    float mx = rv.get(poc)
    array<int>   idx = array.new<int>()
    array<float> vol = array.new<float>()
    for i = 0 to n - 1
        float v = rv.get(i)
        if i != poc and v >= mx * thr / 100
            bool peak = true
            for k = 1 to span
                if i - k >= 0 and rv.get(i - k) >= v
                    peak := false
                if i + k < n and rv.get(i + k) > v
                    peak := false
            if peak
                idx.push(i)
                vol.push(v)
    while idx.size() > maxN
        int m = vol.indexof(vol.min())
        idx.remove(m)
        vol.remove(m)
    idx
 
drawProfile(Group g, int t0, int t1, array<float> rv, float bot, float step, int poc, int up, int dn, array<int> hv) =>
    float mx   = rv.get(poc)
    int   span = t1 - t0
    int   n    = rv.size()
    if showHist
        for i = 0 to n - 1
            float v = rv.get(i)
            if v > 0
                int w = math.max(1, int(span * widthPct / 100.0 * v / mx))
                color c = i == poc ? color.new(cPOC, 40) : (showHVN and hv.includes(i)) ? color.new(cHVN, 50) : (i >= dn and i <= up) ? cVA : cOut
                g.bx.push(box.new(t0, bot + (i + 1) * step, t0 + w, bot + i * step, xloc=xloc.bar_time, border_width=0, bgcolor=c))
    float pocP = bot + (poc + 0.5) * step
    g.ex.push(line.new(t0, pocP, t1, pocP, xloc=xloc.bar_time, color=cPOC, width=2))
    g.exl.push(label.new(t1, pocP, "POC " + str.tostring(pocP, format.mintick), xloc=xloc.bar_time, style=label.style_label_left, color=color.new(cPOC, 100), textcolor=cPOC, size=size.small))
    if showVA
        float vah = bot + (up + 1) * step
        float val = bot + dn * step
        g.ln.push(line.new(t0, vah, t1, vah, xloc=xloc.bar_time, color=cVAL, style=line.style_dashed))
        g.ln.push(line.new(t0, val, t1, val, xloc=xloc.bar_time, color=cVAL, style=line.style_dashed))
        g.lb.push(label.new(t1, vah, "VAH", xloc=xloc.bar_time, style=label.style_label_left, color=color.new(cVAL, 100), textcolor=cVAL, size=size.tiny))
        g.lb.push(label.new(t1, val, "VAL", xloc=xloc.bar_time, style=label.style_label_left, color=color.new(cVAL, 100), textcolor=cVAL, size=size.tiny))
    if showHVN
        for i in hv
            float p = bot + (i + 0.5) * step
            g.ex.push(line.new(t0, p, t1, p, xloc=xloc.bar_time, color=cHVN, style=line.style_dotted, width=2))
            g.exl.push(label.new(t1, p, "HVN " + str.tostring(p, format.mintick), xloc=xloc.bar_time, style=label.style_label_left, color=color.new(cHVN, 100), textcolor=cHVN, size=size.small))
 
// ---------- State ----------
var array<float> aH = array.new<float>()
var array<float> aL = array.new<float>()
var array<float> aV = array.new<float>()
var int sStart = na
var int sClose = na
var array<Group> hist  = array.new<Group>()
var Group        liveG = newGroup(0)
var array<float> lastHVN = array.new<float>()
var float        lastPOC = na
 
// Keeps full profiles for the last showLast sessions, POC/HVN lines for the last extN
manageHist() =>
    int keep = math.max(showLast, extN)
    while hist.size() > keep
        clearGroup(hist.shift())
    int n = hist.size()
    if n > 0
        for j = 0 to n - 1
            Group g = hist.get(j)
            int age = n - 1 - j
            if age >= showLast
                clearVis(g)
            for l in g.ex
                l.set_extend(age < extN ? extend.right : extend.none)
            if age >= extN
                for t in g.exl
                    t.set_x(g.tEnd)
 
// ---------- Completed session ----------
if sessEnd and aV.size() > 0 and aV.sum() > 0
    [rv, bot, step] = calcProfile(aH, aL, aV, rows)
    [poc, up, dn]   = calcVA(rv, vaPct)
    hv = calcHVN(rv, poc, hvnThr, hvnSpan, hvnMax)
    lastPOC := bot + (poc + 0.5) * step
    lastHVN.clear()
    for i in hv
        lastHVN.push(bot + (i + 0.5) * step)
    if math.max(showLast, extN) > 0
        Group g = newGroup(sClose)
        drawProfile(g, sStart, sClose, rv, bot, step, poc, up, dn, hv)
        hist.push(g)
        manageHist()
 
if sessEnd
    aH.clear()
    aL.clear()
    aV.clear()
 
// ---------- Collect current session ----------
if inSess
    if newSess or na(sStart)
        aH.clear()
        aL.clear()
        aV.clear()
        sStart := time
    if lV.size() > 0
        for i = 0 to lV.size() - 1
            aH.push(lH.get(i))
            aL.push(lL.get(i))
            aV.push(nz(lV.get(i)))
    else
        aH.push(high)
        aL.push(low)
        aV.push(nz(volume))
    sClose := time_close
 
// ---------- Live session + extended label position ----------
if barstate.islast
    clearGroup(liveG)
    if showLive and inSess and aV.size() > 0 and aV.sum() > 0
        [rvL, botL, stepL] = calcProfile(aH, aL, aV, rows)
        [pocL, upL, dnL]   = calcVA(rvL, vaPct)
        hvL = calcHVN(rvL, pocL, hvnThr, hvnSpan, hvnMax)
        drawProfile(liveG, sStart, sClose, rvL, botL, stepL, pocL, upL, dnL, hvL)
    int n = hist.size()
    if n > 0
        int xr = time + 3 * timeframe.in_seconds() * 1000
        for j = 0 to n - 1
            if n - 1 - j < extN
                for t in hist.get(j).exl
                    t.set_x(xr)
 
// ---------- PDH/PDL + PWH/PWL ----------
lKey  = year(time, lvlTz) * 10000 + month(time, lvlTz) * 100 + dayofmonth(time, lvlTz)
lDay  = bar_index == 0 or lKey != nz(lKey[1])
mDow  = (dayofweek(time, lvlTz) + 5) % 7
lWeek = bar_index == 0 or (lDay and mDow < nz(mDow[1]))
 
type Lvl
    float curH
    float curL
    int   curHT
    int   curLT
    float pH
    float pL
    line  hl
    line  ll
    label hb
    label lbb
 
// Tracks the running period high/low; on reset draws the completed period's H/L from where it formed
trackLvl(Lvl s, bool reset, bool show, color c, string hTag, string lTag) =>
    if reset
        if not na(s.curH)
            s.pH := s.curH
            s.pL := s.curL
            line.delete(s.hl)
            line.delete(s.ll)
            label.delete(s.hb)
            label.delete(s.lbb)
            if show
                s.hl  := line.new(s.curHT, s.curH, time, s.curH, xloc=xloc.bar_time, extend=extend.right, color=c, width=1)
                s.ll  := line.new(s.curLT, s.curL, time, s.curL, xloc=xloc.bar_time, extend=extend.right, color=c, width=1)
                s.hb  := label.new(time, s.curH, hTag + " " + str.tostring(s.curH, format.mintick), xloc=xloc.bar_time, style=label.style_label_left, color=color.new(c, 100), textcolor=c, size=size.small)
                s.lbb := label.new(time, s.curL, lTag + " " + str.tostring(s.curL, format.mintick), xloc=xloc.bar_time, style=label.style_label_left, color=color.new(c, 100), textcolor=c, size=size.small)
        s.curH  := high
        s.curL  := low
        s.curHT := time
        s.curLT := time
    else
        if high > s.curH
            s.curH  := high
            s.curHT := time
        if low < s.curL
            s.curL  := low
            s.curLT := time
    s
 
var Lvl dLvl = Lvl.new()
var Lvl wLvl = Lvl.new()
trackLvl(dLvl, lDay, showPD, cPD, "PDH", "PDL")
trackLvl(wLvl, lWeek, showPW, cPW, "PWH", "PWL")
 
if barstate.islast
    int xl = time + 3 * timeframe.in_seconds() * 1000
    label.set_x(dLvl.hb, xl)
    label.set_x(dLvl.lbb, xl)
    label.set_x(wLvl.hb, xl)
    label.set_x(wLvl.lbb, xl)
 
// ---------- Alerts (prior completed session levels) ----------
bool touchHVN = false
if lastHVN.size() > 0
    for p in lastHVN
        if high >= p and low <= p
            touchHVN := true
bool touchPOC = not na(lastPOC) and high >= lastPOC and low <= lastPOC
alertcondition(touchHVN, "Touch Prior Session HVN", "Price touched a prior session HVN")
alertcondition(touchPOC, "Touch Prior Session POC", "Price touched the prior session POC")
alertcondition(not na(dLvl.pH) and (high > dLvl.pH or low < dLvl.pL), "Trade Through PDH / PDL", "Price traded through PDH or PDL")
alertcondition(not na(wLvl.pH) and (high > wLvl.pH or low < wLvl.pL), "Trade Through PWH / PWL", "Price traded through PWH or PWL")

← 返回列表