Wave Time Bands

uezokazu · study · 175 行 · 点赞 29 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// (c) K'u Hero
//@version=6
// Wave Time Bands  v1.0
// For each zigzag wave, measures the time it took (bars) or its speed (range / bars) and compares it
// with the mean +/- standard deviation of the last N waves. The pane is in sigma units (0 = mean, +/-1, +/-2).
// Statistics are taken on the logarithm of the value (corrects the skew between short and long waves).
// Note: the current (unfinished) wave updates on every tick until the wave ends; completed-wave dots are fixed.
// Display only. This is not a buy/sell signal.
indicator("Wave Time Bands", shorttitle = "Wave Time Bands", overlay = false, max_lines_count = 500, max_labels_count = 500)
 
// ===== Inputs =====
sens   = input.string("Standard", "Wave sensitivity", options = ["Sensitive", "Standard", "Conservative"], tooltip = "Size of a reversal that ends a wave (ATR multiple: 1.5 / 2.5 / 4.0). Sensitive = counts small waves too, Conservative = only large waves.")
metric = input.string("Time (bars)", "Measure", options = ["Time (bars)", "Speed (range / bars)"])
peer   = input.string("Same-direction waves", "Compare with", options = ["Same-direction waves", "All waves"], tooltip = "Same-direction waves = up waves are compared with past up waves, down waves with past down waves.")
nLegs  = input.int(20, "Number of waves to compare", minval = 5, maxval = 200)
showZZ = input.bool(true, "Show waves and bar counts on the chart")
tblPos = input.string("Top right", "Table position", options = ["Top right", "Middle right", "Bottom right", "Top left", "Bottom left"], display = display.none)
 
