MTF VWAP Z-Score (nvkanade)

nvkanade · study · 187 行 · 点赞 4 · 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///@version=6
// © nvkanade
// @version=6
// Multi-timeframe Z-score: how far the latest close is from its recent volume-weighted
// average, in standard deviations, on 15 min / 75 min / Day / Week.
// Non-repainting by default: each timeframe shows the value of its last COMPLETED bar.
// The average and σ come from the PREVIOUS n bars (the bar being scored is left out),
// so a Z-score is a true "how unusual is this close" measure with no built-in ceiling.
indicator("MTF Z-Score (15m / 75m / D / W)", shorttitle = "MTFZ", overlay = false, precision = 2)
 
// ───────────────────────── Inputs
string GT = "Timeframes and lookbacks"
string tf1 = input.timeframe("15", "Lower TF 1", group = GT, inline = "t1")
int n1 = input.int(20, "bars", minval = 5, group = GT, inline = "t1")
string tf2 = input.timeframe("75", "Lower TF 2", group = GT, inline = "t2")
int n2 = input.int(20, "bars", minval = 5, group = GT, inline = "t2")
string tf3 = input.timeframe("D", "Higher TF 1", group = GT, inline = "t3")
int n3 = input.int(20, "bars", minval = 5, group = GT, inline = "t3")
string tf4 = input.timeframe("W", "Higher TF 2", group = GT, inline = "t4")
int n4 = input.int(20, "bars", minval = 5, group = GT, inline = "t4")
 
string GC = "Calculation"
bool useRange = input.bool(true, "Include each bar's high–low range in σ", group = GC,
     tooltip = "Adds each bar's own spread, (high − low)² / 12, to the volume-weighted variance, so σ is not understated when bars are wide.")
bool live = input.bool(false, "Show the developing bar (repaints)", group = GC,
     tooltip = "Off (default): each timeframe shows its last completed bar, so nothing changes after the fact. On: shows the bar still forming, which moves until it closes.")
float ext = input.float(2.0, "Extreme level (σ)", minval = 0.5, step = 0.25, group = GC)
float mild = input.float(1.0, "Mild level (σ)", minval = 0.25, step = 0.25, group = GC)
 
