本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Multi-Period Volume Profile Levels", shorttitle = "MPVP Levels", overlay = true, max_lines_count = 60, max_labels_count = 60)
// =====================================================================
// Constants
// =====================================================================
int DAY_MS = 86400000
// =====================================================================
// General settings
// =====================================================================
string G0 = "General"
iMode = input.string("Exact", "Period mode", options = ["Exact", "Start of week"], group = G0,
tooltip = "Exact: rolling windows (7 / 14 calendar days, 1 / 3 calendar months) back from today's session open, snapped to the nearest daily open.\n\nStart of week: 7D starts at last week's open, 2W at the open two weeks ago, 1M at last month's open, 3M at the open three months ago. Each window grows through the period and resets at the next open.")
iVA = input.float(70.0, "Value area volume %", minval = 10, maxval = 100, step = 1, group = G0)
iRows = input.int(24, "Profile rows", minval = 10, maxval = 1000, group = G0,
tooltip = "Equivalent to 'Number of rows' in TradingView's Fixed Range Volume Profile (default 24). More rows gives finer, slightly different levels.")
iCalcTF = input.timeframe("30", "Calculation timeframe", group = G0,
tooltip = "Bars used to build the profiles. Lower = more precise but less history available. If the 3M levels show '(partial)', raise this (e.g. 60). If the chart timeframe is higher than this, the chart timeframe is used.")
iWkCustom = input.bool(false, "Custom week open (Sunday, UK time)", inline = "wk", group = G0,
tooltip = "Off: uses the symbol's own weekly session open (FX opens Sunday evening UK time). On: forces the week to start on Sunday at the hour:minute given, UK time. Useful for 24/7 markets such as crypto.")
iWkHour = input.int(22, "", minval = 0, maxval = 23, inline = "wk", group = G0)
iWkMin = input.int(0, ":", minval = 0, maxval = 59, inline = "wk", group = G0)
iExtend = input.bool(true, "Extend lines right", group = G0)
string GL = "Labels"
iLabels = input.bool(true, "Show labels", inline = "lbl", group = GL)
iPrices = input.bool(false, "Include price in text", inline = "lbl", group = GL)
iScale = input.bool(true, "Price scale value badges", group = GL,
tooltip = "Shows each level's price as a coloured badge on the price scale, like the current price. To also show the name on the badge, right-click the price scale > Labels > tick 'Indicators and financials name labels'.")
iLblStyle = input.string("Filled", "Style", options = ["Filled", "Text only"], inline = "lbs", group = GL,
tooltip = "Filled: a box in the set's colour, centred on the line. Text only: coloured text centred on the line.")
iLblSize = input.string("Normal", "Size", options = ["Tiny", "Small", "Normal", "Large"], inline = "lbs", group = GL)
iLblOff = input.int(30, "Label offset (candles to the right)", minval = 0, maxval = 500, step = 5, group = GL,
tooltip = "How many candles to the right of the latest candle the labels sit. Set it to match your usual right margin. When you scroll back so the latest candle is off screen, labels pin to the right edge instead.")
// =====================================================================
// Per-period style sets
// =====================================================================
string G1 = "7 Day"
s1On = input.bool(true, "Show", inline = "s1a", group = G1)
s1Col = input.color(#26C6DA, "", inline = "s1a", group = G1)
s1W = input.int(1, "Width", minval = 1, maxval = 5, inline = "s1a", group = G1)
s1Sty = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], inline = "s1a", group = G1)
s1Min = input.timeframe("1", "Chart TFs from", inline = "s1b", group = G1)
s1Max = input.timeframe("1W", "to", inline = "s1b", group = G1)
s1Lv = input.string("POC, VAH & VAL", "Levels", options = ["POC, VAH & VAL", "POC only", "VAH & VAL only"], group = G1)
string G2 = "2 Week"
s2On = input.bool(true, "Show", inline = "s2a", group = G2)
s2Col = input.color(#FFA726, "", inline = "s2a", group = G2)
s2W = input.int(1, "Width", minval = 1, maxval = 5, inline = "s2a", group = G2)
s2Sty = input.string("Dashed", "", options = ["Solid", "Dashed", "Dotted"], inline = "s2a", group = G2)
s2Min = input.timeframe("1", "Chart TFs from", inline = "s2b", group = G2)
s2Max = input.timeframe("1W", "to", inline = "s2b", group = G2)
s2Lv = input.string("POC, VAH & VAL", "Levels", options = ["POC, VAH & VAL", "POC only", "VAH & VAL only"], group = G2)
string G3 = "1 Month"
s3On = input.bool(true, "Show", inline = "s3a", group = G3)
s3Col = input.color(#AB47BC, "", inline = "s3a", group = G3)
s3W = input.int(2, "Width", minval = 1, maxval = 5, inline = "s3a", group = G3)
s3Sty = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], inline = "s3a", group = G3)
s3Min = input.timeframe("1", "Chart TFs from", inline = "s3b", group = G3)
s3Max = input.timeframe("1W", "to", inline = "s3b", group = G3)
s3Lv = input.string("POC, VAH & VAL", "Levels", options = ["POC, VAH & VAL", "POC only", "VAH & VAL only"], group = G3)
string G4 = "3 Month"
s4On = input.bool(true, "Show", inline = "s4a", group = G4)
s4Col = input.color(#EF5350, "", inline = "s4a", group = G4)
s4W = input.int(3, "Width", minval = 1, maxval = 5, inline = "s4a", group = G4)
s4Sty = input.string("Dotted", "", options = ["Solid", "Dashed", "Dotted"], inline = "s4a", group = G4)
s4Min = input.timeframe("1", "Chart TFs from", inline = "s4b", group = G4)
s4Max = input.timeframe("1W", "to", inline = "s4b", group = G4)
s4Lv = input.string("POC, VAH & VAL", "Levels", options = ["POC, VAH & VAL", "POC only", "VAH & VAL only"], group = G4)
// =====================================================================
// Helpers (date maths)
// =====================================================================
f_dim(int y, int m) =>
m == 2 ? ((y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)) ? 29 : 28) : (m == 4 or m == 6 or m == 9 or m == 11) ? 30 : 31
// Same day/time n calendar months earlier (exchange timezone)
f_monthsBack(int t, int n) =>
int y = year(t)
int m = month(t) - n
while m < 1
m += 12
y -= 1
int d = math.min(dayofmonth(t), f_dim(y, m))
timestamp(y, m, d, hour(t), minute(t))
// Earliest daily open at or after target (3h tolerance absorbs DST shifts). opens is newest-first.
f_snap(array<int> opens, int target) =>
int res = na
int tol = target - 3 * 3600000
for t in opens
if t >= tol
res := t
else
break
res
f_exact(array<int> opens, int target, int first) =>
target < first ? int(na) : f_snap(opens, target)
// Key identifying the custom week (Sunday hh:mm UK time), DST safe
f_customWeekKey(int t, int hh, int mm) =>
string tz = "Europe/London"
int noon = timestamp(tz, year(t, tz), month(t, tz), dayofmonth(t, tz), 12, 0)
int sun = noon - (dayofweek(t, tz) - 1) * DAY_MS
int a = timestamp(tz, year(sun, tz), month(sun, tz), dayofmonth(sun, tz), hh, mm)
if t < a
sun -= 7 * DAY_MS
a := timestamp(tz, year(sun, tz), month(sun, tz), dayofmonth(sun, tz), hh, mm)
a
// =====================================================================
// Volume profile: returns [POC, VAH, VAL] for bars with time >= startT
// =====================================================================
f_profile(array<int> bT, array<float> bH, array<float> bL, array<float> bV, int startT, int rows, float vaPct, bool run) =>
float poc = na
float vah = na
float val = na
int n = bT.size()
if run and not na(startT) and n > 0
int i0 = n
for i = n - 1 to 0
if bT.get(i) >= startT
i0 := i
else
break
if i0 < n
float hi = bH.get(i0)
float lo = bL.get(i0)
for i = i0 to n - 1
hi := math.max(hi, bH.get(i))
lo := math.min(lo, bL.get(i))
if hi > lo
float step = (hi - lo) / rows
array<float> vols = array.new<float>(rows, 0.0)
for i = i0 to n - 1
float h = bH.get(i)
float l = bL.get(i)
float v = bV.get(i)
if v > 0
int r1 = math.max(0, math.min(rows - 1, math.floor((l - lo) / step)))
int r2 = math.max(0, math.min(rows - 1, math.floor((h - lo) / step)))
if r1 == r2
vols.set(r1, vols.get(r1) + v)
else
float rng = h - l
for r = r1 to r2
float rb = lo + r * step
float ov = math.min(h, rb + step) - math.max(l, rb)
if ov > 0
vols.set(r, vols.get(r) + v * ov / rng)
float total = vols.sum()
if total > 0
int pocRow = vols.indexof(vols.max())
float target = total * vaPct / 100
int up = pocRow
int dn = pocRow
float acc = vols.get(pocRow)
while acc < target and (up < rows - 1 or dn > 0)
float vUp = up < rows - 1 ? vols.get(up + 1) : -1.0
float vDn = dn > 0 ? vols.get(dn - 1) : -1.0
if vUp >= vDn
up += 1
acc += vUp
else
dn -= 1
acc += vDn
poc := lo + (pocRow + 0.5) * step
vah := lo + (up + 1) * step
val := lo + dn * step
[poc, vah, val]
// =====================================================================
// Runs on the calculation timeframe: stores bars, tracks opens,
// builds the four profiles on the last bar only
// =====================================================================
f_calc() =>
var array<int> bT = array.new<int>()
var array<float> bH = array.new<float>()
var array<float> bL = array.new<float>()
var array<float> bV = array.new<float>()
var array<int> dOpen = array.new<int>()
var array<int> wOpen = array.new<int>()
var array<int> mOpen = array.new<int>()
bT.push(time)
bH.push(high)
bL.push(low)
bV.push(nz(volume))
int cutoff = time - 150 * DAY_MS
while bT.size() > 0 and bT.get(0) < cutoff
bT.shift()
bH.shift()
bL.shift()
bV.shift()
int dKey = time("D")
int wKey = iWkCustom ? f_customWeekKey(time, iWkHour, iWkMin) : time("W")
int mKey = time("M")
if not na(dKey[1]) and dKey != dKey[1]
dOpen.unshift(time)
if dOpen.size() > 200
dOpen.pop()
if not na(wKey[1]) and wKey != wKey[1]
wOpen.unshift(time)
if wOpen.size() > 30
wOpen.pop()
if not na(mKey[1]) and mKey != mKey[1]
mOpen.unshift(time)
if mOpen.size() > 12
mOpen.pop()
bool run = barstate.islast
int first = bT.size() > 0 ? bT.get(0) : time
int base = dOpen.size() > 0 ? dOpen.get(0) : time
int a1 = na
int a2 = na
int a3 = na
int a4 = na
if run
if iMode == "Exact"
a1 := f_exact(dOpen, base - 7 * DAY_MS, first)
a2 := f_exact(dOpen, base - 14 * DAY_MS, first)
a3 := f_exact(dOpen, f_monthsBack(base, 1), first)
a4 := f_exact(dOpen, f_monthsBack(base, 3), first)
else
a1 := wOpen.size() > 1 ? wOpen.get(1) : na
a2 := wOpen.size() > 2 ? wOpen.get(2) : na
a3 := mOpen.size() > 1 ? mOpen.get(1) : na
a4 := mOpen.size() > 3 ? mOpen.get(3) : na
// Partial = not enough history to cover the full window
bool x1 = run and (na(a1) or a1 < first)
bool x2 = run and (na(a2) or a2 < first)
bool x3 = run and (na(a3) or a3 < first)
bool x4 = run and (na(a4) or a4 < first)
int s1 = run ? (x1 ? first : a1) : na
int s2 = run ? (x2 ? first : a2) : na
int s3 = run ? (x3 ? first : a3) : na
int s4 = run ? (x4 ? first : a4) : na
[p1, h1, l1] = f_profile(bT, bH, bL, bV, s1, iRows, iVA, run)
[p2, h2, l2] = f_profile(bT, bH, bL, bV, s2, iRows, iVA, run)
[p3, h3, l3] = f_profile(bT, bH, bL, bV, s3, iRows, iVA, run)
[p4, h4, l4] = f_profile(bT, bH, bL, bV, s4, iRows, iVA, run)
[p1, h1, l1, s1, x1, p2, h2, l2, s2, x2, p3, h3, l3, s3, x3, p4, h4, l4, s4, x4]
// =====================================================================
// Request data
// =====================================================================
string calcTF = timeframe.in_seconds() > timeframe.in_seconds(iCalcTF) ? timeframe.period : iCalcTF
[p1, h1, l1, s1, x1, p2, h2, l2, s2, x2, p3, h3, l3, s3, x3, p4, h4, l4, s4, x4] = request.security(syminfo.tickerid, calcTF, f_calc(), lookahead = barmerge.lookahead_on)
// =====================================================================
// Drawing
// =====================================================================
var array<line> gLines = array.new<line>()
var array<label> gLabels = array.new<label>()
int tfMs = timeframe.in_seconds() * 1000
f_style(string s) =>
s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid
f_tfOk(string tfMin, string tfMax) =>
int s = timeframe.in_seconds()
s >= timeframe.in_seconds(tfMin) and s <= timeframe.in_seconds(tfMax)
// Black or white text, whichever reads better on the fill colour
f_contrast(color c) =>
(0.299 * color.r(c) + 0.587 * color.g(c) + 0.114 * color.b(c)) > 150 ? color.black : color.white
f_size() =>
iLblSize == "Tiny" ? size.tiny : iLblSize == "Large" ? size.large : iLblSize == "Normal" ? size.normal : size.small
// Line from the period start, extended right, plus a label centred on the line.
// Label x: N bars right of the last candle. If you scroll back so the last candle
// is off screen, it pins to the right edge of the visible chart instead.
f_level(int x1, float y, color c, int w, string sty, string txt) =>
if not na(y) and not na(x1)
gLines.push(line.new(x1, y, time, y, xloc = xloc.bar_time, extend = iExtend ? extend.right : extend.none, color = c, width = w, style = f_style(sty)))
if iLabels
string t = iPrices ? txt + " " + str.tostring(y, format.mintick) : txt
int rvt = chart.right_visible_bar_time
bool scrolled = not na(rvt) and rvt < time
int lx = scrolled ? rvt : time + iLblOff * tfMs
bool filled = iLblStyle == "Filled"
gLabels.push(label.new(lx, y, t, xloc = xloc.bar_time,
style = filled ? (scrolled ? label.style_label_right : label.style_label_left) : label.style_none,
color = filled ? c : color.new(color.black, 100),
textcolor = filled ? f_contrast(c) : c,
textalign = scrolled ? text.align_right : text.align_left, size = f_size()))
f_set(bool on, string tfMin, string tfMax, string lv, string name, float poc, float vah, float val, int x1, bool part, color c, int w, string sty) =>
if on and f_tfOk(tfMin, tfMax)
string sfx = part ? " (partial)" : ""
if lv != "VAH & VAL only"
f_level(x1, poc, c, w, sty, "POC " + name + sfx)
if lv != "POC only"
f_level(x1, vah, c, w, sty, "VAH " + name + sfx)
f_level(x1, val, c, w, sty, "VAL " + name + sfx)
if barstate.islast
for ln in gLines
ln.delete()
gLines.clear()
for lb in gLabels
lb.delete()
gLabels.clear()
f_set(s1On, s1Min, s1Max, s1Lv, "7D", p1, h1, l1, s1, x1, s1Col, s1W, s1Sty)
f_set(s2On, s2Min, s2Max, s2Lv, "2wk", p2, h2, l2, s2, x2, s2Col, s2W, s2Sty)
f_set(s3On, s3Min, s3Max, s3Lv, "1M", p3, h3, l3, s3, x3, s3Col, s3W, s3Sty)
f_set(s4On, s4Min, s4Max, s4Lv, "3M", p4, h4, l4, s4, x4, s4Col, s4W, s4Sty)
// =====================================================================
// Right-edge labels on the price scale (no line drawn by these plots)
// =====================================================================
bool onScale = iScale
bool v1 = onScale and s1On and f_tfOk(s1Min, s1Max)
bool v2 = onScale and s2On and f_tfOk(s2Min, s2Max)
bool v3 = onScale and s3On and f_tfOk(s3Min, s3Max)
bool v4 = onScale and s4On and f_tfOk(s4Min, s4Max)
plot(v1 and s1Lv != "VAH & VAL only" ? p1 : na, "POC 7D", s1Col, display = display.price_scale, editable = false)
plot(v1 and s1Lv != "POC only" ? h1 : na, "VAH 7D", s1Col, display = display.price_scale, editable = false)
plot(v1 and s1Lv != "POC only" ? l1 : na, "VAL 7D", s1Col, display = display.price_scale, editable = false)
plot(v2 and s2Lv != "VAH & VAL only" ? p2 : na, "POC 2wk", s2Col, display = display.price_scale, editable = false)
plot(v2 and s2Lv != "POC only" ? h2 : na, "VAH 2wk", s2Col, display = display.price_scale, editable = false)
plot(v2 and s2Lv != "POC only" ? l2 : na, "VAL 2wk", s2Col, display = display.price_scale, editable = false)
plot(v3 and s3Lv != "VAH & VAL only" ? p3 : na, "POC 1M", s3Col, display = display.price_scale, editable = false)
plot(v3 and s3Lv != "POC only" ? h3 : na, "VAH 1M", s3Col, display = display.price_scale, editable = false)
plot(v3 and s3Lv != "POC only" ? l3 : na, "VAL 1M", s3Col, display = display.price_scale, editable = false)
plot(v4 and s4Lv != "VAH & VAL only" ? p4 : na, "POC 3M", s4Col, display = display.price_scale, editable = false)
plot(v4 and s4Lv != "POC only" ? h4 : na, "VAH 3M", s4Col, display = display.price_scale, editable = false)
plot(v4 and s4Lv != "POC only" ? l4 : na, "VAL 3M", s4Col, display = display.price_scale, editable = false)
// =====================================================================
// Alerts: one alert covers every level.
// Create Alert > Condition: MPVP Levels > "Any alert() function call"
// =====================================================================
string GA = "Alerts"
aPoc = input.bool(true, "Alert on POC touch", group = GA)
aVA = input.bool(true, "Alert on VAH / VAL touch", group = GA)
aVis = input.bool(true, "Only levels shown on this chart", group = GA,
tooltip = "On: only levels currently displayed (period switched on, chart timeframe in its range, and that level type selected) can trigger. Off: all twelve levels can trigger.")
// Touch = this bar's range reaches the level and the previous bar's didn't,
// so it re-arms once price moves away rather than firing on every bar it sits there
f_touch(float y) =>
not na(y) and high >= y and low <= y and not (high[1] >= y and low[1] <= y)
f_hit(bool want, bool vis, float y, string name, array<string> fired) =>
bool t = f_touch(y)
string out = ""
if want and (vis or not aVis) and t and not fired.includes(name)
fired.push(name)
out := name + " " + str.tostring(y, format.mintick)
out
var array<string> aFired = array.new<string>()
if barstate.isnew
aFired.clear()
bool w1 = s1On and f_tfOk(s1Min, s1Max)
bool w2 = s2On and f_tfOk(s2Min, s2Max)
bool w3 = s3On and f_tfOk(s3Min, s3Max)
bool w4 = s4On and f_tfOk(s4Min, s4Max)
array<string> hits = array.new<string>()
hits.push(f_hit(aPoc, w1 and s1Lv != "VAH & VAL only", p1, "POC 7D", aFired))
hits.push(f_hit(aVA, w1 and s1Lv != "POC only", h1, "VAH 7D", aFired))
hits.push(f_hit(aVA, w1 and s1Lv != "POC only", l1, "VAL 7D", aFired))
hits.push(f_hit(aPoc, w2 and s2Lv != "VAH & VAL only", p2, "POC 2wk", aFired))
hits.push(f_hit(aVA, w2 and s2Lv != "POC only", h2, "VAH 2wk", aFired))
hits.push(f_hit(aVA, w2 and s2Lv != "POC only", l2, "VAL 2wk", aFired))
hits.push(f_hit(aPoc, w3 and s3Lv != "VAH & VAL only", p3, "POC 1M", aFired))
hits.push(f_hit(aVA, w3 and s3Lv != "POC only", h3, "VAH 1M", aFired))
hits.push(f_hit(aVA, w3 and s3Lv != "POC only", l3, "VAL 1M", aFired))
hits.push(f_hit(aPoc, w4 and s4Lv != "VAH & VAL only", p4, "POC 3M", aFired))
hits.push(f_hit(aVA, w4 and s4Lv != "POC only", h4, "VAH 3M", aFired))
hits.push(f_hit(aVA, w4 and s4Lv != "POC only", l4, "VAL 3M", aFired))
array<string> msgs = array.new<string>()
for m in hits
if m != ""
msgs.push(m)
if msgs.size() > 0
alert(syminfo.ticker + " (" + timeframe.period + "): price touched " + msgs.join(", "), alert.freq_all)