// ===== Constants =====
ATR_LEN  = 14
MIN_LEGS = 5
mult     = sens == "Sensitive" ? 1.5 : sens == "Standard" ? 2.5 : 4.0
isTime   = metric == "Time (bars)"
sameDir  = peer == "Same-direction waves"
atr      = ta.atr(ATR_LEN)
UP_COL   = color.new(#26a69a, 0)
DN_COL   = color.new(#ef5350, 0)
 
// ===== Functions =====
f_push(array<float> a, float v, int n) =>
    a.push(v)
    while a.size() > n
        a.shift()
    a.size()
 
// value of a wave (time = bars / speed = range / bars)
f_val(float p0, float p1, int bars) =>
    b = math.max(bars, 1)
    isTime ? float(b) : math.abs(p1 - p0) / b
 
f_z(array<float> a, float logV) =>
    float z = na
    if a.size() >= MIN_LEGS
        s = a.stdev()
        if s > 0
            z := (logV - a.avg()) / s
    z
 
// ===== Zigzag (a wave ends when price comes back ATR x sensitivity) =====
var int   dir    = 0
var float startP = na
var int   startB = na
var float extP   = na
var int   extB   = na
var int   legCnt = 0
var line  curLn  = na
var array<float> upLog  = array.new<float>()
var array<float> dnLog  = array.new<float>()
var array<float> allLog = array.new<float>()
 
float doneZ   = na
int   doneDir = 0
 
if not na(atr)
    if dir == 0
        dir    := close >= open ? 1 : -1
        startP := dir == 1 ? low : high
        startB := bar_index
        extP   := dir == 1 ? high : low
        extB   := bar_index
    else
        bool newExt = dir == 1 ? high >= extP : low <= extP
        bool rev    = dir == 1 ? extP - low >= mult * atr : high - extP >= mult * atr
        if newExt
            extP := dir == 1 ? high : low
            extB := bar_index
        else if rev
            legCnt += 1
            // the first wave has an inaccurate start, so it is not used in the statistics
            if legCnt > 1
                logV = math.log(math.max(f_val(startP, extP, extB - startB), 1e-10))
                if sameDir
                    doneZ := f_z(dir == 1 ? upLog : dnLog, logV)
                else
                    doneZ := f_z(allLog, logV)
                doneDir := dir
                if dir == 1
                    f_push(upLog, logV, nLegs)
                else
                    f_push(dnLog, logV, nLegs)
                f_push(allLog, logV, nLegs)
            if showZZ and not na(curLn)
                line.set_xy2(curLn, extB, extP)
                label.new(extB, extP, str.tostring(extB - startB), style = dir == 1 ? label.style_label_down : label.style_label_up, color = color.new(color.black, 100), textcolor = dir == 1 ? UP_COL : DN_COL, size = size.small, force_overlay = true)
                curLn := na
            startP := extP
            startB := extB
            dir    := -dir
            extP   := dir == 1 ? high : low
            extB   := bar_index
 
    if showZZ
        if na(curLn)
            curLn := line.new(startB, startP, extB, extP, color = dir == 1 ? UP_COL : DN_COL, width = 2, force_overlay = true)
        else
            line.set_xy2(curLn, extB, extP)
 
// ===== Current wave =====
// Time : bars from the start of the wave to now (sideways time is counted too)
// Speed: range from the start to the extreme / bars
int   curBars = bar_index - startB
float curVal  = na(startB) ? na : isTime ? float(math.max(curBars, 1)) : f_val(startP, extP, extB - startB)
 
float m = na
float s = na
int   nRef = 0
if not na(curVal)
    array<float> ref = allLog
    if sameDir
        if dir == 1
            ref := upLog
        else
            ref := dnLog
    nRef := ref.size()
    if nRef >= MIN_LEGS
        m := ref.avg()
        s := ref.stdev()
 
float z = na(m) or s == 0 ? na : (math.log(math.max(curVal, 1e-10)) - m) / s
 
// ===== Plots (sigma units) =====
h2u = hline(2,  "+2σ", color = color.new(color.orange, 30), linestyle = hline.style_dashed)
h1u = hline(1,  "+1σ", color = color.new(color.gray, 50), linestyle = hline.style_dotted)
hline(0,        "Mean", color = color.new(color.gray, 20))
h1d = hline(-1, "-1σ", color = color.new(color.gray, 50), linestyle = hline.style_dotted)
h2d = hline(-2, "-2σ", color = color.new(color.aqua, 30), linestyle = hline.style_dashed)
fill(h1u, h1d, color = color.new(color.gray, 92), title = "±1σ")
 
plot(z, "Current wave", color = dir == 1 ? UP_COL : DN_COL, linewidth = 2, style = plot.style_linebr)
plot(doneZ, "Completed wave", color = doneDir == 1 ? UP_COL : DN_COL, style = plot.style_circles, linewidth = 4)
 
// ===== Table =====
f_fmt(float v) =>
    na(v) ? "-" : isTime ? str.tostring(v, "#") + " bars" : str.tostring(v / syminfo.mintick, "#.#") + " ticks/bar"
 
f_judge(float zz) =>
    string t = "Not enough data"
    if not na(zz)
        if isTime
            t := zz >= 2 ? "Unusually long (> +2σ)" : zz >= 1 ? "Longer than usual" : zz >= -1 ? "Average" : "Still short"
        else
            t := zz >= 2 ? "Unusually fast (expanding)" : zz >= 1 ? "Fast" : zz >= -1 ? "Average" : "Slow (contracting)"
    t
 
f_pos(string p) =>
    p == "Middle right" ? position.middle_right : p == "Bottom right" ? position.bottom_right : p == "Top left" ? position.top_left : p == "Bottom left" ? position.bottom_left : position.top_right
 
var table tb = table.new(f_pos(tblPos), 2, 5, bgcolor = color.new(color.black, 30), border_width = 1)
if barstate.islast
    txt = color.white
    table.cell(tb, 0, 0, "Current wave", text_color = txt, text_size = size.small)
    table.cell(tb, 1, 0, dir == 1 ? "Up" : "Down", text_color = dir == 1 ? UP_COL : DN_COL, text_size = size.small)
    table.cell(tb, 0, 1, isTime ? "Elapsed" : "Speed", text_color = txt, text_size = size.small)
    table.cell(tb, 1, 1, f_fmt(curVal), text_color = txt, text_size = size.small)
    table.cell(tb, 0, 2, "Mean (" + str.tostring(nRef) + " waves)", text_color = txt, text_size = size.small)
    table.cell(tb, 1, 2, na(m) ? "-" : f_fmt(math.exp(m)), text_color = txt, text_size = size.small)
    table.cell(tb, 0, 3, "+2σ", text_color = txt, text_size = size.small)
    table.cell(tb, 1, 3, na(m) ? "-" : f_fmt(math.exp(m + 2 * s)), text_color = txt, text_size = size.small)
    table.cell(tb, 0, 4, "Status", text_color = txt, text_size = size.small)
    table.cell(tb, 1, 4, f_judge(z) + (na(z) ? "" : "  " + str.tostring(z, "+0.0;-0.0") + "σ"), text_color = txt, text_size = size.small)
 
// ===== Alerts =====
alertcondition(ta.crossover(z, 2),  "Wave above +2σ", "Wave Time Bands: the current wave went above +2σ of past waves")
alertcondition(ta.crossunder(z, -2), "Wave below -2σ", "Wave Time Bands: the current wave went below -2σ of past waves")

← 返回列表