string GD = "Display"
bool showTable = input.bool(true, "Show the summary panel", group = GD)
string tablePos = input.string("Top right", "Panel position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = GD)
color c1 = input.color(color.new(#00BCD4, 0), "Lower TF 1", group = GD, inline = "c")
color c2 = input.color(color.new(#2962FF, 0), "Lower TF 2", group = GD, inline = "c")
color c3 = input.color(color.new(#FF9800, 0), "Higher TF 1", group = GD, inline = "c")
color c4 = input.color(color.new(#9C27B0, 0), "Higher TF 2", group = GD, inline = "c")
 
// ───────────────────────── Z-score on the requested timeframe
// Mean and σ: volume-weighted, over the previous n bars (the [1] leaves the current bar out).
// Symbols with no volume (e.g. an index) fall back to equal weights.
zScore(int n) =>
    float w = nz(volume) > 0 ? nz(volume) : 1.0
    float rv = useRange ? math.pow(high - low, 2) / 12.0 : 0.0
    float sw = math.sum(w, n)
    float spw = math.sum(hlc3 * w, n)
    float sp2w = math.sum((hlc3 * hlc3 + rv) * w, n)
    float m = spw[1] / sw[1]
    float sd = math.sqrt(math.max(sp2w[1] / sw[1] - m * m, 0.0))
    sd > 0 ? (close - m) / sd : na
 
// Non-repainting fetch: value of the last completed bar of `tf` ([1] + lookahead_on).
// A timeframe lower than the chart's cannot be shown reliably, so it returns na.
getZ(string tf, int n) =>
    float zDone = request.security(syminfo.tickerid, tf, zScore(n)[1], lookahead = barmerge.lookahead_on)
    float zLive = request.security(syminfo.tickerid, tf, zScore(n), lookahead = barmerge.lookahead_off)
    bool lowerThanChart = timeframe.in_seconds(tf) < timeframe.in_seconds()
    lowerThanChart ? na : live ? zLive : zDone
 
float z1 = getZ(tf1, n1)
float z2 = getZ(tf2, n2)
float z3 = getZ(tf3, n3)
float z4 = getZ(tf4, n4)
 
// ───────────────────────── Plots
hZero = hline(0, "Zero", color.new(color.gray, 30), hline.style_dotted)
hUp1 = hline(mild, "+ mild", color.new(color.gray, 70), hline.style_dotted)
hUp2 = hline(ext, "+ extreme", color.new(color.red, 40), hline.style_dashed)
hDn1 = hline(-mild, "− mild", color.new(color.gray, 70), hline.style_dotted)
hDn2 = hline(-ext, "− extreme", color.new(color.green, 40), hline.style_dashed)
fill(hUp1, hUp2, color.new(color.red, 94), "High zone")
fill(hDn1, hDn2, color.new(color.green, 94), "Low zone")
 
plot(z1, "Z lower TF 1", c1, 1, plot.style_stepline)
plot(z2, "Z lower TF 2", c2, 1, plot.style_stepline)
plot(z3, "Z higher TF 1", c3, 2, plot.style_stepline)
plot(z4, "Z higher TF 2", c4, 2, plot.style_stepline)
 
// ───────────────────────── Reading the situation
tfName(string tf) =>
    switch tf
        "15"  => "15 min"
        "75"  => "75 min"
        "60"  => "1 hour"
        "D"   => "Day"
        "1D"  => "Day"
        "W"   => "Week"
        "1W"  => "Week"
        "M"   => "Month"
        => tf
 
zRead(float z) =>
    na(z) ? "—" : z >= ext ? "Extreme high" : z >= mild ? "High" : z <= -ext ? "Extreme low" : z <= -mild ? "Low" : "Neutral"
 
zCol(float z) =>
    na(z) ? color.new(color.gray, 80) : z >= ext ? color.new(color.red, 35) : z >= mild ? color.new(color.red, 70) : z <= -ext ? color.new(color.green, 35) : z <= -mild ? color.new(color.green, 70) : color.new(color.gray, 85)
 
// Higher-timeframe backdrop and lower-timeframe stretch
float hA = nz(z3, nz(z4))
float hB = nz(z4, nz(z3))
bool haveHigher = not na(z3) or not na(z4)
int bias = not haveHigher ? 0 : hA > 0 and hB > 0 ? 1 : hA < 0 and hB < 0 ? -1 : 0
float loMin = math.min(nz(z1, 0.0), nz(z2, 0.0))
float loMax = math.max(nz(z1, 0.0), nz(z2, 0.0))
 
int nOk = 0
int nHi = 0
int nLo = 0
for zv in array.from(z1, z2, z3, z4)
    if not na(zv)
        nOk += 1
        nHi += zv >= ext ? 1 : 0
        nLo += zv <= -ext ? 1 : 0
 
string xs = str.tostring(ext) + "σ"
string head = ""
string detail = ""
color headCol = color.new(color.gray, 60)
if nOk >= 3 and nHi == nOk
    head := "OVERSTRETCHED UP"
    detail := "Every timeframe ≥ +" + xs + ": late longs risky, watch for a stall"
    headCol := color.new(color.orange, 30)
else if nOk >= 3 and nLo == nOk
    head := "OVERSTRETCHED DOWN"
    detail := "Every timeframe ≤ −" + xs + ": late shorts risky, watch for a bounce"
    headCol := color.new(color.orange, 30)
else if bias == 1 and loMin <= -ext
    head := "DIP IN AN UPTREND"
    detail := "Higher TFs up, a lower TF ≤ −" + xs + ": pullback-buy zone"
    headCol := color.new(color.green, 30)
else if bias == -1 and loMax >= ext
    head := "RALLY IN A DOWNTREND"
    detail := "Higher TFs down, a lower TF ≥ +" + xs + ": fade-the-rally zone"
    headCol := color.new(color.red, 30)
else if bias == 1 and loMax >= ext
    head := "UPTREND, SHORT-TERM HOT"
    detail := "Higher TFs up, a lower TF ≥ +" + xs + ": strong but extended"
    headCol := color.new(color.teal, 30)
else if bias == -1 and loMin <= -ext
    head := "DOWNTREND, SHORT-TERM FLUSH"
    detail := "Higher TFs down, a lower TF ≤ −" + xs + ": weak but extended"
    headCol := color.new(color.maroon, 30)
else if bias == 1
    head := "UPTREND"
    detail := "Higher TFs above their averages; lower TFs calm"
    headCol := color.new(color.green, 55)
else if bias == -1
    head := "DOWNTREND"
    detail := "Higher TFs below their averages; lower TFs calm"
    headCol := color.new(color.red, 55)
else if loMax >= ext or loMin <= -ext
    head := loMax >= ext ? "MIXED, SHORT-TERM HOT" : "MIXED, SHORT-TERM WASHED OUT"
    detail := "Higher TFs disagree: no clear backdrop"
else
    head := "NO CLEAR SETUP"
    detail := "Higher TFs disagree; lower TFs calm"
 
// ───────────────────────── Summary panel
pos = switch tablePos
    "Top left"     => position.top_left
    "Bottom right" => position.bottom_right
    "Bottom left"  => position.bottom_left
    => position.top_right
 
var table tb = table.new(pos, 3, 8, border_width = 1, border_color = color.new(color.gray, 70))
if barstate.islast and showTable
    color hdr = color.new(color.gray, 75)
    table.cell(tb, 0, 0, "Timeframe", text_color = chart.fg_color, bgcolor = hdr, text_size = size.small)
    table.cell(tb, 1, 0, "Z", text_color = chart.fg_color, bgcolor = hdr, text_size = size.small)
    table.cell(tb, 2, 0, "Read", text_color = chart.fg_color, bgcolor = hdr, text_size = size.small)
    array<string> names = array.from(tfName(tf1), tfName(tf2), tfName(tf3), tfName(tf4))
    array<float> zs = array.from(z1, z2, z3, z4)
    for i = 0 to 3
        float zz = zs.get(i)
        string zTxt = na(zz) ? "—" : (zz >= 0 ? "+" : "") + str.tostring(zz, "0.00")
        table.cell(tb, 0, i + 1, names.get(i), text_color = chart.fg_color, text_size = size.small, text_halign = text.align_left)
        table.cell(tb, 1, i + 1, zTxt, text_color = chart.fg_color, bgcolor = zCol(zz), text_size = size.small)
        table.cell(tb, 2, i + 1, zRead(zz), text_color = chart.fg_color, bgcolor = zCol(zz), text_size = size.small)
    table.cell(tb, 0, 5, head, text_color = color.white, bgcolor = headCol, text_size = size.small)
    table.merge_cells(tb, 0, 5, 2, 5)
    table.cell(tb, 0, 6, detail, text_color = chart.fg_color, text_size = size.small)
    table.merge_cells(tb, 0, 6, 2, 6)
    table.cell(tb, 0, 7, "Context only, not a tested signal · " + (live ? "live bar (repaints)" : "completed bars"), text_color = color.new(chart.fg_color, 40), text_size = size.tiny)
    table.merge_cells(tb, 0, 7, 2, 7)
 
// ───────────────────────── Alerts (fire only on completed bars unless 'live' is on)
alertcondition(bias == 1 and loMin <= -ext and not (bias[1] == 1 and loMin[1] <= -ext), "Dip in an uptrend", "{{ticker}}: higher timeframes up, a lower timeframe is at an extreme low Z")
alertcondition(bias == -1 and loMax >= ext and not (bias[1] == -1 and loMax[1] >= ext), "Rally in a downtrend", "{{ticker}}: higher timeframes down, a lower timeframe is at an extreme high Z")

← 返回列表